"""Reproduce the frozen BTC/USDT H1 negative-volume-delta study from verified ZIPs."""
import argparse
from collections import Counter
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
import re
from zipfile import ZipFile

EXPECTED_PROTOCOL = "abbb30908101198519244b5151c4d28aa5bf54430fd3d2ea13d7d9d43b1cbeec"
FROZEN_UTC = "2026-11-09T13:20:09Z"
BASE_URL = "https://data.binance.vision/data/spot/monthly/klines/BTCUSDT/15m"
M15 = 900_000
H1 = 4 * M15
getcontext().prec = 40
D = Decimal
ZERO = D(0)
ONE = D(1)
R_PRECISION = D("0.000000000001")
STATUSES = (
    "confirmation_unavailable",
    "invalidated",
    "expired",
    "entry_unavailable",
    "risk_skipped",
    "outcome_unavailable",
    "executed",
)


def ms(utc):
    return int(datetime.fromisoformat(utc.replace("Z", "+00:00")).timestamp()) * 1000


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


def month_end(month):
    year, number = map(int, month.split("-"))
    if number == 12:
        return f"{year + 1}-01"
    return f"{year}-{number + 1:02d}"


def month_start_ms(month):
    return ms(f"{month}-01T00:00:00Z")


def number(value):
    text = format(value, "f")
    return text.rstrip("0").rstrip(".") if "." in text else text


def r_number(value):
    return format(value.quantize(R_PRECISION), "f")


@dataclass(frozen=True, slots=True)
class Bar:
    open_ms: int
    open: Decimal
    high: Decimal
    low: Decimal
    close: Decimal
    volume: Decimal
    taker_buy: Decimal

    @property
    def delta(self):
        return 2 * self.taker_buy - self.volume

    def record(self):
        return {
            "open_ms": self.open_ms,
            "utc": utc(self.open_ms),
            "open": number(self.open),
            "high": number(self.high),
            "low": number(self.low),
            "close": number(self.close),
            "volume": number(self.volume),
            "taker_buy": number(self.taker_buy),
            "delta": number(self.delta),
        }


def archive_pair(path):
    name = path.name
    check = path.with_name(name + ".CHECKSUM").read_bytes()
    parts = check.decode("ascii").split()
    if len(parts) != 2 or not re.fullmatch("[a-f0-9]{64}", parts[0]) or parts[1] != name:
        raise ValueError(f"Invalid publisher checksum record for {name}")
    data = path.read_bytes()
    digest = sha256(data).hexdigest()
    if digest != parts[0]:
        raise ValueError(f"Publisher SHA-256 mismatch for {name}")
    return digest, len(data), sha256(check).hexdigest()


def parse_bar(row, factor):
    if len(row) != 12:
        raise ValueError("Expected twelve spot kline fields")
    stamp_raw = int(row[0])
    close_raw = int(row[6])
    if stamp_raw % (M15 * factor) != 0:
        raise ValueError("Invalid kline open-time grid")
    expected_close = stamp_raw + M15 * factor - 1
    stamp = stamp_raw // factor
    open_, high, low, close, total = map(D, row[1:6])
    quote, taker, taker_quote = map(D, (row[7], row[9], row[10]))
    prices = (open_, high, low, close)
    volumes = (total, quote, taker, taker_quote)
    if any(not x.is_finite() or x <= ZERO for x in prices):
        raise ValueError("Nonpositive or malformed price")
    if not (low <= open_ <= high and low <= close <= high):
        raise ValueError("Open or close outside high-low range")
    if any(not x.is_finite() or x < ZERO for x in volumes) or taker > total:
        raise ValueError("Malformed or out-of-range volume")
    if int(row[8]) < 0:
        raise ValueError("Negative trade count")
    if total > ZERO and not stamp_raw <= close_raw <= expected_close:
        raise ValueError("Positive-volume source close time falls outside its slot")
    anomaly = None
    if close_raw != expected_close:
        anomaly = {
            "open_ms": stamp,
            "utc": utc(stamp),
            "source_close": close_raw,
            "expected_source_close": expected_close,
            "zero_volume": total == ZERO,
        }
    return Bar(stamp, open_, high, low, close, total, taker), anomaly


def ranges(stamps, interval):
    result = []
    for stamp in stamps:
        if result and stamp == result[-1]["end_exclusive_ms"]:
            prior = result[-1]
            prior["end_exclusive_ms"] = stamp + interval
            prior["slots"] += 1
        else:
            result.append({"start_ms": stamp, "end_exclusive_ms": stamp + interval, "slots": 1})
    for item in result:
        item["start_utc"] = utc(item["start_ms"])
        item["end_exclusive_utc"] = utc(item["end_exclusive_ms"])
    return result


def load_bars(raw, protocol):
    begin = protocol["data"]["warmup_start_utc"][:7]
    end = protocol["data"]["exclusive_archive_end_utc"][:7]
    spot_bars = {}
    zero_volume = set()
    sources = []
    close_anomalies = []
    month = begin
    while month < end:
        following = month_end(month)
        start_ms, end_ms = month_start_ms(month), month_start_ms(following)
        factor = 1000 if month >= "2025-01" else 1
        path = raw / f"BTCUSDT-15m-{month}.zip"
        digest, byte_count, checksum_digest = archive_pair(path)
        last = start_ms - M15
        first = None
        count = 0
        empty = 0
        unusual_closes = 0
        with ZipFile(path) as zip_file:
            member = path.stem + ".csv"
            if zip_file.namelist() != [member]:
                raise ValueError(f"Unexpected CSV members in {path.name}")
            with zip_file.open(member) as source:
                for line, row in enumerate(csv.reader(TextIOWrapper(source, encoding="ascii")), 1):
                    try:
                        bar, anomaly = parse_bar(row, factor)
                        if not start_ms <= bar.open_ms < end_ms or bar.open_ms <= last:
                            raise ValueError("Out-of-month, duplicate or unordered bar")
                    except (ArithmeticError, ValueError) as exc:
                        raise ValueError(f"{path.name}, line {line}: {exc}") from exc
                    if first is None:
                        first = bar.open_ms
                    last = bar.open_ms
                    count += 1
                    if anomaly is not None:
                        close_anomalies.append(anomaly)
                        unusual_closes += 1
                    if bar.volume == ZERO:
                        empty += 1
                        zero_volume.add(bar.open_ms)
                    else:
                        spot_bars[bar.open_ms] = bar
        if first is None:
            raise ValueError(f"No rows in {path.name}")
        expected = (end_ms - start_ms) // M15
        url = f"{BASE_URL}/{path.name}"
        sources.append({
            "month": month,
            "url": url,
            "checksum_url": f"{url}.CHECKSUM",
            "sha256": digest,
            "checksum_sha256": checksum_digest,
            "bytes": byte_count,
            "member": member,
            "epoch_unit": "us" if factor == 1000 else "ms",
            "expected": expected,
            "rows": count,
            "available": count - empty,
            "missing": expected - count,
            "zero_volume": empty,
            "nonstandard_close_timestamps": unusual_closes,
            "first_open_utc": utc(first),
            "last_open_utc": utc(last),
        })
        month = following
    start_ms, end_ms = month_start_ms(begin), month_start_ms(end)
    missing = [
        time for time in range(start_ms, end_ms, M15)
        if time not in spot_bars and time not in zero_volume
    ]
    hourly = {}
    for time in range(start_ms, end_ms, H1):
        parts = [spot_bars.get(t) for t in range(time, time + H1, M15)]
        if None in parts:
            continue
        hourly[time] = Bar(
            time, parts[0].open, max(part.high for part in parts),
            min(part.low for part in parts), parts[-1].close,
            sum(part.volume for part in parts), sum(part.taker_buy for part in parts),
        )
    expected_hourly = (end_ms - start_ms) // H1
    coverage = {
        "start_utc": utc(start_ms),
        "end_exclusive_utc": utc(end_ms),
        "m15": {
            "expected": (end_ms - start_ms) // M15,
            "rows": len(spot_bars) + len(zero_volume),
            "available": len(spot_bars),
            "missing": len(missing),
            "zero_volume": len(zero_volume),
            "missing_ranges": ranges(missing, M15),
            "zero_volume_ranges": ranges(sorted(zero_volume), M15),
            "close_timestamp_anomalies": close_anomalies,
        },
        "h1": {
            "expected": expected_hourly,
            "available": len(hourly),
            "unavailable": expected_hourly - len(hourly),
            "unavailable_ranges": ranges(
                (time for time in range(start_ms, end_ms, H1) if time not in hourly), H1
            ),
        },
    }
    if len(sources) != 70 or len(missing) != sum(item["missing"] for item in sources):
        raise ValueError("Source month count or missing coverage mismatch")
    if len(spot_bars) + len(zero_volume) + len(missing) != coverage["m15"]["expected"]:
        raise ValueError("Archive coverage did not reconcile")
    return spot_bars, hourly, zero_volume, sources, coverage


@dataclass(frozen=True, slots=True)
class Exit:
    bar: Bar
    reference: Decimal
    reason: str
    on_open: bool
    ambiguous: bool
    target_first_reference: Decimal

    def record(self):
        return {
            "open_ms": self.bar.open_ms,
            "utc": utc(self.bar.open_ms),
            "resolved_ms": self.bar.open_ms if self.on_open else self.bar.open_ms + M15,
            "reference": number(self.reference),
            "reason": self.reason,
            "on_open": self.on_open,
            "ambiguous": self.ambiguous,
            "target_first_reference": number(self.target_first_reference),
        }


def resolve_exit(bars, entry_time, stop, target, max_hold_hours):
    time_exit = entry_time + max_hold_hours * H1
    for time in range(entry_time, time_exit, M15):
        bar = bars.get(time)
        if bar is None:
            return None, time
        if bar.open <= stop:
            return Exit(bar, bar.open, "stop", True, False, bar.open), None
        if bar.open >= target:
            return Exit(bar, bar.open, "target", True, False, bar.open), None
        if bar.low <= stop:
            ambiguous = bar.high >= target
            alternate = target if ambiguous else stop
            return Exit(bar, stop, "stop", False, ambiguous, alternate), None
        if bar.high >= target:
            return Exit(bar, target, "target", False, False, target), None
    bar = bars.get(time_exit)
    if bar is None:
        return None, time_exit
    return Exit(bar, bar.open, "time", True, False, bar.open), None


def fills_and_r(entry, exit_reference, risk, fee, slippage):
    entry_fill = entry * (ONE + slippage)
    exit_fill = exit_reference * (ONE - slippage)
    fee_entry, fee_exit = fee * entry_fill, fee * exit_fill
    net_r = (exit_fill - entry_fill - fee_entry - fee_exit) / risk
    return {
        "entry": number(entry_fill),
        "exit": number(exit_fill),
        "fee_entry": number(fee_entry),
        "fee_exit": number(fee_exit),
    }, net_r


def test_setup(setup, signal, hourly, bars, zero_volume, protocol):
    confirmation = None
    for offset in range(1, protocol["confirmation"]["max_following_closed_hours"] + 1):
        time = signal.open_ms + offset * H1
        setup["decision_ms"] = time + H1
        candidate = hourly.get(time)
        if candidate is None:
            setup["status"] = "confirmation_unavailable"
            setup["unavailable_open_ms"] = time
            return None
        if candidate.low <= signal.low:
            setup["status"] = "invalidated"
            return None
        if candidate.close > signal.high:
            confirmation = candidate
            break
    if confirmation is None:
        setup["status"] = "expired"
        return None
    setup["confirmation"] = confirmation.record()
    entry_time = confirmation.open_ms + H1
    entry_bar = bars.get(entry_time)
    if entry_bar is None:
        setup["status"] = "entry_unavailable"
        setup["unavailable_open_ms"] = entry_time
        setup["unavailable_reason"] = "zero_volume" if entry_time in zero_volume else "missing"
        return None
    entry = entry_bar.open
    stop = signal.low
    risk = entry - stop
    setup["entry"] = {"open_ms": entry_time, "utc": utc(entry_time), "reference": number(entry)}
    setup["stop"] = number(stop)
    setup["risk"] = number(risk)
    if risk <= ZERO or risk < entry * D(protocol["entry"]["risk_min_fraction"]):
        setup["status"] = "risk_skipped"
        return None
    target = entry + D(protocol["exit"]["target_r"]) * risk
    setup["target"] = number(target)
    exit, unavailable = resolve_exit(bars, entry_time, stop, target, protocol["exit"]["max_hold_hours"])
    if exit is None:
        setup["status"] = "outcome_unavailable"
        setup["unavailable_open_ms"] = unavailable
        setup["unavailable_reason"] = "zero_volume" if unavailable in zero_volume else "missing"
        return None

    setup["exit"] = exit.record()
    setup["status"] = "executed"
    cost = protocol["costs"]
    values = {"gross": (exit.reference - entry) / risk}
    fills = {}
    for scenario, assumptions in (
        ("base", "base"), ("stress", "stress"),
        ("target_first", "base"), ("stress_target_first", "stress"),
    ):
        reference = exit.target_first_reference if "target_first" in scenario else exit.reference
        fill, result = fills_and_r(
            entry, reference, risk, D(cost[f"per_side_{assumptions}_fee"]),
            D(cost[f"per_side_{assumptions}_slippage"]),
        )
        if scenario in ("base", "stress"):
            fills[scenario] = fill
        values[scenario] = result
    setup["fills"] = fills
    setup["net_r"] = {key: r_number(value) for key, value in values.items()}
    return values


def summarize(trades):
    n = len(trades)
    totals = {key: sum((v[key] for _, v in trades), ZERO) for key in
              ("base", "stress", "target_first", "stress_target_first", "gross")}
    equity = peak = drawdown = ZERO
    for _, results in trades:
        equity += results["base"]
        peak = max(peak, equity)
        drawdown = max(drawdown, peak - equity)
    return {
        "trades": n,
        "wins": sum(values["base"] > ZERO for _, values in trades),
        "net_r": r_number(totals["base"]),
        "mean_r": r_number(totals["base"] / n) if n else None,
        "max_drawdown_r": r_number(drawdown),
        "gross_r": r_number(totals["gross"]),
        "stress_net_r": r_number(totals["stress"]),
        "target_first_net_r": r_number(totals["target_first"]),
        "stress_target_first_net_r": r_number(totals["stress_target_first"]),
        "ambiguous": sum(setup["exit"]["ambiguous"] for setup, _ in trades),
        "exit_reasons": dict(sorted(Counter(setup["exit"]["reason"] for setup, _ in trades).items())),
    }


def cohorts(trades):
    return {
        "base": summarize(trades),
        "filtered": summarize([pair for pair in trades if pair[0]["negative_delta"]]),
        "excluded": summarize([pair for pair in trades if not pair[0]["negative_delta"]]),
    }


def eligible_price(bar, prior):
    return bar.high > bar.low and bar.low < min(p.low for p in prior) and (
        4 * (bar.close - bar.low) >= 3 * (bar.high - bar.low)
    )


def test_period(period, hourly, bars, zero_volume, protocol):
    start, end = ms(period["start_utc"]), ms(period["end_exclusive_utc"])
    history = protocol["signal"]["previous_hours"]
    cool = protocol["signal"]["cooldown_hours"] * H1
    max_total = protocol["confirmation"]["max_following_closed_hours"] + protocol["exit"]["max_hold_hours"]
    counts = Counter(dict.fromkeys((
        "hours", "period_edge_hours", "period_edge_candidates", "unavailable_signal_window",
        "price_rule_rejected", "price_candidates", "cooldown_skipped", "setups", "confirmed",
        "negative_delta_setups", "filtered_executed", "excluded_executed", *STATUSES,
    ), 0))
    cooldown_until = start
    setups, trades, screened = [], [], []
    for time in range(start, end, H1):
        counts["hours"] += 1
        close_time = time + H1
        edge = close_time + max_total * H1 >= end
        if edge:
            counts["period_edge_hours"] += 1
        bar = hourly.get(time)
        prior = [hourly.get(t) for t in range(time - history * H1, time, H1)]
        if bar is None or None in prior:
            if not edge:
                counts["unavailable_signal_window"] += 1
            continue
        if not eligible_price(bar, prior):
            if not edge:
                counts["price_rule_rejected"] += 1
            continue
        if edge:
            counts["period_edge_candidates"] += 1
            screened.append({"signal_open_ms": time, "period": period["key"], "reason": "period_edge"})
            continue
        counts["price_candidates"] += 1
        if close_time < cooldown_until:
            counts["cooldown_skipped"] += 1
            screened.append({
                "signal_open_ms": time, "period": period["key"], "reason": "cooldown",
                "cooldown_until_ms": cooldown_until,
            })
            continue
        cooldown_until = close_time + cool
        counts["setups"] += 1
        setup = {
            "id": f"{period['key']}-{counts['setups']:04d}",
            "period": period["key"],
            "signal": bar.record(),
            "signal_close_ms": close_time,
            "negative_delta": bar.delta < ZERO,
            "cooldown_until_ms": cooldown_until,
            "confirmation": None,
            "entry": None,
            "exit": None,
        }
        values = test_setup(setup, bar, hourly, bars, zero_volume, protocol)
        counts[setup["status"]] += 1
        counts["confirmed"] += setup["confirmation"] is not None
        counts["negative_delta_setups"] += setup["negative_delta"]
        if values is not None:
            trades.append((setup, values))
            counts["filtered_executed" if setup["negative_delta"] else "excluded_executed"] += 1
            if setup["exit"]["resolved_ms"] >= end:
                raise ValueError("Trade outcome exceeded period boundary")
            if len(trades) > 1 and trades[-2][0]["exit"]["resolved_ms"] > setup["entry"]["open_ms"]:
                raise ValueError("Shared setup cooldown allowed overlapping positions")
        setups.append(setup)

    if counts["hours"] != sum(counts[key] for key in (
        "period_edge_hours", "unavailable_signal_window", "price_rule_rejected", "price_candidates"
    )):
        raise ValueError("Period hour accounting did not reconcile")
    if counts["price_candidates"] != counts["setups"] + counts["cooldown_skipped"]:
        raise ValueError("Price candidates did not reconcile")
    if counts["setups"] != sum(counts[status] for status in STATUSES):
        raise ValueError("Setup dispositions did not reconcile")
    if counts["executed"] != counts["filtered_executed"] + counts["excluded_executed"]:
        raise ValueError("Executed cohorts did not reconcile")
    years = {}
    for year in range(int(utc(start)[:4]), int(utc(end - H1)[:4]) + 1):
        years[str(year)] = cohorts([pair for pair in trades if pair[0]["signal"]["utc"][:4] == str(year)])
    return {
        "start_utc": utc(start), "end_exclusive_utc": utc(end), "counts": dict(counts),
        **cohorts(trades), "years": years,
    }, setups, trades, screened


def chart_window(bars, start, end, interval, coverage_start, coverage_end):
    return [
        bars[time].record() if time in bars else {"open_ms": time, "utc": utc(time), "unavailable": True}
        for time in range(max(start, coverage_start), min(end + interval, coverage_end), interval)
    ]


def examples_for(trades, hourly, bars, coverage):
    chosen = []
    start, end = ms(coverage["start_utc"]), ms(coverage["end_exclusive_utc"])
    filtered = [pair for pair in trades if pair[0]["negative_delta"]]
    excluded = [pair for pair in trades if not pair[0]["negative_delta"]]
    criteria = (
        ("filtered_win", [pair for pair in filtered if pair[1]["base"] > ZERO], filtered),
        ("filtered_nonwin", [pair for pair in filtered if pair[1]["base"] <= ZERO], filtered),
        ("base_only", excluded, excluded),
    )
    for kind, subset, arm in criteria:
        example = {"kind": kind, "fallback": not bool(subset)}
        pair = next(iter(subset or arm or trades), None)
        if pair is None:
            example.update({"trade": None, "h1": [], "m15": []})
        else:
            setup = pair[0]
            signal_time = setup["signal"]["open_ms"]
            exit_time = setup["exit"]["open_ms"]
            exit_hour = exit_time // H1 * H1
            example.update({
                "trade": setup,
                "h1": chart_window(hourly, signal_time - 8 * H1, exit_hour + 8 * H1, H1, start, end),
                "m15": chart_window(bars, exit_time - 8 * M15, exit_time + 8 * M15, M15, start, end),
            })
        chosen.append(example)
    return chosen


def run(raw, protocol):
    bars, hourly, zero_volume, sources, coverage = load_bars(raw, protocol)
    periods = {}
    setups, screened = [], []
    holdout_trades = []
    for period in protocol["periods"]:
        key = period["key"]
        result, period_setups, trades, exclusions = test_period(period, hourly, bars, zero_volume, protocol)
        periods[key] = result
        setups.extend(period_setups)
        screened.extend(exclusions)
        if key == "holdout":
            holdout_trades = trades
    return {
        "schema": "mpf.btc-h1-negative-delta.v1",
        "protocol_sha256": EXPECTED_PROTOCOL,
        "protocol_frozen_utc": FROZEN_UTC,
        "protocol": protocol,
        "sources": sources,
        "coverage": coverage,
        "periods": periods,
        "setups": setups,
        "screened_candidates": screened,
        "examples": examples_for(holdout_trades, hourly, bars, coverage),
    }


def main():
    directory = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--protocol", type=Path, default=directory / "protocol.json")
    parser.add_argument("--raw-dir", type=Path, default=directory / "raw")
    parser.add_argument("--output", type=Path, default=directory / "evidence.json")
    args = parser.parse_args()
    source = args.protocol.read_bytes()
    digest = sha256(source).hexdigest()
    if digest != EXPECTED_PROTOCOL:
        raise ValueError(f"Frozen protocol hash mismatch: {digest}")
    evidence = run(args.raw_dir, json.loads(source))
    partial = args.output.with_name(args.output.name + ".part")
    partial.write_text(json.dumps(evidence, separators=(",", ":"), ensure_ascii=False) + "\n", encoding="utf-8")
    partial.replace(args.output)
    print(json.dumps({key: value for key, value in evidence.items() if key in ("coverage", "periods")}, indent=2))


if __name__ == "__main__":
    main()
