#!/usr/bin/env python3
"""
最终回测API测试
"""

import requests
import time
import json

def test_health():
    """测试健康检查"""
    print("1. 测试健康检查...")
    try:
        response = requests.get("http://192.168.2.154:8088/health", timeout=5)
        print(f"   状态码: {response.status_code}")
        print(f"   响应: {response.json()}")
        return True
    except Exception as e:
        print(f"   ❌ 失败: {e}")
        return False

def test_swagger():
    """测试Swagger UI"""
    print("\n2. 测试Swagger UI...")
    try:
        response = requests.get("http://192.168.2.154:8088/docs", timeout=5)
        print(f"   状态码: {response.status_code}")
        if response.status_code == 200:
            print("   ✅ Swagger UI可访问")
            return True
        else:
            print("   ❌ Swagger UI不可访问")
            return False
    except Exception as e:
        print(f"   ❌ 失败: {e}")
        return False

def test_backtest_simple():
    """测试简单回测"""
    print("\n3. 测试简单回测...")
    
    url = "http://192.168.2.154:8088/api/backtest/run"
    
    # 极简策略
    simple_strategy = '''from vnpy_ctastrategy import CtaTemplate

class SimpleTest(CtaTemplate):
    """极简测试策略"""
    author = "姜维"
    
    def on_init(self):
        self.write_log("✅ 策略初始化完成")
        self.load_bar(1)  # 只加载1根K线
    
    def on_bar(self, bar):
        self.write_log(f"收到K线: {bar.datetime}")
'''
    
    payload = {
        "strategy_code": simple_strategy,
        "symbol": "rb8888.SHFE",
        "interval": "1m",
        "start": 20240101,
        "end": 20240101,  # 只测试1天
        "capital": 100000,
    }
    
    try:
        print(f"   发送请求到: {url}")
        print(f"   合约: {payload['symbol']}")
        print(f"   时间: {payload['start']} - {payload['end']}")
        
        start_time = time.time()
        response = requests.post(url, json=payload, timeout=15)  # 15秒超时
        elapsed = time.time() - start_time
        
        print(f"   响应时间: {elapsed:.2f}秒")
        print(f"   状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"   ✅ 回测成功!")
            print(f"      消息: {result.get('msg')}")
            print(f"      返回码: {result.get('code')}")
            
            if result.get('data'):
                data = result['data']
                print(f"      数据包含: {list(data.keys())}")
                if 'statistics' in data:
                    stats = data['statistics']
                    print(f"      统计信息:")
                    for key, value in stats.items():
                        print(f"        {key}: {value}")
            
            return True
        else:
            print(f"   ❌ HTTP错误: {response.status_code}")
            print(f"      响应: {response.text[:200]}...")
            return False
            
    except requests.exceptions.Timeout:
        print("   ❌ 请求超时 (15秒)")
        print("      可能原因:")
        print("      1. ZMQ RPC服务未运行")
        print("      2. 策略执行时间过长")
        print("      3. 网络问题")
        return False
    except requests.exceptions.ConnectionError:
        print("   ❌ 连接失败")
        print("      请检查:")
        print("      1. NAS IP地址: 192.168.2.154")
        print("      2. 端口8088是否开放")
        print("      3. Docker容器是否运行")
        return False
    except Exception as e:
        print(f"   ❌ 其他错误: {e}")
        return False

def main():
    print("🚀 最终回测API测试")
    print("=" * 60)
    
    # 测试健康检查
    health_ok = test_health()
    
    # 测试Swagger
    swagger_ok = test_swagger()
    
    # 测试回测
    backtest_ok = test_backtest_simple()
    
    print("\n" + "=" * 60)
    print("测试结果汇总:")
    print(f"  健康检查: {'✅ 通过' if health_ok else '❌ 失败'}")
    print(f"  Swagger UI: {'✅ 通过' if swagger_ok else '❌ 失败'}")
    print(f"  回测功能: {'✅ 通过' if backtest_ok else '❌ 失败'}")
    
    if health_ok and swagger_ok and backtest_ok:
        print("\n🎉 所有测试通过！回测API已修复！")
        print("请通知各位将军可以开始测试了。")
        print("\n访问地址:")
        print("  - Swagger UI: http://192.168.2.154:8088/docs")
        print("  - API端点: POST http://192.168.2.154:8088/api/backtest/run")
    else:
        print("\n⚠️  部分测试失败，需要进一步排查。")
        print("请检查:")
        print("  1. Docker容器状态")
        print("  2. 服务日志")
        print("  3. 端口映射配置")
    
    print("=" * 60)

if __name__ == "__main__":
    main()