#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import asyncio
import logging
import sys
import os

# 添加 ccxt 路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ccxt import mt5 as mt5_sync
from ccxt.async_support import mt5 as mt5_async

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger('MT5-Fixed-Test')

# 测试配置 - 使用你的配置
TEST_CONFIG = {
    'apiKey': '76888962',
    'secret': 'LZ-trade666888',
    'hostname': '43.167.188.220:5000',
    'host': '18.163.85.196',
    'port': 443,
    'sandbox': True,
    'verbose': True,
}


def test_url_fix():
    """测试 URL 修复"""
    logger.info("🔧 测试 URL 修复...")
    
    try:
        exchange = mt5_sync(TEST_CONFIG)
        
        # 检查 URLs 配置
        logger.info("检查 URLs 配置:")
        logger.info(f"  Public API: {exchange.urls['api']['public']}")
        logger.info(f"  Private API: {exchange.urls['api']['private']}")
        
        # 测试连接
        logger.info("\n测试连接...")
        token = exchange.get_token()
        logger.info(f"✅ 连接成功! Token: {token}")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


async def test_async_url_fix():
    """测试异步 URL 修复"""
    logger.info("\n🔧 测试异步 URL 修复...")
    
    exchange = None
    try:
        exchange = mt5_async(TEST_CONFIG)
        
        # 检查 URLs 配置
        logger.info("检查异步 URLs 配置:")
        logger.info(f"  Public API: {exchange.urls['api']['public']}")
        logger.info(f"  Private API: {exchange.urls['api']['private']}")
        
        # 测试连接
        logger.info("\n测试异步连接...")
        token = await exchange.get_token()
        logger.info(f"✅ 异步连接成功! Token: {token}")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ 异步测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        if exchange:
            await exchange.close()


def test_direct_connection():
    """测试直接连接"""
    logger.info("\n🔧 测试直接连接...")
    
    try:
        # 使用 requests 直接测试连接
        import requests
        
        url = "http://43.167.188.220:5000/Connect"
        params = {
            'user': '76888962',
            'password': 'LZ-trade666888',
            'host': '18.163.85.196',
            'port': 443,
            'connectTimeoutSeconds': 30
        }
        
        logger.info(f"测试直接请求: {url}")
        response = requests.get(url, params=params, timeout=30)
        
        logger.info(f"状态码: {response.status_code}")
        logger.info(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            logger.info("✅ 直接连接成功!")
            return True
        else:
            logger.error(f"❌ 直接连接失败: {response.status_code}")
            return False
            
    except Exception as e:
        logger.error(f"❌ 直接连接测试失败: {e}")
        return False


async def main():
    """运行修复测试"""
    print("🚀 MT5 URL 修复测试")
    print("="*50)
    
    # 测试直接连接
    direct_success = test_direct_connection()
    
    # 测试同步版本
    sync_success = test_url_fix()
    
    # 测试异步版本
    async_success = await test_async_url_fix()
    
    print("\n" + "="*50)
    print("📊 修复测试结果")
    print(f"直接连接: {'✅ 通过' if direct_success else '❌ 失败'}")
    print(f"同步版本: {'✅ 通过' if sync_success else '❌ 失败'}")
    print(f"异步版本: {'✅ 通过' if async_success else '❌ 失败'}")
    
    if direct_success and sync_success and async_success:
        print("🎉 所有修复测试通过！")
    else:
        print("\n⚠️  如果直接连接失败，请检查:")
        print("  1. 网络连接是否正常")
        print("  2. 服务器地址是否正确")
        print("  3. 防火墙设置")
        print("  4. 服务器状态")


if __name__ == "__main__":
    asyncio.run(main())