"""
Token 使用统计路由

提供 token 使用情况的查询接口
"""
from fastapi import APIRouter, HTTPException
from typing import Dict, Any, List, Optional

try:
    from backend.services.token_usage_service import token_usage_service
except ImportError:
    from services.token_usage_service import token_usage_service

router = APIRouter(prefix="/token-usage", tags=["token-usage"])


@router.get("/months")
async def list_months():
    """列出所有有数据的月份"""
    return await token_usage_service.list_months()


@router.get("/stats/{year}/{month}")
async def get_monthly_stats(
    year: int,
    month: int,
    role_name: Optional[str] = None,
    chat_name: Optional[str] = None
):
    """
    获取指定月份的统计数据
    
    Args:
        year: 年份
        month: 月份
        role_name: 角色名称（可选）
        chat_name: 聊天名称（可选）
    """
    if month < 1 or month > 12:
        raise HTTPException(status_code=400, detail="月份必须在 1-12 之间")
    
    try:
        stats = await token_usage_service.get_stats_by_month(
            year=year,
            month=month,
            role_name=role_name,
            chat_name=chat_name
        )
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计数据失败: {str(e)}")


@router.get("/api-urls")
async def get_api_url_stats():
    """
    ✅ 获取按 API URL 分组的统计数据（快速查询）
    
    Returns:
        {
            "api_url_1": {
                "totalPromptTokens": 1000,
                "totalCompletionTokens": 2000,
                "totalTokens": 3000,
                "count": 10,
                "firstUsed": 1234567890,
                "lastUsed": 1234567899
            },
            ...
        }
    """
    try:
        stats = await token_usage_service.get_api_url_stats()
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取 API URL 统计失败: {str(e)}")


@router.get("/daily/{year}/{month}")
async def get_daily_stats(year: int, month: int):
    """
    ✅ 获取指定月份的每日统计数据（快速查询）
    
    Args:
        year: 年份
        month: 月份
        
    Returns:
        {
            "2024-01-01": {
                "promptTokens": 1000,
                "completionTokens": 2000,
                "totalTokens": 3000,
                "count": 10
            },
            ...
        }
    """
    if month < 1 or month > 12:
        raise HTTPException(status_code=400, detail="月份必须在 1-12 之间")
    
    try:
        stats = await token_usage_service.get_daily_stats(year, month)
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取每日统计失败: {str(e)}")


@router.get("/roles/{year}/{month}")
async def get_available_roles(year: int, month: int):
    """获取指定月份有数据的角色列表"""
    if month < 1 or month > 12:
        raise HTTPException(status_code=400, detail="月份必须在 1-12 之间")
    
    roles = await token_usage_service.get_available_roles(year, month)
    return {"roles": roles}


@router.get("/chats/{year}/{month}")
async def get_available_chats(
    year: int,
    month: int,
    role_name: Optional[str] = None
):
    """获取指定月份有数据的聊天列表"""
    if month < 1 or month > 12:
        raise HTTPException(status_code=400, detail="月份必须在 1-12 之间")
    
    chats = await token_usage_service.get_available_chats(year, month, role_name)
    return {"chats": chats}
