"""Background task API routes."""

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field

from ieum.server.auth import get_request_user_id

logger = logging.getLogger(__name__)

router = APIRouter()


def get_task_service(request: Request) -> Any:
    """Dependency to get the task service."""
    return request.app.state.task_service


def get_session_service(request: Request) -> Any:
    """Dependency to get the session service."""
    return request.app.state.session_service


class TaskCreate(BaseModel):
    """Request body for creating a background task."""

    description: str = Field(..., description="Task description for the agent")


class TaskInfo(BaseModel):
    """Task information response."""

    id: str
    session_id: str
    user_id: str
    description: str
    status: str
    created_at: str
    started_at: str | None
    completed_at: str | None
    result_summary: str | None
    error: str | None
    branch_name: str | None


@router.post("/{session_id}/tasks", response_model=TaskInfo)
async def create_task(
    session_id: str,
    body: TaskCreate,
    request: Request,
    task_service: Any = Depends(get_task_service),
    session_service: Any = Depends(get_session_service),
) -> dict:
    """Create a new background task for a session."""
    user_id = get_request_user_id(request)

    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    task = await task_service.create_task(
        session_id=session_id,
        user_id=user_id,
        description=body.description,
    )
    return task.to_dict()


@router.get("/{session_id}/tasks")
async def list_tasks(
    session_id: str,
    request: Request,
    task_service: Any = Depends(get_task_service),
    session_service: Any = Depends(get_session_service),
) -> list[dict]:
    """List background tasks for a session."""
    user_id = get_request_user_id(request)

    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    tasks = task_service.list_tasks(session_id, user_id=user_id)
    return [t.to_dict() for t in tasks]


@router.get("/{session_id}/tasks/{task_id}", response_model=TaskInfo)
async def get_task(
    session_id: str,
    task_id: str,
    request: Request,
    task_service: Any = Depends(get_task_service),
) -> dict:
    """Get a specific task by ID."""
    task = task_service.get_task(task_id)
    if task is None or task.session_id != session_id:
        raise HTTPException(status_code=404, detail="Task not found")
    return task.to_dict()


@router.delete("/{session_id}/tasks/{task_id}")
async def cancel_task(
    session_id: str,
    task_id: str,
    request: Request,
    task_service: Any = Depends(get_task_service),
) -> dict:
    """Cancel a background task."""
    task = task_service.get_task(task_id)
    if task is None or task.session_id != session_id:
        raise HTTPException(status_code=404, detail="Task not found")

    cancelled = await task_service.cancel_task(task_id)
    if not cancelled:
        raise HTTPException(
            status_code=409,
            detail=f"Task cannot be cancelled (status: {task.status})",
        )
    return {"id": task_id, "status": "cancelled"}
