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

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

import yaml


EXPECTED = {
    "ci": "Validators (Pushes and Pull Requests)",
    "prepare_release": "Prepare Release",
    "deploy_prod": "Deploy to Production",
}


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 CICD chain contract")
    parser.add_argument("--contract", default="docs/WBS_10_DOTNET_CICD_CHAIN_CONTRACT.yaml")
    args = parser.parse_args(argv)

    contract_path = Path(args.contract).resolve()
    payload: dict[str, Any] = {
        "formula_id": "WBS_10_DOTNET_CICD_CHAIN_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_CICD_CHAIN_CONTRACT_V1":
        payload["missing"].append("formula_id")
    if data.get("goal") != "CI, prepare-release, deploy-prod 순차 게이트를 고정한다.":
        payload["missing"].append("goal")

    workflows = data.get("workflows") or {}
    for key, expected_name in EXPECTED.items():
        node = workflows.get(key) or {}
        if node.get("name") != expected_name:
            payload["missing"].append(f"workflows.{key}.name")

    chain = data.get("dependency_chain") or []
    if "Validators (Pushes and Pull Requests) -> Prepare Release -> Deploy to Production" not in chain:
        payload["missing"].append("dependency_chain")

    guards = data.get("required_guards") or []
    if len(guards) < 4:
        payload["missing"].append("required_guards")

    checks = data.get("health_checks") or []
    if len(checks) < 4:
        payload["missing"].append("health_checks")

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

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