"""
自动化回测服务 - 主入口
启动 FastAPI 服务，接受回测任务提交，执行回测，返回结果
遵循 vnpy 原生设计，只做外层封装
"""
import uvicorn
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from .config import settings
from .api import router
from .task_queue import task_queue
from .models import ApiResponse, HealthCheckResponse


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期：启动时开启worker线程，关闭时停止"""
    # 启动
    task_queue.start_worker_pool()
    print(f"✅ 回测服务启动 (max_workers={settings.max_workers})")
    yield
    # 关闭
    task_queue.close_worker_pool()
    print("回测服务已停止")


app = FastAPI(
    title="sanguo 自动化回测服务",
    description="基于 vnpy 原生 BacktestingEngine 的自动化回测API服务",
    version="1.0.0",
    lifespan=lifespan
)

# CORS 配置
if settings.cors_allow_all:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 注册API路由
app.include_router(router, tags=["backtest"])


@app.get("/api/backtest/health", summary="服务健康检查", response_model=ApiResponse[HealthCheckResponse])
def health():
    """服务健康检查，返回当前任务统计"""
    return ApiResponse(
        code=0,
        msg="ok",
        data=HealthCheckResponse(
            pending_count=len(task_queue.pending_tasks),
            running_count=len(task_queue.running_tasks),
            completed_count=len(task_queue.completed_tasks),
            failed_count=len(task_queue.failed_tasks),
            max_workers=settings.max_workers
        )
    )


if __name__ == "__main__":
    uvicorn.run(
        "backtest_service.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
    )
