#!/usr/bin/env python3
"""Reproduce the frozen ETH/USDT H4 study with the publisher ZIPs and checksums."""
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 statistics import median
from urllib.request import urlopen
from zipfile import ZipFile

getcontext().prec = 40
M15 = 900_000
H4 = 16 * M15
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):
    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 name == "spot" and 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}/{feed['archive']}/{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 spot_h4(m15, start, end):
    complete = {}
    for t in range(start, end, H4):
        members = [m15.get(i) for i in range(t, t+H4, M15)]
        if all(members):
            complete[t] = Candle(members[0].open, max(b.high for b in members),
                                 min(b.low for b in members), members[-1].close,
                                 sum(b.volume for b in members))
    return complete


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 basis_bps(spot, perpetual, t):
    if t in spot and t in perpetual:
        return D(10_000) * (perpetual[t].close / spot[t].close - 1)
    return None


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 spot_exit(m15, entry_ms, stop, target, hold):
    boundary = entry_ms + hold
    for t in range(entry_ms, boundary, M15):
        bar = m15.get(t)
        if bar is None:
            return None
        if bar.open <= stop:
            return t, t, "stop_gap", bar.open, None
        if bar.open >= target:
            return t, t, "target_gap", target, None
        if bar.low <= stop:
            return t, t + M15, "stop", stop, target if bar.high >= target else None
        if bar.high >= target:
            return t, t + M15, "target", target, None
    return (boundary, boundary, "time", m15[boundary].open, None) if boundary in m15 else None


def run_period(protocol, name, start, end, spot, m15, perpetual):
    setup_rules = protocol["setup"]
    confirm_count = protocol["confirmation"]["next_h4"]
    lookback = setup_rules["prior_h4_bodies"]
    multiple = D(setup_rules["minimum_body_multiple"])
    lower = D(setup_rules["close_bottom_fraction"])
    fraction = D(protocol["confirmation"]["range_midpoint"])
    minimum = D(protocol["execution"]["minimum_risk_fraction"])
    target_r = D(protocol["execution"]["target_r"])
    hold = H4 * protocol["execution"]["max_hold_h4"]
    fee = D(protocol["costs"]["fee_per_side"])
    slip = D(protocol["costs"]["adverse_slippage_per_side"])
    stress = D(protocol["costs"]["stress_multiplier"])
    cooldown = H4 * setup_rules["cooldown_h4"]
    next_setup = start
    setups = []
    for t in range(start, end, H4):
        setup = spot.get(t)
        if not setup or not setup.low <= setup.close < setup.open or setup.high <= setup.low:
            continue
        if setup.close > setup.low + lower * (setup.high - setup.low):
            continue
        prior = [spot.get(i) for i in range(t-lookback*H4, t, H4)]
        if not all(prior):
            continue
        normal_body = median(abs(b.close-b.open) for b in prior)
        if normal_body <= 0 or setup.open-setup.close < multiple*normal_body:
            continue
        midpoint = setup.low + fraction * (setup.high - setup.low)
        row = {"period": name, "signal": candle_record(t, setup),
               "median_body": format_decimal(normal_body), "midpoint": format_decimal(midpoint)}
        setups.append(row)
        if t + (confirm_count+1)*H4 + hold >= end:
            row["status"] = "period_cutoff"
            continue
        if t < next_setup:
            row["status"] = "cooldown"
            continue
        next_setup = t + cooldown
        for confirmation_ms in range(t+H4, t+(confirm_count+1)*H4, H4):
            bar = spot.get(confirmation_ms)
            if bar is None:
                row["status"] = "confirmation_unavailable"
                break
            if bar.low <= setup.low:
                row["status"] = "cancelled"
                break
            if bar.close > midpoint:
                row["confirmation"] = candle_record(confirmation_ms, bar)
                break
        else:
            row["status"] = "expired"
        if "status" in row:
            continue
        entry_ms = confirmation_ms + H4
        b0, b1 = (basis_bps(spot, perpetual, index) for index in (t, confirmation_ms))
        row.update(basis_setup_bps=format_decimal(b0), basis_confirmation_bps=format_decimal(b1),
                   perpetual_setup_close=format_decimal(perpetual[t].close) if t in perpetual else None,
                   perpetual_confirmation_close=format_decimal(perpetual[confirmation_ms].close) if confirmation_ms in perpetual else None)
        if b0 is None or b1 is None:
            row["status"] = "basis_unavailable"
            continue
        row["passes_filter"] = b0 < 0 and b1 > b0
        if entry_ms not in m15:
            row["status"] = "entry_unavailable"
            continue
        entry = m15[entry_ms].open
        risk = entry - setup.low
        row["entry"] = {"open_ms": entry_ms, "utc": utc(entry_ms), "reference": format_decimal(entry)}
        if risk < minimum * entry:
            row["status"] = "risk_too_small"
            continue
        target = entry + target_r * risk
        row.update(stop=format_decimal(setup.low), target=format_decimal(target), initial_risk=format_decimal(risk))
        outcome = spot_exit(m15, entry_ms, setup.low, target, hold)
        if outcome is None:
            row["status"] = "outcome_unavailable"
            continue
        exit_ms, resolved_ms, reason, reference, alternative = outcome
        row["exit"] = {"open_ms": exit_ms, "utc": utc(exit_ms), "resolved_ms": resolved_ms, "reason": reason,
                       "reference": format_decimal(reference), "ambiguous": alternative is not None}
        row["net_r"] = {"base": cost_adjusted_r(entry, reference, risk, fee, slip),
                        "stress": cost_adjusted_r(entry, reference, risk, stress*fee, stress*slip),
                        "target_first": cost_adjusted_r(entry, alternative if alternative is not None else reference, risk, fee, slip),
                        "gross": (reference-entry)/risk}
        row["status"] = "executed"
    return setups


def metrics(trades):
    totals = {key: sum((row["net_r"][key] for row in trades), ZERO)
              for key in ("base", "stress", "target_first", "gross")}
    equity = high_water = drawdown = ZERO
    for trade in sorted(trades, key=lambda row: row["exit"]["resolved_ms"]):
        equity += trade["net_r"]["base"]
        high_water = max(high_water, equity)
        drawdown = max(drawdown, high_water-equity)
    n = len(trades)
    return {"trades": n, "wins": sum(row["net_r"]["base"] > 0 for row in trades),
            "mean_r": format_decimal(totals["base"] / n if n else None),
            "net_r": format_decimal(totals["base"]), "max_drawdown_r": format_decimal(drawdown),
            "stress_net_r": format_decimal(totals["stress"]), "target_first_net_r": format_decimal(totals["target_first"]),
            "gross_r": format_decimal(totals["gross"]),
            "ambiguous": sum(row["exit"]["ambiguous"] for row in trades),
            "exit_reasons": dict(Counter(row["exit"]["reason"] for row in trades))}


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


def examples(trades, spot, m15, perpetual):
    holdout = [r for r in trades if r["period"] == "holdout"]
    selected = [
        ("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 selected:
        if trade is None:
            result.append({"kind": kind, "trade": None, "h4": [], "m15": []})
            continue
        signal, exit_ms = trade["signal"]["open_ms"], trade["exit"]["open_ms"]
        exit_h4 = exit_ms // H4 * H4
        h4_rows = []
        for t in range(signal-6*H4, exit_h4+4*H4, H4):
            row = candle_record(t, spot.get(t))
            row.update(perpetual_close=format_decimal(perpetual[t].close) if t in perpetual else None,
                       basis_bps=format_decimal(basis_bps(spot, perpetual, t)))
            h4_rows.append(row)
        m15_rows = [candle_record(t, m15.get(t)) for t in range(exit_ms-8*M15, exit_ms+9*M15, M15)]
        result.append({"kind": kind, "trade": trade, "h4": h4_rows, "m15": m15_rows})
    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("-"))
    next_month = f"{year+1:04d}-01" if month == 12 else f"{year:04d}-{month+1:02d}"
    months = list(month_keys(first, next_month))
    start, end = (millis(f"{value}-01T00:00:00Z") for value in (months[0], months[-1]))
    m15, spot_coverage, spot_manifest = load_feed("spot", p["feeds"]["spot"], months, raw, p["symbol"])
    perp, perp_coverage, perp_manifest = load_feed("perpetual", p["feeds"]["perpetual"], months, raw, p["symbol"])
    spot = spot_h4(m15, start, end)
    paired = spot.keys() & perp.keys()
    setups, completed, periods = [], [], {}
    for name, (lo, hi) in p["periods"].items():
        rows = run_period(p, name, millis(lo), millis(hi), spot, m15, perp)
        trades = [r for r in rows if r["status"] == "executed"]
        for left, right in zip(trades, trades[1:]):
            assert left["exit"]["resolved_ms"] <= right["entry"]["open_ms"]
        statuses = Counter(r["status"] for r in rows)
        periods[name] = {"start_utc": lo, "end_exclusive_utc": hi,
                         "counts": {"impulses": len(rows), "scheduled": len(rows)-statuses["cooldown"]-statuses["period_cutoff"],
                                    "statuses": dict(statuses), "confirmations": sum("confirmation" in r for r in rows)},
                         **arms(trades)}
        setups.extend(rows)
        completed.extend(trades)
    yearly = {str(year): arms([r for r in completed if int(r["signal"]["utc"][:4]) == year]) for year in range(2021, 2027)}
    cases = examples(completed, spot, m15, perp)
    for trade in completed:
        trade["net_r"] = {key: format_decimal(number) for key, number in trade["net_r"].items()}
    return {"protocol_sha256": digest(protocol_bytes), "protocol": p,
            "sources": spot_manifest + perp_manifest,
            "coverage": {"start_utc": utc(start), "end_exclusive_utc": utc(end),
                         "spot_m15": spot_coverage, "perpetual_h4": perp_coverage,
                         "spot_h4": {"expected": (end-start)//H4, "available": len(spot),
                                     "unavailable_ranges": gaps(spot, start, end, H4)},
                         "paired_h4": len(paired)},
            "periods": periods, "yearly": yearly, "setups": setups, "examples": cases}


def download_inputs(protocol, raw):
    def acquire(job):
        feed, month = job
        name = f"{protocol['symbol']}-{feed['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}/{feed['archive']}/{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()
