"""
Test script to verify MT5 connection and data retrieval
"""

import MetaTrader5 as mt5
import sys
from datetime import datetime, timedelta

def test_mt5_connection():
    print("=" * 60)
    print("MT5 Connection Test")
    print("=" * 60)
    
    # Test 1: Initialize MT5
    print("\n[1] Testing MT5 initialization...")
    if not mt5.initialize():
        error = mt5.last_error()
        print(f"❌ Failed to initialize MT5: {error}")
        print("\nTroubleshooting:")
        print("  1. Ensure MT5 terminal is running")
        print("  2. Ensure you are logged into your trading account")
        print("  3. Check if 64-bit Python is installed")
        print("  4. Try specifying MT5 path: mt5.initialize(path='C:\\\\path\\\\to\\\\terminal64.exe')")
        return False
    print("✅ MT5 initialized successfully")
    
    # Test 2: Get MT5 version
    print("\n[2] Getting MT5 version...")
    print(f"   MetaTrader5 package version: {mt5.__version__}")
    terminal_info = mt5.terminal_info()
    if terminal_info:
        print(f"   Terminal path: {terminal_info.path}")
        print(f"   Terminal build: {terminal_info.build}")
        print(f"   Terminal company: {terminal_info.company}")
    print("✅ MT5 version retrieved successfully")
    
    # Test 3: Get account info
    print("\n[3] Getting account information...")
    account_info = mt5.account_info()
    if account_info is None:
        print("❌ Failed to get account info")
        mt5.shutdown()
        return False
    
    print(f"   Account: {account_info.login}")
    print(f"   Name: {account_info.name}")
    print(f"   Server: {account_info.server}")
    print(f"   Balance: {account_info.balance} {account_info.currency}")
    print(f"   Equity: {account_info.equity} {account_info.currency}")
    print(f"   Margin: {account_info.margin} {account_info.currency}")
    print(f"   Free Margin: {account_info.margin_free} {account_info.currency}")
    print(f"   Leverage: 1:{account_info.leverage}")
    print("✅ Account info retrieved successfully")
    
    # Test 4: Get open positions
    print("\n[4] Getting open positions...")
    positions = mt5.positions_get()
    if positions is None:
        print("❌ Failed to get positions")
        mt5.shutdown()
        return False
    
    print(f"   Total open positions: {len(positions)}")
    if len(positions) > 0:
        print("\n   Open Positions:")
        for i, pos in enumerate(positions[:5], 1):  # Show first 5
            position_type = "BUY" if pos.type == 0 else "SELL"
            print(f"   [{i}] {pos.symbol} - {position_type} - Vol: {pos.volume} - "
                  f"Open: {pos.price_open} - Current: {pos.price_current} - Profit: {pos.profit}")
        if len(positions) > 5:
            print(f"   ... and {len(positions) - 5} more")
    else:
        print("   No open positions")
    print("✅ Positions retrieved successfully")
    
    # Test 5: Get closed positions (last 7 days)
    print("\n[5] Getting recent closed positions...")
    to_date = datetime.now()
    from_date = to_date - timedelta(days=7)
    
    history = mt5.history_deals_get(from_date, to_date)
    if history is None:
        print("❌ Failed to get history")
        mt5.shutdown()
        return False
    
    print(f"   Closed positions in last 7 days: {len(history)}")
    if len(history) > 0:
        print("\n   Recent Closed Positions:")
        for i, deal in enumerate(history[:5], 1):  # Show first 5
            deal_type = "BUY" if deal.type == 0 else "SELL"
            print(f"   [{i}] {deal.symbol} - {deal_type} - Vol: {deal.volume} - "
                  f"Price: {deal.price} - Profit: {deal.profit} - Time: {deal.time}")
        if len(history) > 5:
            print(f"   ... and {len(history) - 5} more")
    else:
        print("   No closed positions in last 7 days")
    print("✅ History retrieved successfully")
    
    # Test 6: Get symbol info
    print("\n[6] Getting symbol information...")
    symbols = mt5.symbols_get()
    if symbols is None:
        print("❌ Failed to get symbols")
        mt5.shutdown()
        return False
    
    print(f"   Total available symbols: {len(symbols)}")
    print(f"   First 5 symbols: {[s.name for s in symbols[:5]]}")
    print("✅ Symbols retrieved successfully")
    
    # Cleanup
    print("\n[7] Shutting down MT5 connection...")
    mt5.shutdown()
    print("✅ MT5 shutdown successful")
    
    print("\n" + "=" * 60)
    print("✅ All tests passed! MT5 connection is working.")
    print("=" * 60)
    print("\nYou can now run the MT5 sync service:")
    print("  python mt5_sync.py")
    print("  python mt5_sync_advanced.py")
    return True

if __name__ == "__main__":
    try:
        success = test_mt5_connection()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ Test failed with exception: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
