from __future__ import annotations

import json
from pathlib import Path
from statistics import median
from typing import Any


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


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


def _parse_jsonish(value: Any) -> Any:
    if isinstance(value, (dict, list)):
        return value
    if isinstance(value, str) and value.strip():
        try:
            return json.loads(value)
        except Exception:
            return value
    return value


def _numeric_values(rows: list[dict[str, Any]], key: str) -> list[float]:
    vals: list[float] = []
    for row in rows:
        try:
            v = float(row.get(key))
        except Exception:
            continue
        vals.append(v)
    return vals


def main() -> int:
    gtd = _load_json(DEFAULT_JSON)
    h = ((gtd.get("data") or {}).get("_harness_context") or {})
    anti_late = _parse_jsonish(h.get("anti_late_entry_json"))
    if not isinstance(anti_late, list):
        anti_late = []
    rows = [r for r in anti_late if isinstance(r, dict)]
    v1 = _numeric_values(rows, "velocity_1d")
    v5 = _numeric_values(rows, "velocity_5d")
    payload = {
        "formula_id": "VELOCITY_V1",
        "gate": "PASS" if (v1 or v5) else "DATA_MISSING",
        "velocity_1d": round(median(v1), 4) if v1 else 0.0,
        "velocity_5d": round(median(v5), 4) if v5 else 0.0,
        "sample_count": len(rows),
        "source": "anti_late_entry_json",
    }
    DEFAULT_OUT.parent.mkdir(parents=True, exist_ok=True)
    DEFAULT_OUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0


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