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

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

import yaml


REQUIRED_STATES = {"pending", "running", "succeeded", "failed", "retrying", "blocked"}


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

    contract_path = Path(args.contract).resolve()
    payload: dict[str, Any] = {
        "formula_id": "WBS_10_DOTNET_SCHEDULER_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_SCHEDULER_CONTRACT_V1":
        payload["missing"].append("formula_id")
    if data.get("goal") != "스케줄러 상태 전이, 의존성, 재시도, 감사 추적을 표준화한다.":
        payload["missing"].append("goal")

    machine = data.get("state_machine") or {}
    states = set(machine.get("states") or [])
    if REQUIRED_STATES - states:
        payload["missing"].append("state_machine.states")

    transitions = machine.get("allowed_transitions") or {}
    for state in REQUIRED_STATES:
        if state not in transitions:
            payload["missing"].append(f"allowed_transitions.{state}")

    job_definitions = data.get("job_definitions") or []
    job_ids = {item.get("job_id", "") for item in job_definitions}
    for required in {"daily-collection", "hourly-price-update", "weekly-report", "monthly-optimization"} - job_ids:
        payload["missing"].append(f"{required} missing")

    if not data.get("audit_fields"):
        payload["missing"].append("audit_fields")
    if data.get("idempotency", {}).get("required") is not True:
        payload["missing"].append("idempotency.required")

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

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