from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func
from typing import List, Optional
import logging

from app.api.v1 import deps
from app.models.application import Application
from app.models.user import User
from app.schemas.application import CategoryStats, CategoryUpdate, CategoryMerge
from app.services.sms_service import SmsService

router = APIRouter()
logger = logging.getLogger(__name__)

@router.get("/categories", response_model=List[CategoryStats], summary="获取所有应用分类")
def get_categories(
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
    search: Optional[str] = Query(None, description="搜索分类名称")
):
    """
    获取所有应用分类及其统计信息。
    超级管理员查看所有，开发者只查看自己应用使用的分类。
    """
    try:
        # 记录请求参数
        logger.info(f"[分类管理] 请求开始 - 用户ID: {current_user.id}, 角色: {current_user.role}, 搜索参数: {repr(search)}")
        logger.info(f"[分类管理] search参数类型: {type(search)}, 值: {search}")
        
        # 构建查询
        query = db.query(
            Application.category,
            func.count(Application.id).label('app_count')
        ).filter(
            Application.is_deleted == False,
            Application.category.isnot(None),
            Application.category != ''
        )
        
        logger.info(f"[分类管理] 基础查询构建完成")
        
        if current_user.role != "SUPER_ADMIN":
            query = query.filter(Application.owner_id == current_user.id)
            logger.info(f"[分类管理] 已添加所有者过滤条件: owner_id={current_user.id}")
        
        # 处理空字符串，转换为 None，只处理有效的搜索关键词
        if search and search.strip():
            search_term = search.strip()
            query = query.filter(Application.category.ilike(f"%{search_term}%"))
            logger.info(f"[分类管理] 已添加搜索过滤条件: {search_term}")
        else:
            logger.info(f"[分类管理] 无搜索条件或搜索条件为空")
        
        # 执行查询
        logger.info(f"[分类管理] 开始执行数据库查询")
        results = query.group_by(Application.category).order_by(Application.category).all()
        logger.info(f"[分类管理] 查询完成，结果数量: {len(results)}")
        
        # 记录原始查询结果
        logger.info(f"[分类管理] 原始查询结果详情:")
        for idx, row in enumerate(results):
            logger.info(f"  [{idx}] category={repr(row[0])}, type={type(row[0])}, app_count={row[1]}, type={type(row[1])}")
        
        # 构建返回数据
        category_list = []
        for idx, row in enumerate(results):
            try:
                category_value = row[0]
                app_count_value = row[1]
                
                logger.info(f"[分类管理] 处理第 {idx} 条记录: category={repr(category_value)}, app_count={app_count_value}")
                
                if category_value is None:
                    logger.warning(f"[分类管理] 跳过 None 值记录: {idx}")
                    continue
                
                # 创建 CategoryStats 对象
                category_stat = CategoryStats(
                    category=category_value,
                    app_count=app_count_value
                )
                
                logger.info(f"[分类管理] 成功创建 CategoryStats: {category_stat.model_dump()}")
                category_list.append(category_stat)
                
            except Exception as e:
                logger.error(f"[分类管理] 处理第 {idx} 条记录时出错: {e}", exc_info=True)
                logger.error(f"[分类管理] 错误记录详情: row={row}, row[0]={repr(row[0])}, row[1]={repr(row[1])}")
                raise
        
        logger.info(f"[分类管理] 最终返回数据数量: {len(category_list)}")
        logger.info(f"[分类管理] 返回数据详情: {[item.model_dump() for item in category_list]}")
        
        return category_list
        
    except Exception as e:
        logger.error(f"[分类管理] 发生未捕获的异常: {e}", exc_info=True)
        logger.error(f"[分类管理] 异常类型: {type(e).__name__}")
        raise

@router.put("/categories/rename", summary="重命名分类")
def rename_category(
    rename_data: CategoryUpdate,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
):
    """
    重命名应用分类。
    需要手机验证码验证。
    """
    if not rename_data.verification_code:
        raise HTTPException(status_code=400, detail="需要提供手机验证码")
    
    if not SmsService.verify_code(current_user.mobile, rename_data.verification_code):
        raise HTTPException(status_code=400, detail="验证码无效或已过期")
    
    # 构建查询
    query = db.query(Application).filter(
        Application.is_deleted == False,
        Application.category == rename_data.old_category
    )
    
    if current_user.role != "SUPER_ADMIN":
        query = query.filter(Application.owner_id == current_user.id)
    
    apps = query.all()
    
    if not apps:
        raise HTTPException(status_code=404, detail=f"分类 '{rename_data.old_category}' 不存在或无权限")
    
    # 检查新分类名是否已存在
    new_category_query = db.query(Application).filter(
        Application.is_deleted == False,
        Application.category == rename_data.new_category
    )
    if current_user.role != "SUPER_ADMIN":
        new_category_query = new_category_query.filter(Application.owner_id == current_user.id)
    
    if new_category_query.first():
        raise HTTPException(status_code=400, detail=f"分类 '{rename_data.new_category}' 已存在")
    
    # 更新所有应用的分类
    for app in apps:
        app.category = rename_data.new_category
    
    db.commit()
    
    return {"message": f"成功将 {len(apps)} 个应用的分类从 '{rename_data.old_category}' 重命名为 '{rename_data.new_category}'"}

@router.post("/categories/merge", summary="合并分类")
def merge_categories(
    merge_data: CategoryMerge,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
):
    """
    将源分类下的所有应用合并到目标分类。
    需要手机验证码验证。
    """
    if not merge_data.verification_code:
        raise HTTPException(status_code=400, detail="需要提供手机验证码")
    
    if not SmsService.verify_code(current_user.mobile, merge_data.verification_code):
        raise HTTPException(status_code=400, detail="验证码无效或已过期")
    
    if merge_data.source_category == merge_data.target_category:
        raise HTTPException(status_code=400, detail="源分类和目标分类不能相同")
    
    # 构建查询
    query = db.query(Application).filter(
        Application.is_deleted == False,
        Application.category == merge_data.source_category
    )
    
    if current_user.role != "SUPER_ADMIN":
        query = query.filter(Application.owner_id == current_user.id)
    
    apps = query.all()
    
    if not apps:
        raise HTTPException(status_code=404, detail=f"分类 '{merge_data.source_category}' 不存在或无权限")
    
    # 更新所有应用的分类
    for app in apps:
        app.category = merge_data.target_category
    
    db.commit()
    
    return {"message": f"成功将 {len(apps)} 个应用从分类 '{merge_data.source_category}' 合并到 '{merge_data.target_category}'"}

@router.delete("/categories", summary="删除分类")
def delete_category(
    category: str = Query(..., description="要删除的分类名称"),
    verification_code: str = Query(..., description="手机验证码"),
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
):
    """
    删除分类（将该分类下的所有应用的分类字段设为空）。
    需要手机验证码验证。
    """
    if not SmsService.verify_code(current_user.mobile, verification_code):
        raise HTTPException(status_code=400, detail="验证码无效或已过期")
    
    # 构建查询
    query = db.query(Application).filter(
        Application.is_deleted == False,
        Application.category == category
    )
    
    if current_user.role != "SUPER_ADMIN":
        query = query.filter(Application.owner_id == current_user.id)
    
    apps = query.all()
    
    if not apps:
        raise HTTPException(status_code=404, detail=f"分类 '{category}' 不存在或无权限")
    
    # 将分类设为空
    for app in apps:
        app.category = None
    
    db.commit()
    
    return {"message": f"成功删除分类 '{category}'，已清空 {len(apps)} 个应用的分类字段"}
