#!/usr/bin/env python3
"""Replay the frozen Solana D1 study from publisher-verified spot archives."""
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import csv
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal, getcontext
from hashlib import sha256
from io import TextIOWrapper
import json
from pathlib import Path
from urllib.request import urlopen
from zipfile import ZipFile

getcontext().prec = 40
HOUR = 3_600_000
DAY = 24 * HOUR
D = Decimal
ZERO = D(0)
PRECISION = D("0.000000000001")
ARCHIVE_HOST = "https://data.binance.vision"


@dataclass(frozen=True, slots=True)
class Candle:
    open: Decimal
    high: Decimal
    low: Decimal
    close: Decimal
    volume: Decimal


def utc(ms):
    return datetime.fromtimestamp(ms // 1000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def millis(stamp):
    return int(datetime.fromisoformat(stamp).timestamp()) * 1000


def month_keys(first, last):
    year, month = map(int, first.split("-"))
    while (name := f"{year:04d}-{month:02d}") <= last:
        yield name
        year, month = (year + 1, 1) if month == 12 else (year, month + 1)


def digest(data):
    return sha256(data).hexdigest()


def gaps(available, start, end, interval):
    missing = []
    for timestamp in range(start, end, interval):
        if timestamp in available:
            continue
        if missing and missing[-1][1] == timestamp:
            missing[-1][1] += interval
        else:
            missing.append([timestamp, timestamp + interval])
    return [{"start_utc": utc(start), "end_exclusive_utc": utc(end), "slots": (end-start)//interval}
            for start, end in missing]


def load_feed(name, feed, months, raw):
    symbol = feed["symbol"]
    interval = feed["interval_ms"]
    bars, manifest = {}, []
    row_count = zero_volume = zero_volume_bad_close = 0
    short_closes = []
    for month, next_month in zip(months, months[1:]):
        start, end = (millis(f"{value}-01T00:00:00Z") for value in (month, next_month))
        stem = f"{symbol}-{feed['interval']}-{month}"
        path = raw / feed["subdirectory"] / f"{stem}.zip"
        checksum = path.with_suffix(".zip.CHECKSUM").read_text(encoding="ascii").split()
        actual = digest(path.read_bytes())
        if checksum != [actual, path.name]:
            raise ValueError(f"Invalid checksum for {path}")
        expected_member = f"{stem}.csv"
        with ZipFile(path) as z:
            if z.namelist() != [expected_member]:
                raise ValueError(f"Unexpected contents in {path}")
            with z.open(expected_member) as stream:
                reader = csv.reader(TextIOWrapper(stream, encoding="utf-8", newline=""))
                rows = 0
                previous = start - interval
                for i, row in enumerate(reader):
                    if i == 0 and row[0].strip().lower() == "open_time":
                        continue
                    if len(row) != 12:
                        raise ValueError(f"Expected 12 columns in {path} line {i+1}")
                    native_open, native_close = int(row[0]), int(row[6])
                    scale = 1000 if month >= "2025-01" else 1
                    timestamp, remainder = divmod(native_open, scale)
                    if remainder or timestamp % interval or not start <= timestamp < end or timestamp <= previous:
                        raise ValueError(f"Unexpected candle window in {path} line {i+1}")
                    previous = timestamp
                    rows += 1
                    o, h, l, c, volume = map(D, row[1:6])
                    if min(o, c) < l or max(o, c) > h or l <= 0 or volume < 0:
                        raise ValueError(f"Invalid OHLCV in {path} line {i+1}")
                    valid_close = native_close == native_open + interval * scale - 1
                    if volume == 0:
                        zero_volume += 1
                        zero_volume_bad_close += not valid_close
                    elif not valid_close:
                        short_closes.append({"open_utc": utc(timestamp), "source_close": native_close,
                                             "expected_close": native_open + interval*scale - 1})
                    else:
                        bars[timestamp] = Candle(o, h, l, c, volume)
                if rows == 0:
                    raise ValueError(f"No data in {path}")
        row_count += rows
        manifest.append({"feed": name, "month": month, "filename": path.name, "rows": rows,
                         "sha256": actual, "url": f"{ARCHIVE_HOST}/data/spot/monthly/klines/{symbol}/{feed['interval']}/{path.name}"})
    start, end = (millis(f"{value}-01T00:00:00Z") for value in (months[0], months[-1]))
    expected = (end-start)//interval
    coverage = {"expected": expected, "rows": row_count, "available": len(bars),
                "missing": expected-row_count, "zero_volume": zero_volume,
                "zero_volume_bad_close_timestamp": zero_volume_bad_close,
                "incomplete_positive_volume": short_closes,
                "unavailable_ranges": gaps(bars, start, end, interval)}
    assert coverage["missing"] + zero_volume + len(short_closes) == expected - len(bars)
    return bars, coverage, manifest


def format_decimal(number):
    if number is None:
        return None
    return format(number.quantize(PRECISION).normalize(), "f") if number else "0"


def candle_record(timestamp, bar):
    fields = ("open", "high", "low", "close", "volume")
    return {"open_ms": timestamp, "utc": utc(timestamp),
            **{key: format(getattr(bar, key), "f") if bar else None for key in fields}}


def cost_adjusted_r(entry, reference, risk, fee, slip):
    buy, sell = entry * (1 + slip), reference * (1 - slip)
    return (sell - buy - fee * (buy + sell)) / risk


def daily_candles(hourly, start, end):
    days = {}
    for t in range(start, end, DAY):
        bars = [hourly.get(u) for u in range(t, t+DAY, HOUR)]
        if all(bars):
            days[t] = Candle(bars[0].open, max(b.high for b in bars), min(b.low for b in bars),
                             bars[-1].close, sum(b.volume for b in bars))
    return days


def moving_average(days, start, end, window):
    averages = {}
    for t in range(start+(window-1)*DAY, end, DAY):
        bars = [days.get(u) for u in range(t-(window-1)*DAY, t+DAY, DAY)]
        if all(bars):
            averages[t] = sum(b.close for b in bars) / window
    return averages


def mean_true_range(days, t, count):
    ranges = []
    for u in range(t-(count-1)*DAY, t+DAY, DAY):
        bar, previous = days[u], days[u-DAY].close
        ranges.append(max(bar.high-bar.low, abs(bar.high-previous), abs(bar.low-previous)))
    return sum(ranges) / count


def exit_trade(hourly, days, sma, entry, stop, holding):
    limit = entry+holding
    for t in range(entry, limit+HOUR, HOUR):
        bar = hourly.get(t)
        if bar is None:
            return None
        if t == limit:
            return t, t, "time", bar.open
        if t > entry and t % DAY == 0 and days[t-DAY].close <= sma[t-DAY]:
            return t, t, "sma_exit", bar.open
        if bar.open <= stop:
            return t, t, "stop_gap", bar.open
        if bar.low <= stop:
            return t, t+HOUR, "stop", stop
    raise AssertionError("Horizon did not align to H1")


def compare_period(p, name, start, end, hourly, sol, btc, sma):
    width = p["setup"]["relative_days"] * DAY
    tr_window = p["setup"]["simple_true_range_days"]
    holding = p["execution"]["max_hold_days"] * DAY
    multiple = D(p["execution"]["stop_true_range_multiple"])
    fee = D(p["costs"]["fee_per_side"])
    slip = D(p["costs"]["adverse_slippage_per_side"])
    stress = D(p["costs"]["stress_multiplier"])
    busy_until = start
    rows = []
    for t in range(start, end, DAY):
        previous = t-DAY
        if t not in sma or previous not in sma:
            continue
        if sol[t].close <= sma[t] or sol[previous].close > sma[previous]:
            continue
        entry_time = t+DAY
        row = {"period": name, "signal": candle_record(t, sol[t]), "previous": candle_record(previous, sol[previous]),
               "sma": format_decimal(sma[t]), "previous_sma": format_decimal(sma[previous])}
        rows.append(row)
        if entry_time+holding >= end:
            row["status"] = "period_cutoff"
            continue
        if entry_time < busy_until:
            row["status"] = "position_open"
            continue
        earlier = t-width
        if earlier not in btc or t not in btc:
            row["status"] = "benchmark_unavailable"
            continue
        sol_end, sol_start = sol[t].close, sol[earlier].close
        btc_end, btc_start = btc[t].close, btc[earlier].close
        rel_now, rel_then = sol_end/btc_end, sol_start/btc_start
        row.update(passes_filter=sol_end*btc_start > sol_start*btc_end,
                   earlier_open_ms=earlier, sol_earlier_close=format_decimal(sol_start),
                   btc_earlier_close=format_decimal(btc_start), btc_signal_close=format_decimal(btc_end),
                   sol_return_pct=format_decimal(100*(sol_end/sol_start-1)),
                   btc_return_pct=format_decimal(100*(btc_end/btc_start-1)),
                   ratio_then=format_decimal(rel_then), ratio_now=format_decimal(rel_now),
                   relative_pct=format_decimal(100*(rel_now/rel_then-1)))
        if entry_time not in hourly:
            row["status"] = "entry_unavailable"
            continue
        entry = hourly[entry_time].open
        tr_mean = mean_true_range(sol, t, tr_window)
        risk = tr_mean * multiple
        stop = entry-risk
        row.update(entry={"open_ms": entry_time, "utc": utc(entry_time), "reference": format_decimal(entry)},
                   tr_mean=format_decimal(tr_mean), initial_risk=format_decimal(risk), stop=format_decimal(stop))
        if risk <= 0 or stop <= 0:
            row["status"] = "risk_invalid"
            continue
        outcome = exit_trade(hourly, sol, sma, entry_time, stop, holding)
        if outcome is None:
            busy_until = entry_time+holding
            row["status"] = "outcome_unavailable"
            continue
        exit_open, busy_until, reason, reference = outcome
        row["exit"] = {"open_ms": exit_open, "utc": utc(exit_open), "resolved_ms": busy_until,
                       "reason": reason, "reference": format_decimal(reference)}
        row["net_r"] = {"base": cost_adjusted_r(entry, reference, risk, fee, slip),
                        "stress": cost_adjusted_r(entry, reference, risk, fee*stress, slip*stress),
                        "gross": (reference-entry)/risk}
        row["status"] = "executed"
    return rows


def stats(rows):
    r = [t["net_r"]["base"] for t in rows]
    equity = peak = drawdown = ZERO
    for value in r:
        equity += value
        peak = max(peak, equity)
        drawdown = max(drawdown, peak-equity)
    return {"trades": len(rows), "wins": sum(v > 0 for v in r),
            "net_r": format_decimal(equity), "mean_r": format_decimal(equity/len(rows) if rows else None),
            "max_drawdown_r": format_decimal(drawdown),
            "gross_r": format_decimal(sum(t["net_r"]["gross"] for t in rows)),
            "stress_net_r": format_decimal(sum(t["net_r"]["stress"] for t in rows)),
            "exit_reasons": dict(Counter(t["exit"]["reason"] for t in rows))}


def arms(trades):
    return {"base": stats(trades),
            "filtered": stats([t for t in trades if t["passes_filter"]]),
            "excluded": stats([t for t in trades if not t["passes_filter"]])}


def examples(trades, hourly, sol, btc, sma):
    holdout = [r for r in trades if r["period"] == "holdout"]
    choices = {
        "filtered_win": next((r for r in holdout if r["passes_filter"] and r["net_r"]["base"] > 0), None),
        "filtered_nonwin": next((r for r in holdout if r["passes_filter"] and r["net_r"]["base"] <= 0), None),
        "base_only": next((r for r in holdout if not r["passes_filter"]), None),
    }
    result = []
    for kind, trade in choices.items():
        if trade is None:
            result.append({"kind": kind, "trade": None, "d1": [], "h1": []})
            continue
        signal = trade["signal"]["open_ms"]
        exit_open = trade["exit"]["open_ms"]
        exit_day = exit_open//DAY*DAY
        context = []
        for t in range(signal-22*DAY, exit_day+4*DAY, DAY):
            row = candle_record(t, sol.get(t))
            row["sma50"] = format_decimal(sma.get(t))
            row["btc_close"] = format_decimal(btc[t].close) if t in btc else None
            row["ratio"] = format_decimal(sol[t].close/btc[t].close) if t in sol and t in btc else None
            context.append(row)
        detail = [candle_record(t, hourly.get(t)) for t in range(exit_open-8*HOUR, exit_open+9*HOUR, HOUR)]
        result.append({"kind": kind, "trade": trade, "d1": context, "h1": detail})
    return result


def replay(protocol_bytes, raw):
    p = json.loads(protocol_bytes)
    first, last = (p["months"][k] for k in ("first", "last"))
    year, month = map(int, last.split("-"))
    after_last = f"{year+1:04d}-01" if month == 12 else f"{year:04d}-{month+1:02d}"
    months = list(month_keys(first, after_last))
    start, end = (millis(f"{value}-01T00:00:00Z") for value in (months[0], months[-1]))
    hourly, sol_coverage, sol_sources = load_feed("sol", p["feeds"]["sol"], months, raw)
    btc, btc_coverage, btc_sources = load_feed("btc", p["feeds"]["btc"], months, raw)
    sol = daily_candles(hourly, start, end)
    sma = moving_average(sol, start, end, p["setup"]["sma_days"])
    setups, completed, periods = [], [], {}
    for name, (lo, hi) in p["periods"].items():
        rows = compare_period(p, name, millis(lo), millis(hi), hourly, sol, btc, sma)
        trades = [r for r in rows if r["status"] == "executed"]
        assert all(a["exit"]["resolved_ms"] <= b["entry"]["open_ms"] for a,b in zip(trades,trades[1:]))
        periods[name] = {"start_utc": lo, "end_exclusive_utc": hi,
                         "counts": {"signals": len(rows), "statuses": dict(Counter(r["status"] for r in rows))},
                         **arms(trades)}
        setups.extend(rows)
        completed.extend(trades)
    by_year = {str(year): arms([r for r in completed if int(r["signal"]["utc"][:4]) == year])
               for year in range(2021, 2027)}
    cases = examples(completed, hourly, sol, btc, sma)
    for trade in completed:
        trade["net_r"] = {key: format_decimal(value) for key, value in trade["net_r"].items()}
    return {"protocol_sha256": digest(protocol_bytes), "protocol": p, "sources": sol_sources+btc_sources,
            "coverage": {"start_utc": utc(start), "end_exclusive_utc": utc(end), "sol_h1": sol_coverage,
                         "btc_d1": btc_coverage, "sol_d1": {"expected": (end-start)//DAY, "available": len(sol),
                                                          "unavailable_ranges": gaps(sol,start,end,DAY)},
                         "paired_d1": len(sol.keys() & btc.keys())},
            "periods": periods, "yearly": by_year, "setups": setups, "examples": cases}


def download_inputs(protocol, raw):
    def acquire(job):
        feed, month = job
        symbol, interval = feed["symbol"], feed["interval"]
        name = f"{symbol}-{interval}-{month}.zip"
        path = raw / feed["subdirectory"] / name
        check = path.with_suffix(".zip.CHECKSUM")
        if path.is_file() and check.is_file() and check.read_text(encoding="ascii").split() == [digest(path.read_bytes()), name]:
            return
        url = f"{ARCHIVE_HOST}/data/spot/monthly/klines/{symbol}/{interval}/{name}"
        with urlopen(url+".CHECKSUM", timeout=40) as response:
            checksum = response.read()
        with urlopen(url, timeout=40) as response:
            blob = response.read()
        if checksum.decode("ascii").split() != [digest(blob), name]:
            raise ValueError(f"Invalid publisher checksum for {url}")
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(blob)
        check.write_bytes(checksum)

    months = list(month_keys(protocol["months"]["first"], protocol["months"]["last"]))
    with ThreadPoolExecutor(max_workers=6) as pool:
        for _ in pool.map(acquire, ((feed, month) for feed in protocol["feeds"].values() for month in months)):
            pass


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--protocol", required=True, type=Path)
    parser.add_argument("--raw-dir", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--download", action="store_true", help="fetch missing inputs and their publisher checksums")
    args = parser.parse_args()
    protocol_bytes = args.protocol.read_bytes()
    if args.download:
        download_inputs(json.loads(protocol_bytes), args.raw_dir)
    result = replay(protocol_bytes, args.raw_dir)
    args.output.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":"))+"\n", encoding="utf-8")
    print(json.dumps({"periods": result["periods"], "output_sha256": digest(args.output.read_bytes())}, indent=2))


if __name__ == "__main__":
    main()
