"""
Prompt Template API - 提示词模板接口
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, Query

from src.models.schemas import ResponseModel
from src.models.prompt_template import (
    PromptTemplateCreate,
    PromptTemplateUpdate,
    PromptTemplateCategory
)
from src.services.prompt_template_service import PromptTemplateService
from src.auth.dependencies import get_current_user
from src.auth.models import UserAuth
from src.utils.errors import AppException, ErrorCode

router = APIRouter(tags=["prompt-templates"])
logger = logging.getLogger(__name__)


@router.post("/prompt-templates/init", response_model=ResponseModel)
async def init_templates(current_user: UserAuth = Depends(get_current_user)):
    """初始化系统默认模板（仅管理员）"""
    # 这里可以添加管理员权限检查
    PromptTemplateService.init_default_templates()
    return ResponseModel(message="Templates initialized successfully")


@router.get("/prompt-templates", response_model=ResponseModel)
async def list_templates(
    category: Optional[str] = Query(None, description="分类过滤"),
    target_type: Optional[str] = Query(None, description="目标类型过滤: image/video/audio/music"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    favorites_only: bool = Query(False, description="仅显示收藏"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user: UserAuth = Depends(get_current_user)
):
    """获取提示词模板列表"""
    try:
        result = PromptTemplateService.list_templates(
            user_id=current_user.id,
            category=category,
            target_type=target_type,
            search=search,
            favorites_only=favorites_only,
            page=page,
            page_size=page_size
        )
        return ResponseModel(data=result)
    except Exception as e:
        logger.error(f"Error listing templates: {e}")
        raise AppException(
            message="Failed to list templates",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )


@router.get("/prompt-templates/categories", response_model=ResponseModel)
async def get_categories(
    current_user: UserAuth = Depends(get_current_user)
):
    """获取模板分类列表"""
    categories = PromptTemplateService.get_categories()
    return ResponseModel(data=categories)


@router.post("/prompt-templates", response_model=ResponseModel)
async def create_template(
    data: PromptTemplateCreate,
    current_user: UserAuth = Depends(get_current_user)
):
    """创建新模板"""
    try:
        template = PromptTemplateService.create_template(
            user_id=current_user.id,
            data=data
        )
        return ResponseModel(
            message="Template created successfully",
            data=template
        )
    except Exception as e:
        logger.error(f"Error creating template: {e}")
        raise AppException(
            message="Failed to create template",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )


@router.get("/prompt-templates/{template_id}", response_model=ResponseModel)
async def get_template(
    template_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """获取单个模板详情"""
    template = PromptTemplateService.get_template(
        template_id=template_id,
        user_id=current_user.id
    )
    
    if not template:
        raise AppException(
            message="Template not found",
            code=ErrorCode.NOT_FOUND,
            status_code=404
        )
    
    return ResponseModel(data=template)


@router.put("/prompt-templates/{template_id}", response_model=ResponseModel)
async def update_template(
    template_id: str,
    data: PromptTemplateUpdate,
    current_user: UserAuth = Depends(get_current_user)
):
    """更新模板"""
    try:
        template = PromptTemplateService.update_template(
            template_id=template_id,
            user_id=current_user.id,
            data=data
        )
        
        if not template:
            raise AppException(
                message="Template not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
        
        return ResponseModel(
            message="Template updated successfully",
            data=template
        )
    except PermissionError as e:
        raise AppException(
            message=str(e),
            code=ErrorCode.PERMISSION_DENIED,
            status_code=403
        )
    except Exception as e:
        logger.error(f"Error updating template: {e}")
        raise AppException(
            message="Failed to update template",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )


@router.delete("/prompt-templates/{template_id}", response_model=ResponseModel)
async def delete_template(
    template_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """删除模板"""
    try:
        success = PromptTemplateService.delete_template(
            template_id=template_id,
            user_id=current_user.id
        )
        
        if not success:
            raise AppException(
                message="Template not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
        
        return ResponseModel(message="Template deleted successfully")
    except PermissionError as e:
        raise AppException(
            message=str(e),
            code=ErrorCode.PERMISSION_DENIED,
            status_code=403
        )
    except Exception as e:
        logger.error(f"Error deleting template: {e}")
        raise AppException(
            message="Failed to delete template",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )


@router.post("/prompt-templates/{template_id}/favorite", response_model=ResponseModel)
async def toggle_favorite(
    template_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """切换模板收藏状态"""
    try:
        is_favorite = PromptTemplateService.toggle_favorite(
            template_id=template_id,
            user_id=current_user.id
        )
        
        return ResponseModel(
            message="Favorite toggled successfully",
            data={"is_favorite": is_favorite}
        )
    except Exception as e:
        logger.error(f"Error toggling favorite: {e}")
        raise AppException(
            message="Failed to toggle favorite",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )


@router.post("/prompt-templates/{template_id}/apply", response_model=ResponseModel)
async def apply_template(
    template_id: str,
    user_prompt: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """应用模板到提示词"""
    result = PromptTemplateService.apply_template(
        template_id=template_id,
        user_prompt=user_prompt
    )
    
    if result is None:
        raise AppException(
            message="Template not found",
            code=ErrorCode.NOT_FOUND,
            status_code=404
        )
    
    return ResponseModel(
        data={
            "original": user_prompt,
            "enhanced": result
        }
    )