"""bridge/connectors/mt5_connector.py — MT5 broker connector.

Wraps existing bridge/gold_trader.py functions behind the ConnectorBase interface.
No new MT5 logic — pure delegation to proven bridge code.
"""

from __future__ import annotations

from typing import Any

from bridge.connectors.base import ConnectorBase


class MT5Connector(ConnectorBase):
    """MT5 broker connector — delegates to existing bridge infrastructure."""

    def __init__(self, symbol: str = "XAUUSD"):
        self._symbol = symbol

    def get_price(self, symbol: str = "") -> dict[str, Any]:
        sym = symbol or self._symbol
        try:
            from bridge.gold_trader import get_price
            bid, ask = get_price()
            spread = round((ask - bid) * (10000 if "XAU" in sym.upper() else 100), 1)
            import time
            return {"bid": round(bid, 2), "ask": round(ask, 2),
                    "spread": spread, "timestamp": time.time()}
        except Exception:
            return {"bid": 0, "ask": 0, "spread": 0, "timestamp": 0}

    def place_order(self, symbol: str, side: str, volume: float,
                    sl: float = 0.0, tp: float = 0.0) -> dict[str, Any]:
        try:
            from bridge.gold_trader import write_trade_request
            result = write_trade_request(
                symbol=symbol, action="OPEN", side=side.upper(),
                volume=volume, entry=0.0, sl=sl, tp=tp,
                decision_id=f"connector_{id(self)}",
            )
            return {"ticket": 0, "status": "sent", "error": ""}
        except Exception as e:
            return {"ticket": 0, "status": "error", "error": str(e)}

    def get_positions(self) -> list[dict[str, Any]]:
        try:
            from bridge.gold_trader import load_state
            state = load_state()
            return state.get("positions_all", []) or []
        except Exception:
            return []

    def get_account(self) -> dict[str, Any]:
        try:
            from bridge.gold_trader import load_state
            state = load_state()
            return {
                "balance": float(state.get("balance", 0) or 0),
                "equity": float(state.get("equity", 0) or 0),
                "margin": 0.0,
                "margin_free": 0.0,
                "currency": "USD",
            }
        except Exception:
            return {"balance": 0, "equity": 0, "margin": 0, "margin_free": 0, "currency": "USD"}

    def get_bars(self, symbol: str, timeframe: str, count: int) -> list[dict[str, Any]]:
        try:
            from bridge.garch_volatility import get_vol_multiplier
            # GARCH already fetches bars — use that path
            vol_info = get_vol_multiplier()
            return vol_info.get("bars", []) or []
        except Exception:
            return []

    def is_connected(self) -> bool:
        try:
            from bridge.gold_trader import is_mt5_running
            return bool(is_mt5_running())
        except Exception:
            return False

    def get_symbols(self) -> list[dict[str, Any]]:
        return [
            {"name": "XAUUSD", "pip_value": 0.10, "lot_step": 0.01, "min_lot": 0.01, "max_lot": 50.0},
            {"name": "XAGUSD", "pip_value": 0.50, "lot_step": 0.01, "min_lot": 0.01, "max_lot": 50.0},
        ]
