import MetaTrader5 as mt5
from config import LOT_SIZE, MAGIC_NUMBER


def init_mt5():
    if not mt5.initialize():
        print("❌ MT5 initialization failed")
        print("Error:", mt5.last_error())
        return False

    print("✅ MT5 connected")
    return True


def place_trade(signal):
    symbol = signal["symbol"]

    print(f"\n🚀 Attempting trade on {symbol}")

    # Ensure symbol is available
    if not mt5.symbol_select(symbol, True):
        print("❌ Symbol not available:", symbol)
        return

    tick = mt5.symbol_info_tick(symbol)

    if tick is None:
        print("❌ No tick data — market may be closed")
        return

    print("📈 Tick data:", tick)

    # Determine trade type
    if signal["type"] == "BUY":
        price = tick.ask
        order_type = mt5.ORDER_TYPE_BUY
    else:
        price = tick.bid
        order_type = mt5.ORDER_TYPE_SELL

    # 🔥 Try ALL filling modes (broker-safe method)
    filling_modes = [
        mt5.ORDER_FILLING_IOC,
        mt5.ORDER_FILLING_RETURN,
        mt5.ORDER_FILLING_FOK,
    ]

    for mode in filling_modes:
        print(f"⚙️ Trying filling mode: {mode}")

        request = {
            "action": mt5.TRADE_ACTION_DEAL,
            "symbol": symbol,
            "volume": LOT_SIZE,
            "type": order_type,
            "price": price,
            "sl": signal["sl"],
            "tp": signal["tp"],
            "deviation": 20,
            "magic": MAGIC_NUMBER,
            "comment": "Telegram Auto Trade",
            "type_time": mt5.ORDER_TIME_GTC,
            "type_filling": mode,
        }

        print("📤 Sending order:", request)

        result = mt5.order_send(request)
        print("📊 Result:", result)

        if result is None:
            print("❌ order_send returned None")
            continue

        # ✅ SUCCESS
        if result.retcode == mt5.TRADE_RETCODE_DONE:
            print(f"✅ TRADE SUCCESS using filling mode {mode}")
            return

        # ❌ Unsupported filling mode → try next
        if result.retcode == 10030:
            print("❌ Unsupported filling mode, trying next...")
            continue

        # ❌ Other failure
        print(f"❌ Trade failed, retcode: {result.retcode}")
        return

    print("❌ All filling modes failed — no trade executed")