#!/usr/bin/env python3
"""Check whether WBS-9.5 can be promoted from DATA_GATED to DONE."""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from tools.build_sector_flow_history_progress_v1 import DEFAULT_JSON, FORMULA_ID, main as build_progress_main  # type: ignore


def _load(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
        return payload if isinstance(payload, dict) else {}
    except Exception:
        return {}


def main() -> int:
    ap = argparse.ArgumentParser(description="Check WBS-9.5 readiness.")
    ap.add_argument("--input", default=str(ROOT / "Temp" / "sector_flow_history_progress_v1.json"))
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    input_path = Path(args.input)
    input_path = input_path if input_path.is_absolute() else ROOT / input_path
    if not input_path.exists():
        build_progress_main()

    payload = _load(input_path)
    current = int(payload.get("current_dates") or 0)
    target = int(payload.get("target_dates") or 30)
    ready = current >= target and payload.get("status") == "DONE"

    result = {
        "formula_id": "WBS_9_5_RELIABILITY_READY_V1",
        "source": str(input_path),
        "current_dates": current,
        "target_dates": target,
        "ready": ready,
        "status": "DONE" if ready else "DATA_GATED",
        "message": "WBS-9.5 can be promoted" if ready else "WBS-9.5 remains DATA_GATED",
    }

    print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else f"{result['status']}: {result['message']} ({current}/{target})")
    return 0 if ready else 1


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

