import logging
from datetime import datetime, timezone
from typing import Optional, List, Dict, Any

from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from app.services.image_service import ImageService
from app.services.jwt_token import verify_token
from app.schemas.base import ApiResponse
from pydantic import BaseModel
from app.utils.auth_dependency import get_current_user_with_refresh

# 获取logger
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/images", tags=["图片管理"])
security = HTTPBearer()

# --- 请求模型 ---

class CategoryAdd(BaseModel):
    type_name: str
    parent_id: str = '0'
    remark: Optional[str] = None

class CategoryUpdate(BaseModel):
    type_name: str
    remark: Optional[str] = None

class ImageAdd(BaseModel):
    image_name: str
    image_url: str
    image_type: str
    description: Optional[str] = None

class UploadUrlRequest(BaseModel):
    filename: str
    content_type: str
    prefix: Optional[str] = None

class BatchAddRequest(BaseModel):
    ids: List[str]
    project_name: str
    tags: Optional[List[str]] = None

# --- 分类管理 API ---

@router.get("/categories")
async def get_categories(current_user: dict = Depends(get_current_user_with_refresh)):
    """获取所有图片分类树"""
    try:
        service = ImageService()
        data = await service.get_categories()
        return ApiResponse(code=0, message="成功", data=data, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("获取分类失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.post("/categories")
async def add_category(data: CategoryAdd, current_user: dict = Depends(get_current_user_with_refresh)):
    """新增分类"""
    try:
        user_id = current_user.get("sub", "system")
        service = ImageService()
        success, message, category_id = await service.add_category(data.model_dump(), user_id)
        
        if success:
            return ApiResponse(code=0, message=message, data={"id": category_id}, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=500, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("新增分类失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.put("/categories/{category_id}")
async def edit_category(category_id: str, data: CategoryUpdate, current_user: dict = Depends(get_current_user_with_refresh)):
    """编辑分类"""
    try:
        user_id = current_user.get("sub", "system")
        service = ImageService()
        success, message = await service.edit_category(category_id, data.model_dump(), user_id)
        
        if success:
            return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=500, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("编辑分类失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.delete("/categories/{category_id}")
async def delete_category(category_id: str, current_user: dict = Depends(get_current_user_with_refresh)):
    """删除分类"""
    try:
        service = ImageService()
        success, message = await service.delete_category(category_id)
        
        if success:
            return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=400, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("删除分类失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

# --- 图片管理 API ---

@router.get("")
async def get_image_list(
    category_id: Optional[str] = None, 
    page: int = 1, 
    page_size: int = 10, 
    current_user: dict = Depends(get_current_user_with_refresh)
):
    """获取图片列表"""
    try:
        service = ImageService()
        data = await service.get_image_list(category_id, page, page_size)
        return ApiResponse(code=0, message="成功", data=data, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("获取图片列表失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.post("")
async def add_image(data: ImageAdd, current_user: dict = Depends(get_current_user_with_refresh)):
    """保存图片信息"""
    try:
        user_id = current_user.get("sub", "system")
        service = ImageService()
        success, message = await service.add_image(data.model_dump(), user_id)
        
        if success:
            return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=500, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("保存图片失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.delete("/{image_id}")
async def delete_image(image_id: str, current_user: dict = Depends(get_current_user_with_refresh)):
    """删除图片"""
    try:
        service = ImageService()
        success, message = await service.delete_image(image_id)
        
        if success:
            return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=500, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("删除图片失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.post("/upload-url")
async def get_upload_url(req: UploadUrlRequest, current_user: dict = Depends(get_current_user_with_refresh)):
    """获取 MinIO 预签名上传 URL"""
    try:
        service = ImageService()
        success, message, data = await service.get_upload_url(req.filename, req.content_type, prefix=req.prefix)
        
        if success:
            return ApiResponse(code=0, message=message, data=data, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
        else:
            return ApiResponse(code=500, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
    except Exception as e:
        logger.exception("获取上传链接失败")
        return ApiResponse(code=500, message=str(e), timestamp=datetime.now(timezone.utc).isoformat()).model_dump()

@router.post("/batch-add-to-task")
async def batch_add_to_task(req: BatchAddRequest, current_user: dict = Depends(get_current_user_with_refresh)):
    """批量加入任务中心 (设置 whether_to_task = 1)"""
    try:
        user_id = current_user.get("sub", "admin")
        username = current_user.get("username", user_id)
        
        service = ImageService()
        success, message = await service.batch_add_to_task(req.ids, username, req.project_name, tags=req.tags)
        
        return ApiResponse(
            code=0 if success else 500, 
            message=message, 
            timestamp=datetime.now(timezone.utc).isoformat()
        ).model_dump()
    except Exception as e:
        logger.exception("批量加入任务失败")
        return ApiResponse(code=500, message=f"批量加入任务失败: {str(e)}", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
