from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_JSON = ROOT / "GatherTradingData.json"


def _load_json(path: Path) -> dict[str, Any]:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return data if isinstance(data, dict) else {}


def _as_obj(v: Any) -> dict[str, Any]:
    if isinstance(v, dict):
        return v
    if isinstance(v, str):
        try:
            p = json.loads(v)
            return p if isinstance(p, dict) else {}
        except Exception:
            return {}
    return {}


def main() -> int:
    json_path = DEFAULT_JSON
    if len(sys.argv) > 1:
        json_path = Path(sys.argv[1])
        if not json_path.is_absolute():
            json_path = ROOT / json_path

    data = _load_json(json_path)
    h = _as_obj(data.get("hApex")) or _as_obj(_as_obj(data.get("data")).get("_harness_context")) or data
    eg = _as_obj(h.get("export_gate_json"))

    status = str(eg.get("json_validation_status") or "PENDING_EXPORT")
    failed_checks = eg.get("failed_checks") or []
    resolution_guide = eg.get("resolution_guide") or []

    if not isinstance(failed_checks, list):
        print("EXPORT_GATE_RESOLUTION_FAIL")
        print("- failed_checks is not list")
        return 1
    if not isinstance(resolution_guide, list):
        print("EXPORT_GATE_RESOLUTION_FAIL")
        print("- resolution_guide is not list")
        return 1

    errors: list[str] = []
    if status in ("REVIEW_ONLY", "PENDING_EXPORT", "EXPORT_BLOCKED_CRITICAL"):
        if len(failed_checks) > 0 and len(resolution_guide) == 0:
            errors.append("resolution_guide missing while failed_checks exist")
        for idx, item in enumerate(resolution_guide):
            text = str(item).strip()
            if not text:
                errors.append(f"resolution_guide[{idx}] empty")

    if errors:
        print("EXPORT_GATE_RESOLUTION_FAIL")
        for e in errors:
            print(f"- {e}")
        return 1

    print("EXPORT_GATE_RESOLUTION_OK")
    print(f"status={status} failed_checks={len(failed_checks)} resolution_guide={len(resolution_guide)}")
    return 0


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