#!/usr/bin/env python3
"""
Build a single read-only Agent market governance snapshot.

The snapshot summarizes existing reports only. It does not approve priority
upgrades, scorecard updates, replay, SDK installation, paid API use,
shadow/canary, production routing, or OpenClaw replacement.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
SERVICE_PATH = ROOT / "apps" / "api" / "src" / "services" / "agent_market_governance_snapshot.py"


def main() -> int:
    parser = argparse.ArgumentParser(description="Build AWOOOI Agent market governance snapshot.")
    parser.add_argument("--watch-report", required=True)
    parser.add_argument("--integration-review", required=True)
    parser.add_argument("--discovery-classification", required=True)
    parser.add_argument("--promotion-review", required=True)
    parser.add_argument(
        "--candidates",
        default="docs/ai/agent-replacement-candidates.v1.json",
    )
    parser.add_argument("--output", help="snapshot output JSON")
    args = parser.parse_args()

    service = _load_service()
    report = service.build_agent_market_governance_snapshot(
        watch_report=_read_json(Path(args.watch_report)),
        integration_review=_read_json(Path(args.integration_review)),
        discovery_classification=_read_json(Path(args.discovery_classification)),
        promotion_review=_read_json(Path(args.promotion_review)),
        candidate_registry=_read_json(Path(args.candidates)),
    )
    rendered = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)
    if args.output:
        Path(args.output).write_text(rendered + "\n", encoding="utf-8")
    else:
        print(rendered)
    print(json.dumps(report["summary"], ensure_ascii=False, sort_keys=True))
    return 0


def _read_json(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)
    if not isinstance(payload, dict):
        raise SystemExit(f"{path}: expected JSON object")
    return payload


def _load_service() -> Any:
    module_name = "awoooi_agent_market_governance_snapshot_service"
    spec = importlib.util.spec_from_file_location(module_name, SERVICE_PATH)
    if spec is None or spec.loader is None:
        raise SystemExit(f"cannot load governance snapshot service from {SERVICE_PATH}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


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