"""Proof v2: world with planted gaps -> pass 1 raw -> fit calibration on a
CALIBRATION split -> pass 2 corrected on a HELD-OUT split -> pipeline smoke."""
import json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import pandas as pd
from engine.world import build_world, build_schedule
from engine.reference import ReferenceData
from engine.pipeline import estimate_frame, backtest, fit_calibration, run_pipeline

ref_frames, truth_fn = build_world(seed=7)
ref = ReferenceData.from_frames(ref_frames)
ref.save_fixtures("fixtures")
print(f"[world] history observations: {len(ref.evidence()):,}")

def truth_of(s):
    return s.rename(columns={"country_name":"country","channel_name":"channel",
                             "sports_teams":"teams"}).apply(truth_fn, axis=1)

cal_sched  = build_schedule(ref_frames, seed=21, n_rows=400)
test_sched = build_schedule(ref_frames, seed=99, n_rows=400)
cal_truth, test_truth = truth_of(cal_sched), truth_of(test_sched)

est_raw = estimate_frame(test_sched, ref)
print("[held-out | RAW]", json.dumps(backtest(est_raw, test_truth), indent=2))

corr, sig = fit_calibration(estimate_frame(cal_sched, ref), cal_truth)
print("[calibration] corrections:", {k: round(v,3) for k,v in corr.items()},
      "| sigma:", {k: round(v,3) for k,v in sig.items()})

est_cal = estimate_frame(test_sched, ref, sigma_by_tier=sig, correction_by_tier=corr)
print("[held-out | CALIBRATED]", json.dumps(backtest(est_cal, test_truth), indent=2))

test_sched.to_excel("uploads/PROOF.xlsx", index=False)
Path("worker/config.json").write_text(json.dumps({"reference_mode":"fixtures","fixtures_dir":"fixtures"}))
res = run_pipeline(upload_path=Path("uploads/PROOF.xlsx"), exports_dir=Path("exports"),
                   run_id="PROOF001", on_progress=lambda p,s,d="": None,
                   config_path=Path("worker/config.json"))
print("[pipeline]", {k: (str(v) if isinstance(v, Path) else v) for k, v in res.items()})
