import json
from pathlib import Path
from typing import Any, Dict


def load_mt5_snapshot(path: Path) -> Dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def to_engine_request(mt5_snapshot: Dict[str, Any]) -> Dict[str, Any]:
    market = mt5_snapshot.get("market", {})
    account = mt5_snapshot.get("account", {})
    agent = mt5_snapshot.get("agent", {})
    plan = mt5_snapshot.get("ai_trade_plan", {})

    spread_points = float(market.get("spread_points", 0))
    spread_p90_30m = float(market.get("spread_p90_30m", 1))

    return {
        "market_metrics": {
            "market_data_delay_ms": float(market.get("market_data_delay_ms", 0)),
            "missing_bars": int(market.get("missing_bars", 0)),
            "tick_bar_deviation_bps": float(market.get("tick_bar_deviation_bps", 0)),
            "spread_points": spread_points,
            "spread_p90_30m": spread_p90_30m,
        },
        "account_metrics": {
            "daily_realized_loss_pct": float(account.get("daily_realized_loss_pct", 0)),
            "consecutive_losses": int(account.get("consecutive_losses", 0)),
        },
        "agent_runtime": {
            "agent_timeout_ms": float(agent.get("agent_timeout_ms", 0)),
        },
        "agent_outputs": {
            "risk_agent": {
                "risk_level": str(agent.get("risk_level", "MEDIUM")),
            },
            "strategy_agent": {
                "side_conflict_with_regime": bool(agent.get("side_conflict_with_regime", False)),
            },
        },
        "ai_trade_plan": plan,
    }
