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

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


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


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Validate WBS-10 dotnet domain parity artifact")
    parser.add_argument("--artifact", default="Temp/dotnet_domain_parity_v1.json")
    args = parser.parse_args(argv)

    artifact_path = Path(args.artifact).resolve()
    payload: dict[str, Any] = {
        "formula_id": "WBS_10_DOTNET_DOMAIN_PARITY_ARTIFACT_V1",
        "gate": "FAIL",
        "missing": [],
        "evidence": {"artifact": str(artifact_path)},
    }

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

    if data.get("gate") != "PASS":
        payload["missing"].append("gate")
    if int(data.get("total", 0)) < 40:
        payload["missing"].append("total")
    if data.get("passed") != data.get("total"):
        payload["missing"].append("passed")

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

    out_path = artifact_path.parent / "wbs_10_dotnet_domain_parity_artifact_v1.json"
    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())
