#!/usr/bin/env python3
"""Public reproduction of the Poly Tick Tape TWAP60 guide statistics.

Adapted from scripts/twap60-flips.py; calculation and Gamma-check logic retained.
Python 3 standard library only. No account, credentials or network needed for build.

Layout: DATA/YYYY-MM-DD/btc-{price,twap60}-YYYY-MM-DD.jsonl.gz
Use exactly 2026-08-14 through 2026-10-18 to reproduce the published snapshot.
Both streams must exist for every day; scanning stops at the first incomplete day.
Full daily archives are available through https://polyticktape.com/docs/ and pricing;
the free ten-minute sample cannot reproduce the full-period statistics.

python3 -I twap60-flips.py build DATA --output rebuilt.json
python3 -I twap60-flips.py gamma --output rebuilt.json

build overwrites the output and retains an existing Gamma check only if flipRounds
is unchanged. gamma queries the public Polymarket Gamma API for every flipped round
and overwrites the check with today's results. Historical check: 2026-10-19.
The fixed chart round requires the full period (including 2026-10-08).
Missing boundaries are excluded, never filled. The final midnight-ending round is
excluded before boundary checks. Missing counts by stream overlap. The naive mean
uses available rows in [t-59,t], even when fewer than 60 exist; it is diagnostic,
not a reconstruction of Chainlink's calculation. Duplicate timestamps use the last
row, matching the original script. Decimal comparisons use Python's default context.
"""
import argparse
import gzip
import json
import os
import statistics
import sys
import time
import urllib.error
import urllib.request
from datetime import date, datetime, timedelta, timezone
from concurrent.futures import ThreadPoolExecutor
from decimal import Decimal

FIRST = date(2026, 8, 14)
ROUND = 300
CHART = 1791473700
STREAMS = ("price", "twap60")
OUT = None


def load(path):
    """{ts: (p as Decimal, v)} for one file."""
    rows = {}
    with gzip.open(path, "rt") as f:
        for line in f:
            o = json.loads(line)
            rows[o["ts"]] = (Decimal(o["p"]), o["v"])
    return rows


def days_in(root):
    out = []
    d = FIRST
    while all(os.path.exists(os.path.join(root, d.isoformat(), f"btc-{s}-{d}.jsonl.gz")) for s in STREAMS):
        out.append(d)
        d += timedelta(days=1)
    return out


def epoch(d):
    return int(datetime(d.year, d.month, d.day, tzinfo=timezone.utc).timestamp())


def pct(xs, q):
    xs = sorted(xs)
    return xs[min(len(xs) - 1, int(q * len(xs)))]


def money(x):
    return float(round(x, 2))


def build(root):
    days = days_in(root)
    if not days:
        sys.exit(f"no days in {root}")
    data = {s: {} for s in STREAMS}
    for d in days:
        for s in STREAMS:
            data[s].update(load(os.path.join(root, d.isoformat(), f"btc-{s}-{d}.jsonl.gz")))
        print(f"loaded {d}", file=sys.stderr)
    price, twap = data["price"], data["twap60"]

    first, end = epoch(days[0]), epoch(days[-1]) + 86400
    # Rounds whose end second is in DIR: all but the last one of the last day.
    starts = range(first, end - ROUND, ROUND)
    rounds = []  # (start, twap open, twap close, price open, price close)
    missing = {"twap60": 0, "price": 0}
    for start in starts:
        b = (start, start + ROUND)
        ok = True
        for name, rows in (("twap60", twap), ("price", price)):
            if not all(t in rows for t in b):
                missing[name] += 1
                ok = False
        if ok:
            rounds.append((start, twap[b[0]][0], twap[b[1]][0], price[b[0]][0], price[b[1]][0]))

    def result(o, c):
        return "Up" if c >= o else "Down"

    flips = [r for r in rounds if result(r[1], r[2]) != result(r[3], r[4])]
    up_to_down = sum(1 for r in flips if result(r[1], r[2]) == "Down")
    # |plain price − TWAP60| at every boundary second we have both of.
    gap = {t: abs(price[t][0] - twap[t][0]) for t in range(first, end + 1, ROUND) if t in price and t in twap}
    twap_move = lambda r: abs(r[2] - r[1])
    flip_moves = [twap_move(r) for r in flips]
    all_moves = [twap_move(r) for r in rounds]

    # Rebuilding TWAP60 from the price file: plain mean of the price rows in
    # [t − 59, t]. Only to show how far that lands from Chainlink's own value.
    def mean60(t):
        ps = [price[u][0] for u in range(t - 59, t + 1) if u in price]
        return sum(ps) / len(ps) if ps else None

    naive = {t: mean60(t) for t in sorted({b for r in rounds for b in (r[0], r[0] + ROUND)})}
    naive_gap = [abs(naive[t] - twap[t][0]) for t in naive if naive[t] is not None]
    naive_rounds = [r for r in rounds if naive[r[0]] is not None and naive[r[0] + ROUND] is not None]
    naive_flips = sum(1 for r in naive_rounds if result(r[1], r[2]) != result(naive[r[0]], naive[r[0] + ROUND]))

    by_month = {}
    for r in rounds:
        m = datetime.fromtimestamp(r[0], timezone.utc).strftime("%Y-%m")
        e = by_month.setdefault(m, {"month": m, "rounds": 0, "flips": 0})
        e["rounds"] += 1
        e["flips"] += result(r[1], r[2]) != result(r[3], r[4])
    # Partial months are labelled with their first and last day.
    for e in by_month.values():
        ds = [d for d in days if d.strftime("%Y-%m") == e["month"]]
        e["from"], e["to"] = ds[0].isoformat(), ds[-1].isoformat()

    # Chart: CHART, or else the flipped round with no gap longer than 2 s in
    # either stream where both results are most clear-cut.
    def gapless(r):
        for rows in (price, twap):
            ts = [t for t in range(r[0] - 60, r[0] + ROUND + 1) if t in rows]
            if ts[0] != r[0] - 60 or ts[-1] != r[0] + ROUND or max(b - a for a, b in zip(ts, ts[1:])) > 2:
                return False
        return True

    if CHART:
        pick = next(r for r in flips if r[0] == CHART)
    else:
        pick = max((r for r in flips if gapless(r)), key=lambda r: min(abs(r[2] - r[1]), abs(r[4] - r[3])))
    s = pick[0]
    series = lambda rows: [[t, round(rows[t][1], 2)] for t in range(s - 60, s + ROUND + 1) if t in rows]
    chart = {
        "start": s,
        "end": s + ROUND,
        "slug": f"btc-updown-5m-{s}",
        "twap60": {"open": str(pick[1]), "close": str(pick[2]), "result": result(pick[1], pick[2])},
        "price": {"open": str(pick[3]), "close": str(pick[4]), "result": result(pick[3], pick[4])},
        "series": {"price": series(price), "twap60": series(twap)},
    }

    out = {
        "from": days[0].isoformat(),
        "to": days[-1].isoformat(),
        "days": len(days),
        "rounds": len(starts),
        "comparable": len(rounds),
        "missingBoundary": missing,
        "flips": len(flips),
        "flipShare": round(len(flips) / len(rounds), 4),
        "upToDown": up_to_down,
        "downToUp": len(flips) - up_to_down,
        "boundaryGap": {
            "seconds": len(gap),
            "median": money(statistics.median(gap.values())),
            "p90": money(pct(gap.values(), 0.9)),
            "p99": money(pct(gap.values(), 0.99)),
            "max": money(max(gap.values())),
            "maxAt": max(gap, key=gap.get),
        },
        "twapMove": {
            "medianAll": money(statistics.median(all_moves)),
            "medianFlips": money(statistics.median(flip_moves)),
            "flipsUnder10": sum(1 for x in flip_moves if x < 10),
            "flipsUnder25": sum(1 for x in flip_moves if x < 25),
        },
        "naiveMean": {
            "rounds": len(naive_rounds),
            "flips": naive_flips,
            "median": money(statistics.median(naive_gap)),
            "p90": money(pct(naive_gap, 0.9)),
            "max": money(max(naive_gap)),
        },
        "byMonth": list(by_month.values()),
        # [start, TWAP60 result] of every flipped round, for the gamma check.
        "flipRounds": [[r[0], result(r[1], r[2])] for r in flips],
        "chart": chart,
    }
    # Keep the last gamma check while the flipped rounds are the same ones.
    if os.path.exists(OUT):
        with open(OUT) as f:
            old = json.load(f)
        if "polymarket" in old and old.get("flipRounds") == out["flipRounds"]:
            out["polymarket"] = old["polymarket"]
    with open(OUT, "w") as f:
        json.dump(out, f, separators=(",", ":"))
        f.write("\n")
    summary = {k: v for k, v in out.items() if k not in ("chart", "flipRounds")}
    print(json.dumps(summary, indent=1))
    print("chart round", chart["slug"], chart["twap60"], chart["price"])


def gamma_result(start):
    """Polymarket's resolved outcome for one round, from the public Gamma API."""
    url = f"https://gamma-api.polymarket.com/markets/slug/btc-updown-5m-{start}"
    for attempt in range(6):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "polyticktape-guide-check"}), timeout=20) as r:
                m = json.load(r)
            break
        except urllib.error.HTTPError as e:
            if e.code == 404:
                return "missing"
            time.sleep(2**attempt)
        except OSError:
            time.sleep(2**attempt)
    else:
        return "error"
    prices = json.loads(m.get("outcomePrices") or "[]")
    if not m.get("closed") or json.loads(m["outcomes"]) != ["Up", "Down"]:
        return "unresolved"
    return {("1", "0"): "Up", ("0", "1"): "Down"}.get(tuple(prices), "unresolved")


def gamma():
    """Adds Polymarket's resolved result for every flipped round to the JSON."""
    with open(OUT) as f:
        out = json.load(f)
    flips = out["flipRounds"]
    with ThreadPoolExecutor(4) as pool:
        got = list(pool.map(gamma_result, [start for start, _ in flips]))
    as_twap = sum(1 for (_, twap), pm in zip(flips, got) if pm == twap)
    as_price = sum(1 for (_, twap), pm in zip(flips, got) if pm in ("Up", "Down") and pm != twap)
    out["polymarket"] = {
        "checked": len(flips),
        "asTwap60": as_twap,
        "asPrice": as_price,
        "other": {k: got.count(k) for k in ("unresolved", "missing", "error") if got.count(k)},
        "against": [start for (start, twap), pm in zip(flips, got) if pm != twap],
        "on": datetime.now(timezone.utc).date().isoformat(),
    }
    with open(OUT, "w") as f:
        json.dump(out, f, separators=(",", ":"))
        f.write("\n")
    print(json.dumps(out["polymarket"], indent=1))


def main():
    global OUT
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True)
    build_parser = commands.add_parser("build", help="Recompute statistics from daily archives")
    build_parser.add_argument("data", help="Directory containing YYYY-MM-DD subdirectories")
    build_parser.add_argument("--output", required=True, help="Destination JSON file")
    gamma_parser = commands.add_parser("gamma", help="Check flipped rounds against the public Gamma API")
    gamma_parser.add_argument("--output", required=True, help="Existing JSON file to update")
    args = parser.parse_args()
    OUT = args.output
    if args.command == "build":
        build(args.data)
    else:
        gamma()


if __name__ == "__main__":
    main()
