"""
用户 API Key 管理接口

提供用户管理自己的 API Key 的 CRUD 接口，以及管理员管理所有用户 API Key 的接口。
"""

from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, status, Query, Request
from pydantic import BaseModel, Field

from src.auth.dependencies import get_current_user, require_admin
from src.auth.models import UserAuth
from src.services.user_api_key_service import user_api_key_service
from src.models.schemas import ResponseModel, PaginationParams
from src.utils.pagination import Paginator
from src.utils.errors import ErrorCode, AppException

router = APIRouter(prefix="/user-api-keys", tags=["user-api-keys"])


# ===== 请求/响应模型 =====

class ApiKeyCreateRequest(BaseModel):
    """创建 API Key 请求"""
    provider: str = Field(..., description="提供商，如 openai, dashscope")
    api_key: str = Field(..., description="API Key 值", min_length=1)
    name: Optional[str] = Field(None, description="自定义名称")
    extra_config: Optional[dict] = Field(None, description="额外配置")


class ApiKeyUpdateRequest(BaseModel):
    """更新 API Key 请求"""
    name: Optional[str] = Field(None, description="新名称")
    api_key: Optional[str] = Field(None, description="新 API Key 值")
    is_active: Optional[bool] = Field(None, description="是否启用")
    extra_config: Optional[dict] = Field(None, description="额外配置")


class ApiKeyResponse(BaseModel):
    """API Key 响应"""
    id: str
    user_id: str
    provider: str
    name: str
    masked_key: str
    is_active: bool
    created_at: float
    updated_at: float
    last_used_at: Optional[float]
    usage_count: int
    extra_config: Optional[dict]


class ApiKeyVerifyResponse(BaseModel):
    """API Key 验证响应"""
    valid: bool
    provider: Optional[str] = None
    message: Optional[str] = None
    error: Optional[str] = None


# ===== 管理员响应模型 =====

class AdminApiKeyListItem(BaseModel):
    """管理员 API Key 列表项"""
    id: str
    user_id: str
    username: str = Field(..., description="关联用户名")
    email: str = Field(..., description="关联用户邮箱")
    provider: str
    name: str
    masked_key: str
    is_active: bool
    created_at: float
    last_used_at: Optional[float]
    usage_count: int


class AdminApiKeyUsageRecord(BaseModel):
    """API Key 使用记录"""
    task_id: Optional[str]
    task_type: Optional[str]
    model: Optional[str]
    provider: str
    credits_used: Optional[float]
    created_at: str


# ===== API 端点 =====

@router.get("", response_model=ResponseModel)
async def list_api_keys(
    current_user: UserAuth = Depends(get_current_user),
    include_inactive: bool = False
):
    """
    获取当前用户的所有 API Key

    Args:
        include_inactive: 是否包含已禁用的 Key
    """
    keys = user_api_key_service.get_user_api_keys(
        user_id=current_user.id,
        include_inactive=include_inactive
    )
    return ResponseModel(data=keys)


@router.post("", status_code=status.HTTP_201_CREATED, response_model=ResponseModel)
async def create_api_key(
    request: ApiKeyCreateRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    创建新的 API Key
    """
    try:
        key_db = user_api_key_service.create_api_key(
            user_id=current_user.id,
            provider=request.provider,
            api_key=request.api_key,
            name=request.name,
            extra_config=request.extra_config
        )
        key = user_api_key_service.get_api_key_by_id(key_db.id, current_user.id)
        return ResponseModel(data=key)
    except ValueError as e:
        raise AppException(
            message=str(e),
            code=ErrorCode.INVALID_PARAMETER,
            status_code=400
        )


@router.get("/{key_id}", response_model=ResponseModel)
async def get_api_key(
    key_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    获取指定 API Key 的详细信息
    """
    key = user_api_key_service.get_api_key_by_id(key_id, current_user.id)
    if not key:
        raise AppException(
                message="API Key not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
    return ResponseModel(data=key)


@router.put("/{key_id}", response_model=ResponseModel)
async def update_api_key(
    key_id: str,
    request: ApiKeyUpdateRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    更新 API Key
    """
    key = user_api_key_service.update_api_key(
        key_id=key_id,
        user_id=current_user.id,
        name=request.name,
        api_key=request.api_key,
        is_active=request.is_active,
        extra_config=request.extra_config
    )
    if not key:
        raise AppException(
                message="API Key not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
    return ResponseModel(data=key)


@router.delete("/{key_id}", response_model=ResponseModel)
async def delete_api_key(
    key_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    删除 API Key
    """
    success = user_api_key_service.delete_api_key(key_id, current_user.id)
    if not success:
        raise AppException(
                message="API Key not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
    return ResponseModel(data={"deleted": True, "id": key_id})


@router.post("/{key_id}/verify", response_model=ResponseModel)
async def verify_api_key(
    key_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    验证 API Key 是否有效
    """
    result = await user_api_key_service.verify_api_key(key_id, current_user.id)
    return ResponseModel(data=result)


# ============================================================================
# 管理员 API 端点
# ============================================================================

@router.get("/admin/api-keys", response_model=ResponseModel)
async def admin_list_api_keys(
    request: Request,
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    user_id: Optional[str] = Query(None, description="按用户 ID 过滤"),
    provider: Optional[str] = Query(None, description="按提供商过滤"),
    current_user: UserAuth = Depends(require_admin),
):
    """
    管理员列出所有 API Keys

    支持分页、按用户 ID、提供商过滤。
    需要管理员权限。
    """
    from sqlmodel import Session, select, func
    from src.config.database import engine
    from src.models.entities import UserApiKeyDB, UserDB

    with Session(engine) as session:
        query = select(UserApiKeyDB)

        # 应用过滤
        if user_id:
            query = query.where(UserApiKeyDB.user_id == user_id)
        if provider:
            query = query.where(UserApiKeyDB.provider == provider)

        # 获取总数
        total = session.exec(
            select(func.count()).select_from(query.subquery())
        ).one()

        # 分页
        offset = (page - 1) * page_size
        query = query.order_by(UserApiKeyDB.created_at.desc()).offset(offset).limit(page_size)

        api_keys = session.exec(query).all()

        # 构建响应项（关联用户信息）
        items = []
        for key in api_keys:
            user = session.get(UserDB, key.user_id)
            # 获取脱敏 key
            raw_key = key.encrypted_key[:8] + "***" if key.encrypted_key else ""
            items.append(
                AdminApiKeyListItem(
                    id=key.id,
                    user_id=key.user_id,
                    username=user.username if user else "Unknown",
                    email=user.email if user else "",
                    provider=key.provider,
                    name=key.name or f"{key.provider} Key",
                    masked_key=raw_key,
                    is_active=key.is_active,
                    created_at=key.created_at,
                    last_used_at=key.last_used_at,
                    usage_count=key.usage_count,
                )
            )

        paginator = Paginator(
            items=[item.model_dump() for item in items],
            total=total,
            page=page,
            page_size=page_size,
        )

        return paginator.to_response(request)


@router.post("/admin/api-keys/{key_id}/revoke", response_model=ResponseModel)
async def admin_revoke_api_key(
    key_id: str,
    current_user: UserAuth = Depends(require_admin),
):
    """
    撤销 API Key

    需要管理员权限。
    """
    from sqlmodel import Session, select
    from src.config.database import engine
    from src.models.entities import UserApiKeyDB

    with Session(engine) as session:
        key = session.get(UserApiKeyDB, key_id)
        if not key:
            raise AppException(
                message="API Key not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        key.is_active = False
        key.updated_at = datetime.now().timestamp()
        session.add(key)
        session.commit()

        return ResponseModel(
            data={
                "id": key_id,
                "is_active": False,
                "message": "API Key 已成功撤销",
            }
        )


@router.get("/admin/api-keys/{key_id}/usage", response_model=ResponseModel)
async def admin_get_api_key_usage(
    key_id: str,
    current_user: UserAuth = Depends(require_admin),
):
    """
    获取 API Key 使用记录

    需要管理员权限。
    """
    from sqlmodel import Session, select
    from src.config.database import engine
    from src.models.entities import UserApiKeyDB, TaskDB

    with Session(engine) as session:
        key = session.get(UserApiKeyDB, key_id)
        if not key:
            raise AppException(
                message="API Key not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        # 查询相关任务记录
        tasks = session.exec(
            select(TaskDB)
            .where(TaskDB.user_id == key.user_id)
            .order_by(TaskDB.created_at.desc())
            .limit(50)
        ).all()

        usage_records = [
            AdminApiKeyUsageRecord(
                task_id=task.id,
                task_type=task.type,
                model=task.model,
                provider=task.provider or key.provider,
                credits_used=None,
                created_at=datetime.fromtimestamp(task.created_at).isoformat(),
            )
            for task in tasks
        ]

        return ResponseModel(
            data={
                "key_id": key_id,
                "usage_count": key.usage_count,
                "records": [r.model_dump() for r in usage_records],
            }
        )
