"""CRJ-2026-012: synthetic measurement audits for action value, not proprietary OBV.

Run: python reproduce.py [output_directory]
Requires Python 3.10+, NumPy; standard-library fractions provide exact checks.
All parameters are designed rather than estimated from professional football.
"""
from __future__ import annotations

import hashlib
import json
import math
import platform
import sys
from datetime import datetime, timezone
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent
OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT
OUT.mkdir(parents=True, exist_ok=True)
SEED = 20261204012
rng = np.random.default_rng(SEED)

Q = np.array([[.15,.55,.05,.10],[.10,.15,.50,.15],[0,.20,.10,.10],[.15,.10,0,.20]])
# Absorbing outcomes: for-chance, against-chance, neutral end.
R = np.array([[0,0,.15],[0,0,.10],[.50,0,.10],[0,.55,0]])
reward = np.array([.20,-.15,0.])
r = R @ reward
assert np.allclose(Q.sum(axis=1)+R.sum(axis=1),1)
v = np.linalg.solve(np.eye(4)-Q,r)

def finite_value(mat, rew, horizon):
    value = np.zeros(len(rew))
    for _ in range(horizon):
        value = rew + mat @ value
    return value

def expanded(subdivision):
    """Delay each physical transition until the last of k zero-time records.

    k changes the event encoding only. No physical time is added. Intermediate
    records contain no additional information; next-state outcome is not revealed
    until the final record. This is a metrology counterexample, not a data format.
    """
    n=4*subdivision
    mat=np.zeros((n,n)); rew=np.zeros(n)
    for s in range(4):
        for phase in range(subdivision):
            i=s*subdivision+phase
            if phase<subdivision-1:
                mat[i,i+1]=1
            else:
                for target in range(4):
                    mat[i,target*subdivision]=Q[s,target]
                rew[i]=r[s]
    return mat,rew

e01=[]
for horizon in [3,5,10,20,40]:
    for subdivision in [1,2,4]:
        mat,rew=expanded(subdivision)
        state_ids=np.arange(4)*subdivision
        fixed=finite_value(mat,rew,horizon)[state_ids]
        matched=finite_value(mat,rew,horizon*subdivision)[state_ids]
        infinite=np.linalg.solve(np.eye(len(rew))-mat,rew)[state_ids]
        reference=finite_value(Q,r,horizon)
        e01.append({"records":horizon,"records_per_transition":subdivision,
                    "fixed_record_values":fixed.tolist(),
                    "matched_physical_horizon_values":matched.tolist(),
                    "eventual_values":infinite.tolist(),
                    "matched_max_abs_error":float(np.max(np.abs(reference-matched))),
                    "eventual_max_abs_error":float(np.max(np.abs(v-infinite)))})

e02=[]
replicates=10000
for length in [5,10,20]:
    for rho in [-.5,0,.5,.9]:
        sigma=.02
        covariance=sigma**2*rho**np.abs(np.arange(length+1)[:,None]-np.arange(length+1)[None,:])
        errors=rng.normal(size=(replicates,length+1)) @ np.linalg.cholesky(covariance).T
        action_errors=np.diff(errors,axis=1)
        for label,selected in [("first_action",[0]),("full_chain",list(range(length))),
                               ("alternating_player",list(range(0,length,2)))]:
            b=np.zeros(length+1)
            for i in selected:
                b[i]-=1;b[i+1]+=1
            exact_var=float(b@covariance@b)
            naive_var=len(selected)*2*sigma**2*(1-rho)
            summed=action_errors[:,selected].sum(axis=1)
            exact_sd=math.sqrt(exact_var);naive_sd=math.sqrt(naive_var)
            coverage=float(np.mean(np.abs(summed)<=1.959963984540054*exact_sd))
            naive_coverage=float(np.mean(np.abs(summed)<=1.959963984540054*naive_sd))
            # Exact repeated-experiment coverage under our Gaussian specification.
            analytic_naive_coverage=math.erf(1.959963984540054*naive_sd/exact_sd/math.sqrt(2))
            e02.append({"transitions":length,"rho":rho,"aggregation":label,
                        "selected_action_count":len(selected),"replicates":replicates,
                        "state_error_sd":sigma,"exact_sd":exact_sd,
                        "naive_independent_sd":naive_sd,"naive_to_exact_sd":naive_sd/exact_sd,
                        "simulated_sd":float(np.std(summed,ddof=1)),
                        "coverage_correct":coverage,"coverage_naive":naive_coverage,
                        "analytic_coverage_naive":analytic_naive_coverage,
                        "coverage_mc_se_correct":math.sqrt(coverage*(1-coverage)/replicates),
                        "coverage_mc_se_naive":math.sqrt(naive_coverage*(1-naive_coverage)/replicates)})

prob=np.array([.02,.08,.20]);weights=np.array([.50,.30,.20])
mu=float(weights@prob)
vp=float(weights@(prob-mu)**2)
within=float(weights@(prob*(1-prob)))
vy=mu*(1-mu)
e03=[]
mc_reps=5000
for n in [25,100,500,1000,2000]:
    p=rng.choice(prob,size=(mc_reps,n),p=weights)
    y=(rng.random(size=p.shape)<p)
    for method,bias in [("goals",0),("calibrated_probability",0),
                        ("biased_probability_0.005",.005),("biased_probability_0.010",.010),
                        ("biased_probability_0.020",.020)]:
        estimates=y.mean(axis=1) if method=="goals" else p.mean(axis=1)+bias
        mse=(estimates-mu)**2
        exact=vy/n if method=="goals" else vp/n+bias*bias
        e03.append({"n":n,"replicates":mc_reps,"method":method,"bias":bias,
                    "exact_mse":exact,"exact_rmse":math.sqrt(exact),
                    "simulated_mse":float(mse.mean()),
                    "mse_mc_se":float(mse.std(ddof=1)/math.sqrt(mc_reps)),
                    "simulated_bias":float(estimates.mean()-mu)})

parameters={"study_id":"CRJ-2026-012","evidence_class":"synthetic/methodological",
    "seed":SEED,"states":["build_up","midfield","attack","opposition_danger"],
    "Q":Q.tolist(),"absorption_probabilities":R.tolist(),"terminal_rewards":reward.tolist(),
    "units":"net expected-goal surrogate units per modelled sequence; not provider OBV",
    "E01":{"horizons":[3,5,10,20,40],"subdivision":[1,2,4]},
    "E02":{"path_lengths":[5,10,20],"rho":[-.5,0,.5,.9],"state_error_sd":.02,"replicates":replicates},
    "E03":{"probabilities":prob.tolist(),"weights":weights.tolist(),"sample_sizes":[25,100,500,1000,2000],"biases":[.005,.010,.020],"replicates":mc_reps}}
results={"study_id":"CRJ-2026-012","experiment_ids":["CRJ-2026-012-E01","CRJ-2026-012-E02","CRJ-2026-012-E03"],
    "evidence_class":"synthetic/methodological","eventual_value":v.tolist(),
    "bellman_residual":float(np.max(np.abs(v-(r+Q@v)))),
    "E01":e01,"E02":e02,"E03":e03,
    "target_moments":{"mean":mu,"variance_probability":vp,"mean_bernoulli_variance":within,
                      "variance_goal":vy,"bias_crossovers_n":{str(b):within/(b*b) for b in [.005,.010,.020]}}}

def write_json(name,data):
    content=json.dumps(data,ensure_ascii=False,sort_keys=True,indent=2,allow_nan=False)+"\n"
    (OUT/name).write_text(content,encoding="utf-8")
    return hashlib.sha256(content.encode()).hexdigest()

parameter_hash=write_json("parameters.json",parameters)
output_hash=write_json("results.json",results)
receipt={"executed_utc":datetime.now(timezone.utc).isoformat(),"python":platform.python_version(),
         "numpy":np.__version__,"seed":SEED,"parameters_sha256":parameter_hash,"results_sha256":output_hash,
         "code_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
         "simulation_replications":{"E02":replicates,"E03":mc_reps},
         "status":"EXECUTED_INTERNAL_CHECKS_PENDING","professional_matches":0,"professional_players":0}
write_json("execution-receipt.json",receipt)
print(json.dumps({"eventual_value":v.tolist(),"target_moments":results["target_moments"],
                  "execution":receipt},indent=2))
