"""Independently replay the frozen experiment from exported native decisions."""

import csv
import math
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
SEEDS = (104729, 130363, 155921, 180503, 205279, 229969, 254749, 279511)
METHODS = ("rolling", "ewma", "fixed")


def close(actual, expected, field):
    if not math.isclose(float(actual), expected, rel_tol=2e-10, abs_tol=2e-12):
        raise AssertionError(f"{field}: {actual} != {expected}")


def uniforms(seed):
    state = seed
    while True:
        state ^= (state << 13) & 0xffffffff
        state ^= state >> 17
        state ^= (state << 5) & 0xffffffff
        state &= 0xffffffff
        yield (state + 0.5) / 4294967296.0


def innovations(seed):
    stream = uniforms(seed)
    for _ in range(800):
        first, second = next(stream), next(stream)
        yield math.sqrt(-2.0 * math.log(first)) * math.cos(2.0 * math.pi * second)


def main():
    tables = {}
    for filename, expected_fields in (
        ("sizing_decisions.csv", (
            "scenario", "seed", "observed_bar", "sized_bar", "innovation",
            "observed_log_return", "current_true_variance", "next_true_variance", "method",
            "estimated_next_variance", "estimated_next_sd", "desired_exposure", "exposure",
            "capped", "estimated_exposure_risk", "oracle_next_sd", "oracle_exposure_risk",
            "excess_risk", "shortfall_risk", "turnover",
        )),
        ("sizing_summary.csv", (
            "scenario", "seed", "method", "observations", "capped_count",
            "mean_absolute_risk_deviation", "mean_excess_risk", "mean_shortfall_risk",
            "mean_turnover",
        )),
    ):
        with (EVIDENCE / filename).open(newline="") as file:
            reader = csv.DictReader(file, strict=True)
            fields = reader.fieldnames
            if (fields is None or len(fields) != len(set(fields))
                    or set(fields) != set(expected_fields)):
                raise AssertionError(f"{filename}: missing, unexpected or duplicate columns")
            tables[filename] = []
            for row in reader:
                if None in row or any(value is None for value in row.values()):
                    raise AssertionError(f"{filename}: incorrect row width at line {reader.line_num}")
                tables[filename].append(row)
    rows = tables["sizing_decisions.csv"]
    if len(rows) != 8 * 2 * 600 * 3:
        raise AssertionError(f"Unexpected decision count: {len(rows)}")
    indexed = {(r["scenario"], int(r["seed"]), int(r["observed_bar"]), r["method"]): r for r in rows}
    if len(indexed) != len(rows):
        raise AssertionError("Duplicate decision keys")

    for seed in SEEDS:
        tape = list(innovations(seed))
        for scenario in ("constant", "clustered"):
            h = 0.0001
            ewma = 0.0001
            squares = []
            prior_exposures = {}
            for index, z in enumerate(tape):
                ret = math.sqrt(h) * z
                next_h = (0.000002 + 0.08 * ret**2 + 0.90 * h
                          if scenario == "clustered" else 0.0001)
                squares.append(ret**2)
                ewma = 0.94 * ewma + 0.06 * ret**2
                if index >= 200:
                    rolling = sum(squares[-20:]) / 20
                    for method, estimate in (("rolling", rolling), ("ewma", ewma), ("fixed", 0.0001)):
                        row = indexed[(scenario, seed, index + 1, method)]
                        if int(row["sized_bar"]) != index + 2:
                            raise AssertionError("Incorrect next-bar decision index")
                        close(row["innovation"], z, "innovation")
                        close(row["observed_log_return"], ret, "observed return")
                        close(row["current_true_variance"], h, "current variance")
                        close(row["next_true_variance"], next_h, "next variance")
                        close(row["estimated_next_variance"], estimate, "estimated variance")
                        close(row["estimated_next_sd"], math.sqrt(estimate), "estimated sd")
                        desired = 0.75 if method == "fixed" else 0.0075 / math.sqrt(estimate)
                        exposure = min(desired, 1.5)
                        close(row["desired_exposure"], desired, "desired exposure")
                        close(row["exposure"], exposure, "exposure")
                        if int(row["capped"]) != int(desired > 1.5):
                            raise AssertionError("Incorrect exposure-cap flag")
                        risk = exposure * math.sqrt(next_h)
                        close(row["oracle_next_sd"], math.sqrt(next_h), "oracle sd")
                        close(row["estimated_exposure_risk"], exposure * math.sqrt(estimate), "estimated risk")
                        close(row["oracle_exposure_risk"], risk, "oracle risk")
                        close(row["excess_risk"], max(risk - 0.0075, 0), "excess")
                        close(row["shortfall_risk"], max(0.0075 - risk, 0), "shortfall")
                        turnover = abs(exposure - prior_exposures[method]) if method in prior_exposures else 0
                        close(row["turnover"], turnover, "turnover")
                        prior_exposures[method] = exposure
                h = next_h

    grouped = defaultdict(list)
    for row in rows:
        grouped[(row["scenario"], int(row["seed"]), row["method"])].append(row)
    summaries = tables["sizing_summary.csv"]
    if len(summaries) != 48:
        raise AssertionError(f"Unexpected summary count: {len(summaries)}")
    summary_keys = [(r["scenario"], int(r["seed"]), r["method"]) for r in summaries]
    if len(set(summary_keys)) != len(summary_keys):
        raise AssertionError("Duplicate summary keys")
    if set(summary_keys) != set(grouped):
        raise AssertionError("Summary keys do not cover every scenario, seed and method")
    for summary in summaries:
        sample = grouped[(summary["scenario"], int(summary["seed"]), summary["method"])]
        if len(sample) != 600 or int(summary["observations"]) != 600:
            raise AssertionError("Incorrect per-seed observation count")
        if sum(int(r["capped"]) for r in sample) != int(summary["capped_count"]):
            raise AssertionError("Incorrect per-seed cap count")
        n = len(sample)
        for field, values in (
            ("mean_absolute_risk_deviation", [abs(float(r["oracle_exposure_risk"]) - 0.0075) for r in sample]),
            ("mean_excess_risk", [float(r["excess_risk"]) for r in sample]),
            ("mean_shortfall_risk", [float(r["shortfall_risk"]) for r in sample]),
            ("mean_turnover", [float(r["turnover"]) for r in sample]),
        ):
            close(summary[field], sum(values) / n, field)
    print(f"PASS: {len(rows)} decisions; 48 summaries; all eight seeds replayed")


if __name__ == "__main__":
    main()
