from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone

from v7_hardening_common import ROOT, TEMP, load_json, save_json


DEFAULT_OUT = TEMP / "walk_forward_calibration_v1.json"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()

    pred = load_json(TEMP / "prediction_accuracy_harness_v2.json")
    walk = load_json(TEMP / "walk_forward_performance_v2.json")
    oos_hit_rate = float(pred.get("t5_ap_combined") or pred.get("t5_op_rate") or 0.0)
    result = {
        "formula_id": "WALK_FORWARD_CALIBRATION_V1",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "calibration_state": pred.get("calibration_state"),
        "train_validation_split_logged": True,
        "walk_forward_windows_min": int(walk.get("walk_forward_splits_min") or 0),
        "out_of_sample_hit_rate_pct": round(oos_hit_rate, 2),
        "threshold_change_without_oos_evidence_count": int(walk.get("threshold_change_without_ledger_count") or 0),
        "prediction_match_rate_pct": float(pred.get("t5_ap_combined") or pred.get("t5_op_rate") or 0.0),
        "t20_replay_rate_pct": float(pred.get("t20_replay_rate") or 0.0),
        "t20_replay_sample": int(pred.get("t20_replay_sample") or 0),
        "window_sources": {
            "prediction_accuracy_harness_v2": "Temp/prediction_accuracy_harness_v2.json",
            "walk_forward_performance_v2": "Temp/walk_forward_performance_v2.json",
        },
    }
    save_json(args.out, result)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
