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 _fetch_equity_direct() -> float:
    """MT5 API直连获取equity"""
    try:
        import MetaTrader5 as mt5
        if mt5.initialize():
            acct = mt5.account_info()
            if acct:
                return float(acct.equity)
    except Exception:
        pass
    return 0.0


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))

    # ── account可能是字符串(login号)而非dict → 直连MT5 API获取equity ──
    if isinstance(account, dict):
        equity = float(account.get("equity", 0) or 0)
    else:
        equity = _fetch_equity_direct()

    return {
        "symbol": str(mt5_snapshot.get("symbol", market.get("symbol", "XAUUSD")) or "XAUUSD").upper(),
        "timeframe": str(
            mt5_snapshot.get("timeframe")
            or plan.get("timeframe")
            or market.get("timeframe")
            or "M5"
        ).upper(),
        "market_metrics": {
            "market_data_delay_ms": float(market.get("market_data_delay_ms", 0)) if market.get("market_data_delay_ms") is not None else None,
            "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": {
            "current_open_positions": int(account.get("current_open_positions", 0)) if isinstance(account, dict) else 0,
            "daily_realized_loss_pct": float(account.get("daily_realized_loss_pct", 0)) if isinstance(account, dict) else 0.0,
            "consecutive_losses": int(account.get("consecutive_losses", 0)) if isinstance(account, dict) else 0,
            "equity": equity,
        },
        "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,
    }
