#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：api_preset.py
模块描述：API 接口预设 CRUD 路由

作者：czj
创建日期：2026-08-13
"""

import logging
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.schemas.api_preset import (
    ApiPresetCreate,
    ApiPresetUpdate,
    ApiPresetResponse,
    ApiPresetListItem,
    ApiPresetListResponse,
)
from app.services.api_preset_service import ApiPresetService

logger = logging.getLogger(__name__)

router = APIRouter()


# ==================== 依赖注入 ====================

async def get_preset_service(db: AsyncSession = Depends(get_db)) -> ApiPresetService:
    """获取 ApiPresetService 实例"""
    return ApiPresetService(db)


# ==================== CRUD 接口 ====================


@router.get("/presets", response_model=ApiPresetListResponse)
async def list_presets(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="按名称/URL 搜索"),
    service: ApiPresetService = Depends(get_preset_service),
):
    """获取接口预设列表（分页）"""
    items, total = await service.list_presets(page=page, page_size=page_size, keyword=keyword)
    return ApiPresetListResponse(
        total=total,
        items=[ApiPresetListItem(**p.to_dict()) for p in items],
    )


@router.post("/presets", response_model=ApiPresetResponse, status_code=201)
async def create_preset(
    data: ApiPresetCreate,
    service: ApiPresetService = Depends(get_preset_service),
):
    """创建接口预设"""
    preset = await service.create_preset(data.model_dump())
    return ApiPresetResponse(**preset.to_dict())


@router.get("/presets/{preset_id}", response_model=ApiPresetResponse)
async def get_preset(
    preset_id: str,
    service: ApiPresetService = Depends(get_preset_service),
):
    """获取接口预设详情"""
    preset = await service.get_preset(preset_id)
    if not preset:
        raise HTTPException(status_code=404, detail="预设不存在")
    return ApiPresetResponse(**preset.to_dict())


@router.put("/presets/{preset_id}", response_model=ApiPresetResponse)
async def update_preset(
    preset_id: str,
    data: ApiPresetUpdate,
    service: ApiPresetService = Depends(get_preset_service),
):
    """更新接口预设"""
    try:
        preset = await service.update_preset(preset_id, data.model_dump(exclude_unset=True))
        if not preset:
            raise HTTPException(status_code=404, detail="预设不存在")
        return ApiPresetResponse(**preset.to_dict())
    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.delete("/presets/{preset_id}", status_code=204)
async def delete_preset(
    preset_id: str,
    service: ApiPresetService = Depends(get_preset_service),
):
    """删除接口预设"""
    deleted = await service.delete_preset(preset_id)
    if not deleted:
        raise HTTPException(status_code=404, detail="预设不存在")