#!/usr/bin/env python3
from __future__ import annotations

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

import yaml


REQUIRED_TARGETS = {
    "formula_engine_timing",
    "formula_engine_sell",
    "formula_engine_final",
    "exit_stop_price",
    "exit_stop_ladder",
    "exit_heat_thresholds",
    "factor_calculator",
}


def load_yaml(path: Path) -> dict[str, Any]:
    if not path.exists():
        raise FileNotFoundError(path)
    return yaml.safe_load(path.read_text(encoding="utf-8"))


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Validate WBS-10 dotnet parity contract")
    parser.add_argument("--contract", default="docs/WBS_10_DOTNET_PARITY_CONTRACT.yaml")
    args = parser.parse_args(argv)

    contract_path = Path(args.contract).resolve()
    payload: dict[str, Any] = {
        "formula_id": "WBS_10_DOTNET_PARITY_CONTRACT_V1",
        "gate": "FAIL",
        "missing": [],
        "evidence": {"contract": str(contract_path)},
    }

    try:
        data = load_yaml(contract_path)
    except FileNotFoundError:
        payload["missing"].append("contract missing")
        print(json.dumps(payload, ensure_ascii=False, indent=2))
        return 1

    if data.get("formula_id") != "WBS_10_DOTNET_PARITY_CONTRACT_V1":
        payload["missing"].append("formula_id")
    if data.get("goal") != "Python reference와 .NET domain 결과를 데이터 기반 parity 계약으로 고정한다.":
        payload["missing"].append("goal")

    targets = data.get("targets") or []
    target_ids: set[str] = set()
    for target in targets:
        target_id = target.get("target_id", "")
        target_ids.add(target_id)
        if not target.get("symbol"):
            payload["missing"].append(f"{target_id}.symbol")
        tolerance = target.get("tolerance") or {}
        if "numeric" not in tolerance:
            payload["missing"].append(f"{target_id}.tolerance.numeric")
        if "text" not in tolerance:
            payload["missing"].append(f"{target_id}.tolerance.text")
        if not target.get("evidence"):
            payload["missing"].append(f"{target_id}.evidence")
        if not target.get("pass_condition"):
            payload["missing"].append(f"{target_id}.pass_condition")

    for required in sorted(REQUIRED_TARGETS - target_ids):
        payload["missing"].append(f"{required} missing")

    payload["gate"] = "PASS" if not payload["missing"] else "FAIL"
    payload["message"] = (
        "WBS-10 dotnet parity contract validation passed."
        if payload["gate"] == "PASS"
        else "WBS-10 dotnet parity contract validation failed."
    )

    out_path = contract_path.parent.parent / "Temp" / "wbs_10_dotnet_parity_contract_v1.json"
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0 if payload["gate"] == "PASS" else 1


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