import uuid
from pathlib import Path
from typing import List

from fastapi import APIRouter, File, HTTPException, UploadFile

from mineru_flow.internal.api.v1.schema.response.upload import UploadResponse
from mineru_flow.internal.config.config import media_dir
from mineru_flow.internal.common.logging import get_api_logger

router = APIRouter(tags=["uploads"])
upload_logger = get_api_logger().bind(endpoint="uploads")


@router.post("/uploads", response_model=UploadResponse)
async def upload_files(files: List[UploadFile] = File(...)):
    """上传一个或多个文件"""
    upload_id = str(uuid.uuid4())
    upload_dir = Path(media_dir) / "uploads" / upload_id

    try:
        # 确保上传目录存在
        upload_dir.mkdir(parents=True, exist_ok=True)
        
        file_path = ''

        for file in files:
            if not file.filename:
                continue

            file_path = upload_dir / file.filename
            file_path.parent.mkdir(parents=True, exist_ok=True)

            # 保存文件
            content = await file.read()
            with open(file_path, "wb") as f:
                f.write(content)

            upload_logger.info(
                "文件已上传",
                upload_id=upload_id,
                filename=file.filename,
                path=str(file_path),
                size=len(content),
            )

        return UploadResponse(
            data={"path": str(upload_dir) if len(files) > 1 else str(file_path)},
            message="Files uploaded successfully",
        )

    except Exception as e:
        upload_logger.error(
            "File upload failed", upload_id=upload_id, error=str(e), path=str(upload_dir)
        )
        raise HTTPException(status_code=500, detail="File upload failed") from e
