from __future__ import annotations

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

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


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


def _rows(v: Any) -> list[dict[str, Any]]:
    if isinstance(v, list):
        return [x for x in v if isinstance(x, dict)]
    if isinstance(v, str):
        try:
            return _rows(json.loads(v))
        except Exception:
            return []
    return []


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--json", default=str(DEFAULT_JSON))
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()
    jp = Path(args.json)
    op = Path(args.out)
    if not jp.is_absolute():
        jp = ROOT / jp
    if not op.is_absolute():
        op = ROOT / op
    payload = _load(jp)
    data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
    h = data.get("_harness_context") if isinstance(data.get("_harness_context"), dict) else {}
    alpha = _rows(h.get("alpha_shield_json"))
    rows = []
    blank = 0
    for r in alpha:
        analyst = f"RS={r.get('rs_status','N/A')} / Gate={r.get('mrg_gate','PASS')}"
        trader = f"vol={r.get('volume_ratio',0)} / overhang={r.get('overhang_pressure',0)}"
        quant = f"weight={r.get('weight_pct',0)} / dev={r.get('deviation_ratio',0)}"
        if not analyst or not trader or not quant:
            blank += 1
        rows.append({"ticker": r.get("ticker"), "name": r.get("name"), "analyst_view": analyst, "trader_view": trader, "quant_view": quant})
    out = {"formula_id": "EJCE_VIEW_RENDERER_V1", "gate": "PASS" if blank == 0 else "CAUTION", "row_count": len(rows), "blank_view_count": blank, "rows": rows}
    op.parent.mkdir(parents=True, exist_ok=True)
    op.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"formula_id": out["formula_id"], "rows": out["row_count"], "blank_views": out["blank_view_count"]}, ensure_ascii=False))
    return 0


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

