"""Replay one fixed rule on resolved Polymarket "Bitcoin Up or Down" daily markets.

Rule, fixed before the run: four hours before a market closes, read the last price
sample at or before that time for each outcome. If exactly one outcome is priced
from $0.60 to $0.85, buy 10 shares of it and hold to resolution. One entry per market.

Fill model: the sample is a price, not a book quote, so each entry pays the sample
plus $0.01. Fees use the market's own feeSchedule: shares * rate * p * (1 - p).

Data: Polymarket Gamma API (market metadata, outcome, fee schedule) and the CLOB
prices-history endpoint. Read-only; it places no orders. Usage:

    python3 polymarket-btc-daily-replay-2026-10-20.py out.csv
"""
import csv
import datetime as dt
import json
import sys
import urllib.parse
import urllib.request

FIRST, LAST = dt.date(2026, 9, 21), dt.date(2026, 10, 20)
SHARES, LOW, HIGH, SPREAD_COST = 10, 0.60, 0.85, 0.01
LEAD, LOOKBACK = 4 * 3600, 30 * 60


def get(url, **params):
    request = urllib.request.Request(f"{url}?{urllib.parse.urlencode(params)}",
                                     headers={"User-Agent": "turbine-replay-example/1.0"})
    with urllib.request.urlopen(request, timeout=20) as r:
        return json.load(r)


def iso(ts):
    return dt.datetime.fromtimestamp(ts, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


rows = []
day = FIRST
while day <= LAST:
    slug = f"bitcoin-up-or-down-on-{day.strftime('%B').lower()}-{day.day}-{day.year}"
    day += dt.timedelta(days=1)
    market = get("https://gamma-api.polymarket.com/events", slug=slug)[0]["markets"][0]
    close = int(dt.datetime.fromisoformat(market["endDate"].replace("Z", "+00:00")).timestamp())
    decide = close - LEAD
    outcomes = json.loads(market["outcomes"])
    tokens = json.loads(market["clobTokenIds"])
    final = json.loads(market["outcomePrices"])
    rate = market["feeSchedule"]["rate"] if market.get("feesEnabled") else 0.0
    row = {"market": slug, "close_utc": market["endDate"], "decision_utc": iso(decide),
           "winner": outcomes[final.index("1")], "fee_rate": rate}
    prices = {}
    for name, token in zip(outcomes, tokens):
        history = get("https://clob.polymarket.com/prices-history", market=token,
                      startTs=decide - LOOKBACK, endTs=decide, fidelity=1)["history"]
        sample = [h for h in history if h["t"] <= decide][-1:] or [None]
        key = name.lower()
        row[f"{key}_token_id"] = token
        row[f"{key}_sample_utc"] = iso(sample[0]["t"]) if sample[0] else ""
        row[f"{key}_sample"] = sample[0]["p"] if sample[0] else ""
        prices[name] = sample[0]["p"] if sample[0] else None
    picks = [n for n, p in prices.items() if p is not None and LOW <= p <= HIGH]
    row.update(action="skip", side="", fill="", cost="", fee="", payout="", net="")
    if None in prices.values():
        row["action"] = "skip_missing_history"
    elif len(picks) == 1:
        side = picks[0]
        fill = round(prices[side] + SPREAD_COST, 4)
        cost = round(SHARES * fill, 4)
        fee = round(SHARES * rate * fill * (1 - fill), 4)
        payout = float(SHARES) if side == row["winner"] else 0.0
        row.update(action="buy", side=side, fill=fill, cost=cost, fee=fee, payout=payout,
                   net=round(payout - cost - fee, 4))
    rows.append(row)

with open(sys.argv[1], "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0]))
    writer.writeheader()
    writer.writerows(rows)

buys = [r for r in rows if r["action"] == "buy"]
print(f"markets={len(rows)} entries={len(buys)} wins={sum(r['payout'] > 0 for r in buys)} "
      f"missing={sum(r['action'] == 'skip_missing_history' for r in rows)}")
print(f"cost={sum(r['cost'] for r in buys):.2f} payout={sum(r['payout'] for r in buys):.2f} "
      f"fees={sum(r['fee'] for r in buys):.2f} net={sum(r['net'] for r in buys):.2f}")
