from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin, require_roles
from app.db.session import get_db
from app.models import AdminUser
from app.services.pdf_cleanup import (
    cleanup_expired_pdfs,
    get_pdf_cleanup_stats,
    manual_cleanup_certificate,
)

router = APIRouter()


@router.get("/stats")
def get_pdf_stats(
    current_admin: AdminUser = Depends(get_current_admin),
) -> dict:
    """获取PDF清理统计信息"""
    return get_pdf_cleanup_stats()


@router.post("/cleanup")
def trigger_cleanup(
    _: AdminUser = Depends(require_roles("system_admin")),
) -> dict:
    """手动触发PDF清理"""
    return cleanup_expired_pdfs()


@router.post("/cleanup/{certificate_no}")
def cleanup_single_certificate(
    certificate_no: str,
    _: AdminUser = Depends(require_roles("system_admin")),
) -> dict:
    """手动清理指定证书的PDF"""
    success = manual_cleanup_certificate(certificate_no)
    if success:
        return {"message": f"证书 {certificate_no} 的PDF已清理"}
    else:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"证书 {certificate_no} 不存在或清理失败",
        )
