from fastapi import APIRouter, HTTPException, Query, Request
from schemas import ConnectRequest, ConnectResponse, ContractResponse, TickResponse, KlineResponse, DisconnectResponse
from tqapi_service import TqApiService

router = APIRouter()

# 存储当前连接的用户凭证
current_credentials = {}

# 获取当前TqApiService实例
async def get_current_service():
    if not current_credentials:
        raise HTTPException(status_code=401, detail="未连接到天勤服务器")
    # 使用当前凭证获取或创建实例
    return await TqApiService.get_instance(
        current_credentials['username'],
        current_credentials['password']
    )

@router.post("/connect", response_model=ConnectResponse)
async def connect(request: ConnectRequest):
    """连接到天勤服务器"""
    try:
        # 存储凭证
        current_credentials['username'] = request.username
        current_credentials['password'] = request.password
        # 获取或创建TqApiService实例
        service = await TqApiService.get_instance(request.username, request.password)
        return ConnectResponse(success=True, message="连接成功")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/contracts", response_model=ContractResponse)
async def get_contracts():
    """获取合约列表"""
    try:
        service = await get_current_service()
        contracts = await service.get_contracts()
        return ContractResponse(success=True, data=contracts)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/contract/{symbol}", response_model=ContractResponse)
async def get_contract(symbol: str):
    """获取合约详情"""
    try:
        service = await get_current_service()
        contract = await service.get_contract(symbol)
        return ContractResponse(success=True, data=contract)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/klines/{symbol}", response_model=KlineResponse)
async def get_klines(
    symbol: str,
    period: str = Query(..., description="周期，如 1M, 5M, 1H, 1D"),
    count: int = Query(30, description="数据数量")
):
    """获取 K 线数据"""
    try:
        service = await get_current_service()
        klines = await service.get_klines(symbol, period, count)
        return KlineResponse(success=True, data=klines)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/tick/{symbol}", response_model=TickResponse)
async def get_tick(symbol: str):
    """获取 tick 数据"""
    try:
        print(f"[Router] 接收到获取 tick 数据请求，symbol: {symbol}")
        print(f"[Router] 正在获取当前服务实例...")
        service = await get_current_service()
        print(f"[Router] 获取服务实例成功")
        print(f"[Router] 正在调用 service.get_tick({symbol})...")
        tick = await service.get_tick(symbol)
        print(f"[Router] 获取 tick 数据成功: {tick}")
        return TickResponse(success=True, data=tick)
    except Exception as e:
        print(f"[Router] 获取 tick 数据失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/disconnect", response_model=DisconnectResponse)
async def disconnect():
    """断开连接"""
    try:
        service = await get_current_service()
        success = await service.disconnect()
        if success:
            # 清除凭证
            current_credentials.clear()
            return DisconnectResponse(success=True, message="断开成功")
        else:
            raise HTTPException(status_code=400, detail="断开失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
