#!/usr/bin/env python3
"""Synthetic teaching fixture for Bailey/Lopez de Prado (2014), Eq. (2).

Python 3.10+, standard library only. Not the EdgeVeris application engine.
No network, market data, secret keys or random runtime state.
"""
from __future__ import annotations

import argparse
import copy
import html
import json
import math
from pathlib import Path
from statistics import NormalDist, fmean, stdev, variance
import sys

sys.dont_write_bytecode = True
NORMAL = NormalDist()
EULER_GAMMA = 0.5772156649015329
HERE = Path(__file__).resolve().parent


def finite(value, name):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise ValueError(f"{name} must be a finite number")
    return float(value)


def moments(returns):
    if not isinstance(returns, list) or len(returns) < 4:
        raise ValueError("This fixture requires at least four return observations, not a sufficiency guarantee")
    values = [finite(x, "return") for x in returns]
    mean = fmean(values)
    sd = stdev(values)  # ddof=1
    if sd <= 0:
        raise ValueError("Return standard deviation must be positive")
    centered = [x - mean for x in values]
    m2 = fmean([x * x for x in centered])
    return {
        "observations": len(values), "mean": mean, "sampleSd": sd,
        "periodSharpe": mean / sd,
        "skewness": fmean([x ** 3 for x in centered]) / m2 ** 1.5,
        "pearsonKurtosis": fmean([x ** 4 for x in centered]) / m2 ** 2,
    }


def psr(sr, n, skew, kurtosis, benchmark):
    sr, skew, kurtosis, benchmark = [finite(v, name) for v, name in
        zip((sr, skew, kurtosis, benchmark), ("Sharpe", "skewness", "Pearson kurtosis", "benchmark"))]
    if type(n) is not int or n < 2:
        raise ValueError("Sample length must be an integer of at least two")
    if kurtosis < skew * skew + 1 - 1e-12:
        raise ValueError("Raw standardized moments violate the Pearson moment inequality")
    adjustment = 1 - skew * sr + (kurtosis - 1) * sr * sr / 4
    if not math.isfinite(adjustment) or adjustment <= 0:
        raise ValueError("Sharpe variance adjustment must be finite and positive")
    z = (sr - benchmark) * math.sqrt(n - 1) / math.sqrt(adjustment)
    return {"varianceAdjustment": adjustment, "z": z, "score": NORMAL.cdf(z)}


def expected_maximum(trial_sd, n):
    trial_sd = finite(trial_sd, "cross-trial Sharpe standard deviation")
    if trial_sd <= 0:
        raise ValueError("Cross-trial Sharpe dispersion must be positive")
    if type(n) is not int or n < 2:
        raise ValueError("The published expected-maximum approximation requires at least two trials here")
    return trial_sd * ((1 - EULER_GAMMA) * NORMAL.inv_cdf(1 - 1 / n)
                       + EULER_GAMMA * NORMAL.inv_cdf(1 - 1 / (n * math.e)))


def not_enough(reason):
    return {"status": "not_enough_evidence", "reason": reason, "dsr": None}


def evaluate_case(fixture, case):
    sample = fixture["samples"][case["sample"]]
    m = moments(sample["returns"])
    history = fixture["histories"].get(case.get("history"))
    if history is None or history.get("complete") is not True:
        return not_enough("Complete comparable trial history is not supplied")
    if case.get("independentTrialsAssumed") is not True:
        return not_enough("An independent-trial count is not justified or explicitly assumed")
    records = history["trials"]
    if len(records) < 2:
        return not_enough("A single winner does not estimate cross-trial dispersion")
    ids = [r["id"] for r in records]
    if len(ids) != len(set(ids)):
        raise ValueError("Duplicate trial identities")
    scores = [finite(r["periodSharpe"], "trial Sharpe") for r in records]
    winner = max(scores)
    selected = [r for r in records if r["id"] == case["selected"]]
    if len(selected) != 1 or not math.isclose(selected[0]["periodSharpe"], m["periodSharpe"], abs_tol=1e-11):
        raise ValueError("Selected return sample does not reproduce its trial Sharpe")
    if sum(math.isclose(x, winner, abs_tol=1e-12) for x in scores) != 1 or not math.isclose(m["periodSharpe"], winner, abs_tol=1e-11):
        raise ValueError("This teaching protocol requires the unique maximum Sharpe candidate")
    sd = stdev(scores)
    benchmark = expected_maximum(sd, len(scores))
    result = psr(m["periodSharpe"], m["observations"], m["skewness"], m["pearsonKurtosis"], benchmark)
    return {"status": "conditional_synthetic_score", "moments": m, "rawTrials": len(scores),
            "trialVariance": variance(scores), "trialSd": sd, "benchmark": benchmark,
            "annualizedDisplay": m["periodSharpe"] * math.sqrt(fixture["periodsPerYearForDisplay"]),
            "psrZero": psr(m["periodSharpe"], m["observations"], m["skewness"], m["pearsonKurtosis"], 0)["score"],
            "dsr": result["score"], "z": result["z"], "varianceAdjustment": result["varianceAdjustment"]}


def synthetic_sample(n, sr, tail=False):
    # Hand-built quantiles, not independent empirical returns or a simulation study.
    values = [NORMAL.inv_cdf((i + .5) / n) for i in range(n)]
    if tail:
        values[0] = -15
    mean, sd = fmean(values), stdev(values)
    returns = [round(.01 * (sr + (v - mean) / sd), 15) for v in values]
    # A fixed permutation changes presentation only. Moments do not depend on order.
    step = next(k for k in range(73, n + 74) if math.gcd(k, n) == 1)
    returns = [returns[(i * step) % n] for i in range(n)]
    return {"construction": "normal mid-quantiles, optionally one tail shock, centered/scaled then fixed permutation",
            "targetPeriodSharpe": sr, "returns": returns}


def make_fixture():
    base = [-.12, -.08, -.05, -.02, 0, .02, .04, .06, .09, .15]
    histories = {}
    for n in (10, 50, 100):
        values = base + [round(-.13 + .26 * (j + .5) / (n - 10), 6) for j in range(n - 10)]
        histories[f"search{n}"] = {"complete": True, "trials": [
            {"id": f"C{i+1:03}", "periodSharpe": value} for i, value in enumerate(values)]}
    values = [.025, .035, .045, .055, .06, .065, .07, .075, .085, .10]
    histories["moderate10"] = {"complete": True, "trials": [
        {"id": f"M{i+1:03}", "periodSharpe": value} for i, value in enumerate(values)]}
    cases = [{"id": f"search{n}", "sample": "selected", "history": f"search{n}",
              "selected": "C010", "independentTrialsAssumed": True} for n in (10, 50, 100)]
    cases += [{"id": "moderate", "sample": "moderate", "history": "moderate10", "selected": "M010", "independentTrialsAssumed": True},
              {"id": "short", "sample": "short", "history": "search10", "selected": "C010", "independentTrialsAssumed": True},
              {"id": "tail", "sample": "tail", "history": "search10", "selected": "C010", "independentTrialsAssumed": True},
              {"id": "missingHistory", "sample": "selected", "selected": "C010", "independentTrialsAssumed": True},
              {"id": "unknownDependence", "sample": "selected", "history": "search100", "selected": "C010", "independentTrialsAssumed": None}]
    return {"schema": "edgeveris-synthetic-dsr-v1", "synthetic": True,
            "formula": "Bailey and Lopez de Prado (2014), equation 2, zero-mean null",
            "returnUnits": "decimal net excess return per artificial daily observation; zero risk-free reference",
            "periodsPerYearForDisplay": 252,
            "conventions": {"returnVarianceDof": 1, "trialVarianceDof": 1,
                            "skewness": "m3 / m2^(3/2), central moments use divisor T",
                            "kurtosis": "m4 / m2^2, Pearson not excess",
                            "trialAssumption": "Independent trials and normal null SR distribution are stipulated for arithmetic, not proved by summaries",
                            "serialDependence": "No long-run autocovariance correction. Constructed sample is not an empirical calibration study"},
            "samples": {"selected": synthetic_sample(252, .15), "moderate": synthetic_sample(1260, .10),
                        "short": synthetic_sample(20, .15), "tail": synthetic_sample(252, .15, tail=True)},
            "histories": histories, "cases": cases}


def rounded(value):
    if isinstance(value, float):
        return round(value, 12)
    if isinstance(value, list):
        return [rounded(x) for x in value]
    if isinstance(value, dict):
        return {k: rounded(v) for k, v in value.items()}
    return value


def run_fixture(fixture):
    if fixture.get("synthetic") is not True:
        raise ValueError("This public runner only accepts its declared synthetic teaching fixture")
    results = {case["id"]: evaluate_case(fixture, case) for case in fixture["cases"]}
    base = results["search10"]
    m = base["moments"]
    sensitivity = []
    for n in (2, 5, 10, 20, 50, 100, 250, 500):
        benchmark = expected_maximum(base["trialSd"], n)
        sensitivity.append({"assumedIndependentTrials": n, "fixedTrialSd": base["trialSd"],
                            "benchmark": benchmark, "dsr": psr(m["periodSharpe"], m["observations"], m["skewness"], m["pearsonKurtosis"], benchmark)["score"]})
    paper = []
    for n in (100, 46):
        benchmark = expected_maximum(math.sqrt(.5 / 250), n)
        paper.append({"trials": n, "benchmark": benchmark,
                      "dsr": psr(2.5 / math.sqrt(250), 1250, -3, 10, benchmark)["score"]})
    return rounded({"schema": "edgeveris-synthetic-dsr-v1", "results": results,
                    "countOnlySensitivity": sensitivity, "publishedPaperControl": paper})


def svg_open(title, desc, height):
    return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 {height}" width="720" height="{height}" role="img" aria-labelledby="title desc"><title id="title">{html.escape(title)}</title><desc id="desc">{html.escape(desc)}</desc><rect width="720" height="{height}" rx="12" fill="#0e1a29"/><g font-family="Arial, sans-serif" fill="#e7eef9">'


def render_scores(output):
    rows = [output["results"][f"search{n}"] for n in (10, 50, 100)]
    svg = svg_open("Same selected Sharpe, different search context", "All three ledgers have chosen daily Sharpe 0.15 and 252 observations. Conditional DSR falls as trial count and measured dispersion change. Exact values appear in the adjacent table.", 430)
    svg += '<text x="30" y="36" font-size="21" font-weight="700">Same chosen return sample. Different search history.</text><text x="30" y="61" font-size="14" fill="#b3c3d8">Synthetic ledgers · native SR 0.15 · 252 observations</text>'
    for pct in (0, 25, 50, 75, 100):
        y = 340 - pct * 2.1
        svg += f'<path d="M88 {y}H684" stroke="#314257"/><text x="75" y="{y+5}" text-anchor="end" font-size="13">{pct}%</text>'
    for i, row in enumerate(rows):
        center = 185 + 190 * i
        for offset, key, color in [(-49, "psrZero", "#5facff"), (7, "dsr", "#43d8bc")]:
            height = row[key] * 210
            svg += f'<rect x="{center+offset}" y="{340-height:.3f}" width="42" height="{height:.3f}" fill="{color}"/><text x="{center+offset+21}" y="{328-height:.3f}" text-anchor="middle" font-size="14">{row[key]*100:.2f}%</text>'
        svg += f'<text x="{center}" y="365" text-anchor="middle" font-size="15">{row["rawTrials"]} trials</text><text x="{center}" y="385" text-anchor="middle" font-size="12" fill="#b3c3d8">SR dispersion {row["trialSd"]:.6f}</text>'
    svg += '<rect x="205" y="82" width="14" height="14" fill="#5facff"/><text x="226" y="94" font-size="14">PSR vs zero</text><rect x="391" y="82" width="14" height="14" fill="#43d8bc"/><text x="412" y="94" font-size="14">Conditional DSR</text><text transform="translate(23 237) rotate(-90)" text-anchor="middle" font-size="14">Model score</text><text x="360" y="416" text-anchor="middle" font-size="14">Complete synthetic trial ledgers (not empirical market findings)</text></g></svg>'
    return svg


def render_eligibility(output):
    missing = output["results"]["missingHistory"]["status"].replace("_", " ")
    svg = svg_open("DSR evidence requirements", "Chosen returns give Sharpe, sample length and moments. Complete comparable trial history gives dispersion. A defensible independent-trial assumption gives the count. Missing history or unknown dependence means not enough evidence, not a numerical DSR.", 410)
    svg += '<text x="30" y="36" font-size="21" font-weight="700">Three inputs. No shortcut from the winner alone.</text>'
    labels = [("1. Chosen excess-return sample", "Period SR, T, skewness and Pearson kurtosis"), ("2. Complete comparable trial ledger", "All trial Sharpes, including unselected candidates"), ("3. Defensible trial-count model", "Independence or a justified effective-count method")]
    for i, (title, desc) in enumerate(labels):
        y = 65 + i * 71
        svg += f'<rect x="30" y="{y}" width="660" height="57" rx="6" fill="#15263b" stroke="#46617e"/><text x="46" y="{y+23}" font-size="16" font-weight="700">{title}</text><text x="46" y="{y+44}" font-size="14" fill="#c1cee0">{desc}</text>'
    svg += '<path d="M360 270v21m-5-5 5 5 5-5" fill="none" stroke="#b7c8dc" stroke-width="2"/><rect x="30" y="300" width="319" height="72" rx="6" fill="#132e36" stroke="#43d8bc"/><text x="46" y="326" font-size="15" font-weight="700">Declared assumptions available</text><text x="46" y="351" font-size="14">Conditional model score, not proof</text><rect x="365" y="300" width="325" height="72" rx="6" fill="#302a20" stroke="#e6c784"/>'
    svg += f'<text x="381" y="326" font-size="15" font-weight="700">History / count not established</text><text x="381" y="351" font-size="14">{missing.capitalize()} · score withheld</text><text x="360" y="396" text-anchor="middle" font-size="13" fill="#b3c3d8">Availability of numbers does not establish validity of assumptions.</text></g></svg>'
    return svg


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true")
    parser.add_argument("--write", type=Path, help="Generate the complete teaching package in a new directory")
    args = parser.parse_args()
    if args.write:
        fixture = make_fixture()
        output = run_fixture(fixture)
        args.write.mkdir(parents=True, exist_ok=False)
        (args.write / "fixture.json").write_text(json.dumps(fixture, indent=2) + "\n")
        (args.write / "expected.json").write_text(json.dumps(output, indent=2) + "\n")
        (args.write / "search-context.svg").write_text(render_scores(output) + "\n")
        (args.write / "eligibility.svg").write_text(render_eligibility(output) + "\n")
        print(f"Generated synthetic evidence in {args.write}")
        return
    fixture = json.loads((HERE / "fixture.json").read_text())
    output = run_fixture(fixture)
    assert output == run_fixture(copy.deepcopy(fixture)), "Repeated output differs"
    if args.check:
        assert output == json.loads((HERE / "expected.json").read_text()), "Known answer differs"
        assert render_scores(output) + "\n" == (HERE / "search-context.svg").read_text()
        assert render_eligibility(output) + "\n" == (HERE / "eligibility.svg").read_text()
        print("PASS: two identical runs, complete expected output and both generated figures")
    else:
        print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()
