"""
图片画廊路由

提供图片查询、删除等管理接口
"""
from fastapi import APIRouter, HTTPException
from typing import Dict, Any, List, Optional
import os

try:
    from backend.services.image_metadata_service import image_metadata_service
except ImportError:
    from services.image_metadata_service import image_metadata_service

router = APIRouter(prefix="/image-gallery", tags=["image-gallery"])


@router.get("/stats")
async def get_gallery_stats():
    """获取画廊统计信息"""
    return await image_metadata_service.get_gallery_stats()


@router.get("/images/{chat_id}")
async def get_chat_images(
    chat_id: str,
    floor: Optional[int] = None
):
    """
    获取指定聊天的图片列表
    
    Args:
        chat_id: 聊天ID (role_name/chat_name)
        floor: 楼层号（可选）
    """
    images = await image_metadata_service.get_images_by_chat(chat_id, floor)
    return {
        "chatId": chat_id,
        "totalImages": len(images),
        "images": [img.model_dump() for img in images]
    }


@router.get("/images/role/{role_name}")
async def get_role_images(role_name: str):
    """获取指定角色的所有图片"""
    images = await image_metadata_service.get_images_by_role(role_name)
    return {
        "roleName": role_name,
        "totalImages": len(images),
        "images": [img.model_dump() for img in images]
    }


@router.delete("/images/{chat_id}/{image_id}")
async def delete_image(chat_id: str, image_id: str):
    """
    删除图片（元数据和文件）
    
    Args:
        chat_id: 聊天ID
        image_id: 图片ID
    """
    # 先获取元数据以得到文件路径
    images = await image_metadata_service.get_images_by_chat(chat_id)
    target_image = None
    for img in images:
        if img.id == image_id:
            target_image = img
            break
    
    if not target_image:
        raise HTTPException(status_code=404, detail="图片不存在")
    
    # 删除元数据
    success = await image_metadata_service.delete_image(chat_id, image_id)
    
    if not success:
        raise HTTPException(status_code=500, detail="删除失败")
    
    # 删除实际文件
    try:
        file_path = image_metadata_service.get_image_full_path(target_image.filepath)
        if file_path.exists():
            file_path.unlink()
    except Exception as e:
        print(f"[ImageGallery] 删除文件失败: {e}")
        # 不抛出异常，因为元数据已删除
    
    return {"message": "图片已删除"}


@router.post("/images/{chat_id}/clear")
async def clear_chat_images(chat_id: str):
    """
    清空指定聊天的所有图片
    
    Args:
        chat_id: 聊天ID
    """
    count = await image_metadata_service.clear_chat_images(chat_id)
    return {
        "message": f"已清空 {count} 张图片",
        "deletedCount": count
    }


@router.post("/images/{chat_id}/{image_id}/set-current")
async def set_current_swipe(chat_id: str, image_id: str):
    """
    设置某张图片为当前显示的 swipe
    
    Args:
        chat_id: 聊天ID
        image_id: 图片ID
    """
    success = await image_metadata_service.set_current_swipe(chat_id, image_id)
    
    if not success:
        raise HTTPException(status_code=404, detail="图片不存在")
    
    return {"message": "已设置为当前显示"}


@router.get("/image/{filepath:path}")
async def get_image(filepath: str):
    """
    获取图片文件
    
    Args:
        filepath: 文件相对路径
    """
    from fastapi.responses import FileResponse
    
    file_path = image_metadata_service.get_image_full_path(filepath)
    
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="图片文件不存在")
    
    return FileResponse(str(file_path))
