from __future__ import annotations

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" / "regime_trim_guidance_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 main() -> int:
    gtd = _load_json(DEFAULT_JSON)
    h = ((gtd.get("data") or {}).get("_harness_context") or {})
    guidance = _parse_jsonish(h.get("regime_trim_guidance_json"))
    if not isinstance(guidance, dict):
        guidance = {}
    if not guidance:
        beta_gate = _parse_jsonish(h.get("portfolio_beta_gate_json"))
        regime = str((beta_gate.get("regime_applied") if isinstance(beta_gate, dict) else None) or h.get("market_regime") or "RISK_ON").upper()
        if "RISK_OFF" in regime or "EVENT_SHOCK" in regime:
            guidance = {
                "phase": "BREAKDOWN",
                "satellite_trim_pct_min": 25,
                "satellite_trim_pct_max": 50,
                "leader_trim_pct_min": 10,
                "leader_trim_pct_max": 25,
            }
        elif "RISK_ON" in regime:
            guidance = {
                "phase": "ADVANCE",
                "satellite_trim_pct_min": 0,
                "satellite_trim_pct_max": 5,
                "leader_trim_pct_min": 0,
                "leader_trim_pct_max": 0,
            }
        else:
            guidance = {
                "phase": "PULLBACK_IN_UPTREND",
                "satellite_trim_pct_min": 5,
                "satellite_trim_pct_max": 10,
                "leader_trim_pct_min": 0,
                "leader_trim_pct_max": 5,
            }

    payload = {
        "formula_id": "REGIME_TRIM_GUIDANCE_V1",
        "gate": "PASS",
        "regime_trim_guidance": guidance,
    }
    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())
