from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.router import router
import uvicorn
import argparse

app = FastAPI(
    title="TQAPI Service",
    description="天勤量化 API 服务",
    version="1.0.0"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(router, prefix="/api")

# 健康检查
@app.get("/health")
async def health_check():
    return {"status": "healthy"}

# 关闭事件处理
@app.on_event("shutdown")
async def shutdown_event():
    """服务关闭时的清理工作"""
    print("正在关闭服务...")
    # 断开TQApi连接
    from api.router import current_credentials
    from tqapi_service import TqApiService
    
    if current_credentials:
        try:
            # 获取当前服务实例并断开连接
            service = await TqApiService.get_instance(current_credentials['username'], current_credentials['password'])
            success = await service.disconnect()
            if success:
                print("TQApi连接已成功关闭")
            else:
                print("TQApi连接关闭失败")
        except Exception as e:
            print(f"关闭TQApi连接时出错: {e}")
    print("服务已关闭")

if __name__ == "__main__":
    # 解析命令行参数
    parser = argparse.ArgumentParser(description="天勤量化 API 服务")
    parser.add_argument("--port", type=int, default=8000, help="服务端口，默认8000")
    parser.add_argument("--host", type=str, default="0.0.0.0", help="服务主机，默认0.0.0.0")
    args = parser.parse_args()
    
    # 启动服务
    print(f"启动天勤量化 API 服务，监听 {args.host}:{args.port}")
    uvicorn.run(app, host=args.host, port=args.port)
