"""File upload endpoint."""

import uuid
import shutil
from pathlib import Path

from fastapi import APIRouter, UploadFile, File, HTTPException

from backend.config import settings
from backend.models.response import UploadResponse
from backend.services.task_manager import task_manager

router = APIRouter(prefix="/api", tags=["upload"])

ALLOWED_EXTENSIONS = {
    ".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus",
    ".aac", ".wma", ".aiff", ".alac", ".ac3"
}


@router.post("/upload", response_model=UploadResponse)
async def upload_file(file: UploadFile = File(...)):
    extension = Path(file.filename).suffix.lower()
    if extension not in ALLOWED_EXTENSIONS:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file format. Allowed: {', '.join(sorted(ALLOWED_EXTENSIONS))}"
        )

    task_id = str(uuid.uuid4())[:8]
    task_dir = settings.temp_dir / task_id
    task_dir.mkdir(parents=True, exist_ok=True)

    input_path = task_dir / f"input{extension}"
    try:
        with open(input_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    except Exception as e:
        shutil.rmtree(task_dir, ignore_errors=True)
        raise HTTPException(status_code=500, detail=f"Failed to save file: {str(e)}")

    file_size = input_path.stat().st_size
    max_size_bytes = settings.max_upload_size_mb * 1024 * 1024
    if file_size > max_size_bytes:
        shutil.rmtree(task_dir, ignore_errors=True)
        raise HTTPException(
            status_code=400,
            detail=f"File too large. Maximum size: {settings.max_upload_size_mb} MB"
        )

    # Create task entry in the task manager
    task_manager.create_task(task_id, file.filename, file_size)

    return UploadResponse(
        task_id=task_id,
        filename=file.filename,
        size=file_size
    )