#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：cleanup.py
模块描述：数据清理 API 路由

作者：czj
创建日期：2026-07-12
"""

import logging
from typing import Optional

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

from app.database import get_db
from app.services.cleanup_service import CleanupService

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/stats", response_model=dict)
async def get_storage_stats(
    db: AsyncSession = Depends(get_db),
):
    """
    获取存储统计信息

    Returns:
        dict: 存储统计
    """
    try:
        service = CleanupService(db)
        stats = await service.get_storage_stats()
        return {
            "success": True,
            "data": stats,
        }
    except Exception as e:
        logger.error(f"获取存储统计失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取存储统计失败: {str(e)}")


@router.post("/cleanup", response_model=dict)
async def cleanup_data(
    days: int = Query(30, ge=1, le=365, description="保留天数"),
    dry_run: bool = Query(False, description="是否模拟运行（不实际删除）"),
    db: AsyncSession = Depends(get_db),
):
    """
    清理过期数据

    Args:
        days (int): 保留天数，超过此天数的数据将被清理
        dry_run (bool): 是否模拟运行

    Returns:
        dict: 清理结果
    """
    try:
        service = CleanupService(db)
        result = await service.cleanup_all(days=days, dry_run=dry_run)

        return {
            "success": True,
            "message": "清理完成" if not dry_run else "模拟运行完成",
            "data": result,
        }
    except Exception as e:
        logger.error(f"清理数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理数据失败: {str(e)}")


@router.post("/cleanup/screenshots", response_model=dict)
async def cleanup_screenshots(
    days: int = Query(30, ge=1, le=365, description="保留天数"),
    dry_run: bool = Query(False, description="是否模拟运行"),
    db: AsyncSession = Depends(get_db),
):
    """
    仅清理过期截图

    Args:
        days (int): 保留天数
        dry_run (bool): 是否模拟运行

    Returns:
        dict: 清理结果
    """
    try:
        service = CleanupService(db)
        result = await service.cleanup_screenshots(days=days, dry_run=dry_run)

        return {
            "success": True,
            "message": "截图清理完成" if not dry_run else "模拟运行完成",
            "data": result,
        }
    except Exception as e:
        logger.error(f"清理截图失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理截图失败: {str(e)}")


@router.post("/cleanup/orphan-screenshots", response_model=dict)
async def cleanup_orphan_screenshots(
    dry_run: bool = Query(False, description="是否模拟运行"),
    db: AsyncSession = Depends(get_db),
):
    """
    清理孤儿截图（没有关联到任何执行记录的截图）

    Args:
        dry_run (bool): 是否模拟运行

    Returns:
        dict: 清理结果
    """
    try:
        service = CleanupService(db)
        result = await service.cleanup_orphan_screenshots(dry_run=dry_run)

        return {
            "success": True,
            "message": "孤儿截图清理完成" if not dry_run else "模拟运行完成",
            "data": result,
        }
    except Exception as e:
        logger.error(f"清理孤儿截图失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理孤儿截图失败: {str(e)}")


@router.post("/optimize", response_model=dict)
async def optimize_database(
    db: AsyncSession = Depends(get_db),
):
    """
    优化数据库（执行 VACUUM）

    Returns:
        dict: 操作结果
    """
    try:
        service = CleanupService(db)
        await service.optimize_database()

        return {
            "success": True,
            "message": "数据库优化完成",
        }
    except Exception as e:
        logger.error(f"数据库优化失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"数据库优化失败: {str(e)}")