#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：login_template.py
模块描述：登录模板管理 API 路由

作者：czj
创建日期：2026-08-05
最后修改：2026-08-05
"""

import logging
from typing import Optional, List

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

from app.database import get_db
from app.schemas.login_template import (
    LoginTemplateCreate,
    LoginTemplateUpdate,
    LoginTemplateResponse,
    LoginTemplateListResponse,
)
from app.services.login_template_service import LoginTemplateService

logger = logging.getLogger(__name__)

router = APIRouter()


def get_template_service(db: AsyncSession = Depends(get_db)) -> LoginTemplateService:
    """
    获取模板服务实例（依赖注入）

    Args:
        db (AsyncSession): 数据库会话

    Returns:
        LoginTemplateService: 模板服务实例
    """
    return LoginTemplateService(db)


@router.post(
    "",
    response_model=LoginTemplateResponse,
    status_code=status.HTTP_201_CREATED,
    summary="创建登录模板",
    description="创建新的登录模板，可设置为默认模板"
)
async def create_template(
    template_data: LoginTemplateCreate,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    创建登录模板

    Args:
        template_data (LoginTemplateCreate): 模板创建数据
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateResponse: 创建的模板
    """
    try:
        template = await service.create(template_data)
        return LoginTemplateResponse.model_validate(template)
    except Exception as e:
        logger.error(f"创建登录模板失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建登录模板失败: {str(e)}"
        )


@router.get(
    "",
    response_model=LoginTemplateListResponse,
    summary="获取登录模板列表",
    description="获取登录模板列表，支持按类型和状态筛选"
)
async def get_templates(
    template_type: Optional[str] = Query(None, description="模板类型筛选: login/navigation/custom"),
    status: Optional[str] = Query(None, description="状态筛选: active/disabled"),
    skip: int = Query(0, ge=0, description="跳过数量"),
    limit: int = Query(100, ge=1, le=500, description="返回数量"),
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    获取登录模板列表

    Args:
        template_type (Optional[str]): 模板类型筛选
        status (Optional[str]): 状态筛选
        skip (int): 跳过数量
        limit (int): 返回数量
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateListResponse: 模板列表
    """
    templates, total = await service.get_list(
        template_type=template_type,
        status=status,
        skip=skip,
        limit=limit
    )

    return LoginTemplateListResponse(
        total=total,
        items=[LoginTemplateResponse.model_validate(t) for t in templates]
    )


@router.get(
    "/default/{template_type}",
    response_model=LoginTemplateResponse,
    summary="获取默认模板",
    description="获取指定类型的默认模板"
)
async def get_default_template(
    template_type: str,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    获取默认模板

    Args:
        template_type (str): 模板类型：login/navigation
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateResponse: 默认模板

    Raises:
        HTTPException: 默认模板不存在时抛出 404
    """
    template = await service.get_default_template(template_type)
    if not template:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"未找到类型为 {template_type} 的默认模板"
        )

    return LoginTemplateResponse.model_validate(template)


@router.get(
    "/{template_id}",
    response_model=LoginTemplateResponse,
    summary="获取单个登录模板",
    description="根据 ID 获取登录模板详情"
)
async def get_template(
    template_id: str,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    获取单个登录模板

    Args:
        template_id (str): 模板ID
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateResponse: 模板详情

    Raises:
        HTTPException: 模板不存在时抛出 404
    """
    template = await service.get_by_id(template_id)
    if not template:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"登录模板不存在: {template_id}"
        )

    return LoginTemplateResponse.model_validate(template)


@router.put(
    "/{template_id}",
    response_model=LoginTemplateResponse,
    summary="更新登录模板",
    description="更新登录模板信息"
)
async def update_template(
    template_id: str,
    template_data: LoginTemplateUpdate,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    更新登录模板

    Args:
        template_id (str): 模板ID
        template_data (LoginTemplateUpdate): 更新数据
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateResponse: 更新后的模板

    Raises:
        HTTPException: 模板不存在时抛出 404
    """
    template = await service.update(template_id, template_data)
    if not template:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"登录模板不存在: {template_id}"
        )

    return LoginTemplateResponse.model_validate(template)


@router.delete(
    "/{template_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="删除登录模板",
    description="删除指定的登录模板"
)
async def delete_template(
    template_id: str,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    删除登录模板

    Args:
        template_id (str): 模板ID
        service (LoginTemplateService): 模板服务

    Raises:
        HTTPException: 模板不存在时抛出 404
    """
    success = await service.delete(template_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"登录模板不存在: {template_id}"
        )


@router.post(
    "/{template_id}/set-default",
    response_model=LoginTemplateResponse,
    summary="设置默认模板",
    description="将指定模板设置为默认模板"
)
async def set_default_template(
    template_id: str,
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    设置默认模板

    Args:
        template_id (str): 模板ID
        service (LoginTemplateService): 模板服务

    Returns:
        LoginTemplateResponse: 更新后的模板

    Raises:
        HTTPException: 模板不存在时抛出 404
    """
    template = await service.set_default_template(template_id)
    if not template:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"登录模板不存在: {template_id}"
        )

    return LoginTemplateResponse.model_validate(template)


@router.post(
    "/init-defaults",
    status_code=status.HTTP_201_CREATED,
    summary="初始化默认模板",
    description="初始化默认登录和导航模板（如果不存在）"
)
async def init_default_templates(
    service: LoginTemplateService = Depends(get_template_service)
):
    """
    初始化默认模板

    如果默认模板不存在，则创建。

    Args:
        service (LoginTemplateService): 模板服务

    Returns:
        dict: 操作结果
    """
    await service.ensure_default_templates()
    return {"message": "默认模板初始化完成"}