"""文件格式转换接口：docx/doc ↔ pdf。"""
from __future__ import annotations

import shutil
import tempfile
from pathlib import Path

from fastapi import APIRouter, File, UploadFile
from fastapi.responses import FileResponse
from starlette.background import BackgroundTask

from app.core.response import AppError
from app.services.converter import convert_file

router = APIRouter(prefix="/convert", tags=["文件转换"])

_ALLOWED_TARGETS = {"pdf", "docx", "doc"}


@router.post("/{target}", summary="文件格式转换（docx/doc ↔ pdf）")
async def convert(target: str, file: UploadFile = File(...)):
    target = target.lower().lstrip(".")
    if target not in _ALLOWED_TARGETS:
        raise AppError(f"不支持的目标格式: {target}")

    ext = Path(file.filename or "").suffix.lower()
    if not ext:
        raise AppError("无法识别源文件扩展名")

    tmp_dir = Path(tempfile.mkdtemp())
    src = tmp_dir / f"input{ext}"
    dst = tmp_dir / f"output.{target}"
    src.write_bytes(await file.read())

    result = convert_file(src, dst, target)
    download_name = f"{Path(file.filename).stem}.{target}"
    return FileResponse(
        str(result),
        filename=download_name,
        background=BackgroundTask(shutil.rmtree, str(tmp_dir), ignore_errors=True),
    )
