# ftsaaipkg/bridge.py

# 🔹 Make MT5 optional for Linux/macOS
try:
    import MetaTrader5 as mt5
except ImportError:
    mt5 = None

from datetime import datetime


def connect_mt5(login: str, password: str, server: str, platform: str = "MT5") -> bool:
    """
    Connects to MT5 using the provided credentials.
    Returns True if connection is successful, else False.
    On non-Windows systems (MT5 not available), returns False.
    """
    if mt5 is None:
        print("⚠️ MetaTrader5 is only available on Windows. Skipping connection.")
        return False

    try:
        login_int = int(login)
    except ValueError:
        print(f"Invalid login number: {login}")
        return False

    # If already initialized, shut it down cleanly
    if mt5.initialize():
        mt5.shutdown()

    # Attempt to initialize MT5
    if not mt5.initialize(login=login_int, password=password, server=server):
        error_code, error_descr = mt5.last_error()
        print(f"MT5 initialize failed, error code = {error_code}, description = {error_descr}")
        return False

    return True


def disconnect_mt5():
    """
    Shuts down MT5 terminal connection if initialized.
    Safe on non-Windows systems.
    """
    if mt5 is None:
        return

    if mt5.initialize():
        mt5.shutdown()


def get_account_summary() -> dict:
    """
    Returns account summary data: balance, equity, margin, free margin
    Safe on non-Windows systems.
    """
    if mt5 is None:
        return {}

    info = mt5.account_info()
    if info is None:
        return {}

    return {
        "balance": info.balance,
        "equity": info.equity,
        "margin": info.margin,
        "freeMargin": info.margin_free
    }


def get_open_trades() -> list:
    """
    Returns list of currently open positions
    Safe on non-Windows systems.
    """
    if mt5 is None:
        return []

    positions = mt5.positions_get()
    if positions is None:
        return []

    trades = []
    for p in positions:
        trades.append({
            "symbol": p.symbol,
            "ticket": p.ticket,
            "time": datetime.utcfromtimestamp(p.time).isoformat() + "Z",
            "type": "buy" if p.type == 0 else "sell",
            "volume": p.volume,
            "open_price": p.price_open,
            "current_price": p.price_current,
            "sl": p.sl,
            "tp": p.tp,
            "profit": p.profit
        })

    return trades