from __future__ import annotations

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

GATE_NAMES = (
    "reconcile_clean",
    "alerts_proven",
    "loss_gates_active",
    "kill_switch_ready",
    "stop_handling_ready",
)


def _load_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return {}


def load_operational_gates(runtime_dir: str | Path = "runtime") -> dict[str, Any]:
    runtime = Path(runtime_dir)
    reconcile = _load_json(runtime / "reports" / "hl_reconcile_watchdog_latest.json")
    preflight = _load_json(runtime / "reports" / "preflight_evidence_latest.json")
    limits = _load_json(runtime / "config" / "tiny_autonomous_live_limits.json")
    watchdog = reconcile.get("watchdog") if isinstance(reconcile.get("watchdog"), dict) else {}
    block_if = set(str(x) for x in (limits.get("block_new_entries_if") or []))
    gates = {
        "reconcile_clean": bool(watchdog) and watchdog.get("critical") is False and watchdog.get("block_new_entries") is False and int(watchdog.get("stops_missing_count") or 0) == 0,
        "alerts_proven": preflight.get("telegram_alerts_tested") is True,
        "loss_gates_active": bool(limits.get("max_daily_loss_usdc")) and bool(limits.get("max_weekly_loss_usdc")) and {"daily_loss_exceeded", "weekly_loss_exceeded"}.issubset(block_if),
        "kill_switch_ready": "kill_switch_active" in block_if,
        "stop_handling_ready": preflight.get("position_without_stop_impossible") is True and preflight.get("testnet_fill_stop") is True and "position_without_stop" in block_if,
    }
    blockers = [f"{name}_missing" for name in GATE_NAMES if gates.get(name) is not True]
    return {
        "gates": gates,
        "blockers": blockers,
        "sources": {
            "reconcile_report": str(runtime / "reports" / "hl_reconcile_watchdog_latest.json"),
            "preflight_report": str(runtime / "reports" / "preflight_evidence_latest.json"),
            "limits_config": str(runtime / "config" / "tiny_autonomous_live_limits.json"),
        },
    }


def format_operational_gate_report(payload: dict[str, Any]) -> str:
    blockers = payload.get("blockers") or []
    blocker_text = ",".join(blockers[:5]) if blockers else "keine"
    green = sum(1 for value in (payload.get("gates") or {}).values() if value is True)
    total = len(payload.get("gates") or GATE_NAMES)
    return f"Operational Gates: green={green}/{total}, blocker={blocker_text}"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Load live-readiness operational gates from runtime reports.")
    parser.add_argument("--runtime-dir", default="runtime")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args(argv)
    result = load_operational_gates(args.runtime_dir)
    if args.json:
        print(json.dumps(result, indent=2, sort_keys=True))
    else:
        print(format_operational_gate_report(result))
    return 0 if not result["blockers"] else 2


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