#!/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 domain parity backlog")
    parser.add_argument("--backlog", default="docs/WBS_10_DOTNET_DOMAIN_PARITY_BACKLOG.yaml")
    args = parser.parse_args(argv)

    backlog_path = Path(args.backlog).resolve()
    payload: dict[str, Any] = {
        "formula_id": "WBS_10_DOTNET_DOMAIN_PARITY_BACKLOG_V1",
        "gate": "FAIL",
        "missing": [],
        "evidence": {"backlog": str(backlog_path)},
    }

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

    if data.get("formula_id") != "WBS_10_DOTNET_DOMAIN_PARITY_BACKLOG_V1":
        payload["missing"].append("formula_id")
    if data.get("coverage_min") != 1.0:
        payload["missing"].append("coverage_min")
    tolerance = data.get("tolerance_policy") or {}
    if tolerance.get("numeric_default") != 0:
        payload["missing"].append("tolerance_policy.numeric_default")
    if tolerance.get("text_default") != "exact":
        payload["missing"].append("tolerance_policy.text_default")

    targets = data.get("parity_targets") or []
    target_ids = {item.get("target_id", "") for item in targets}
    missing_targets = REQUIRED_TARGETS - target_ids
    for target in sorted(missing_targets):
        payload["missing"].append(f"{target} missing")

    priorities = [item.get("priority") for item in targets]
    if priorities != sorted(priorities):
        payload["missing"].append("priority order")

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

    out_path = backlog_path.parent.parent / "Temp" / "wbs_10_dotnet_domain_parity_backlog_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())
