"""Split task endpoint."""

from fastapi import APIRouter, HTTPException, BackgroundTasks

from backend.models.request import SplitRequest
from backend.models.response import SplitResponse, TaskStatus
from backend.services.splitter import run_split_task
from backend.services.task_manager import task_manager

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


@router.post("/split", response_model=SplitResponse)
async def start_split(request: SplitRequest, background_tasks: BackgroundTasks):
    task_id = request.task_id

    if not task_manager.has_task(task_id):
        raise HTTPException(status_code=404, detail=f"Task {task_id} not found")

    status = task_manager.get_status(task_id)
    if status and status["status"] in (TaskStatus.PROCESSING, TaskStatus.DONE):
        raise HTTPException(
            status_code=409,
            detail=f"Task {task_id} is already {status['status']}"
        )

    task_manager.update_task(
        task_id,
        status=TaskStatus.PROCESSING,
        progress=0,
        message="Preparing to split..."
    )

    background_tasks.add_task(run_split_task, task_id, request.tracklist, request.options)

    return SplitResponse(
        task_id=task_id,
        status=TaskStatus.PROCESSING
    )