#!/usr/bin/env python3
"""
测试新API服务 (端口8089)
"""

import requests
import json
import time

def main():
    print("🚀 测试新API服务 - 510300.SSE 回测")
    print("="*60)
    
    # 使用新端口8089
    url = "http://192.168.2.154:8089/api/backtest/run"
    
    # 简单均线策略 - 使用vnpy.app.cta_strategy导入
    strategy_code = '''
from vnpy.app.cta_strategy import CtaTemplate

class SimpleMAStrategy(CtaTemplate):
    """简单均线策略"""
    author = "关羽将军"
    
    parameters = ["fast_window", "slow_window"]
    variables = ["fast_ma", "slow_ma"]
    
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        
        self.fast_window = 5
        self.slow_window = 20
        
        self.fast_ma = 0
        self.slow_ma = 0
    
    def on_init(self):
        self.write_log("✅ 策略初始化完成")
        self.put_event()
    
    def on_bar(self, bar):
        # 简单逻辑
        if self.fast_ma > self.slow_ma and not self.pos:
            self.buy(bar.close, 1)
            self.write_log(f"买入: {bar.close}")
        elif self.fast_ma < self.slow_ma and self.pos > 0:
            self.sell(bar.close, self.pos)
            self.write_log(f"卖出: {bar.close}")
        
        self.put_event()
'''
    
    payload = {
        "strategy_code": strategy_code,
        "symbol": "510300.SSE",
        "interval": "1d",
        "start": 20200101,
        "end": 20220926,
        "capital": 1000000,
    }
    
    print(f"请求参数:")
    print(f"  API地址: {url}")
    print(f"  标的: {payload['symbol']}")
    print(f"  时间: {payload['start']} - {payload['end']}")
    print(f"  初始资金: {payload['capital']}")
    print()
    
    try:
        start_time = time.time()
        response = requests.post(url, json=payload, timeout=60)
        elapsed = time.time() - start_time
        
        print(f"请求完成，耗时: {elapsed:.2f} 秒")
        print(f"状态码: {response.status_code}")
        print()
        
        if response.status_code == 200:
            result = response.json()
            print(f"响应内容:")
            print(json.dumps(result, indent=2, ensure_ascii=False))
            
            code = result.get('code')
            if code == 200:
                print("\n🎉 " + "="*60)
                print("✅ 回测成功完成！")
                print("="*60)
                print("修复验证:")
                print("  ✅ vnpy.app导入问题已解决")
                print("  ✅ 510300.SSE数据已加载")
                print("  ✅ 回测功能正常工作")
                
                data = result.get('data', {})
                if 'statistics' in data:
                    stats = data['statistics']
                    print(f"\n📊 回测统计:")
                    for key, value in stats.items():
                        print(f"   {key}: {value}")
                else:
                    print(f"\n📦 返回数据: {list(data.keys())}")
            else:
                error = result.get('error', '未知错误')
                print(f"\n❌ 回测失败: {error}")
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            print(f"响应: {response.text[:200]}")
            
    except requests.exceptions.Timeout:
        print("❌ 请求超时")
    except Exception as e:
        print(f"❌ 异常: {e}")
    
    print("\n" + "="*60)
    print("测试完成")
    print("="*60)

if __name__ == "__main__":
    main()