"""validate_operational_alpha_calibration_v2.py — OPERATIONAL_ALPHA_CALIBRATION_VALIDATE_V2

Temp/operational_alpha_calibration_v2.json의 최소 계약을 검증한다.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INPUT = ROOT / "Temp" / "operational_alpha_calibration_v2.json"
DEFAULT_OUT = ROOT / "Temp" / "validate_operational_alpha_calibration_v2.json"
FORMULA_ID = "OPERATIONAL_ALPHA_CALIBRATION_VALIDATE_V2"


def _load(path: Path) -> Any:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}


def _is_dict(value: Any) -> bool:
    return isinstance(value, dict)


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

    input_path = Path(args.input)
    input_path = input_path if input_path.is_absolute() else ROOT / input_path
    out_path = Path(args.out)
    out_path = out_path if out_path.is_absolute() else ROOT / out_path

    payload = _load(input_path)
    errors: list[str] = []

    if not _is_dict(payload):
        errors.append("payload must be object")
    else:
        if payload.get("formula_id") != "OPERATIONAL_ALPHA_CALIBRATION_V2":
            errors.append("formula_id mismatch")
        if payload.get("gate") not in {"PERFORMANCE_READY", "NOT_READY"}:
            errors.append(f"gate={payload.get('gate')}")
        if "performance_ready" not in payload or not isinstance(payload.get("performance_ready"), bool):
            errors.append("performance_ready must be bool")
        if "confidence_score" not in payload or not isinstance(payload.get("confidence_score"), (int, float)):
            errors.append("confidence_score must be numeric")
        for key in ["metrics", "targets", "readiness_reasons"]:
            if key not in payload:
                errors.append(f"missing field: {key}")
        metrics = payload.get("metrics")
        if isinstance(metrics, dict):
            for key in [
                "outcome_quality_score",
                "t20_operational_sample",
                "t20_operational_pass_rate",
                "t5_operational_sample",
                "t5_operational_pass_rate",
                "trade_quality_t5_score",
                "value_damage_pct_avg",
            ]:
                if key not in metrics:
                    errors.append(f"missing field: metrics.{key}")
        targets = payload.get("targets")
        if isinstance(targets, dict):
            for key in [
                "outcome_quality_score_min",
                "t20_operational_sample_min",
                "t20_operational_pass_rate_min",
                "t5_operational_sample_min",
                "t5_operational_pass_rate_min",
                "trade_quality_t5_score_min",
                "value_damage_pct_avg_max",
            ]:
                if key not in targets:
                    errors.append(f"missing field: targets.{key}")

        reasons = payload.get("readiness_reasons")
        if isinstance(reasons, list):
            if payload.get("gate") == "PERFORMANCE_READY" and reasons:
                errors.append("PERFORMANCE_READY must not have readiness reasons")
            if payload.get("gate") == "NOT_READY" and not reasons:
                errors.append("NOT_READY must have readiness reasons")

    result = {
        "formula_id": FORMULA_ID,
        "gate": "PASS" if not errors else "FAIL",
        "checked_file": str(Path(args.input).as_posix()),
        "errors": errors,
    }
    out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if not errors else 1


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