# ftsaaipkg/bridge.py

import MetaTrader5 as mt5
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.
    """
    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.
    """
    if mt5.initialize():
        mt5.shutdown()


# 🔥 NEW: Account Summary Fetcher
def get_account_summary() -> dict:
    """
    Returns account summary data:
    balance, equity, margin, free margin
    """
    info = mt5.account_info()

    if info is None:
        return {}

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


# 🔥 NEW: Open Trades Fetcher
def get_open_trades() -> list:
    """
    Returns list of currently open positions
    """
    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