"""API router for beads task operations."""

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

from hangar.dependencies import get_beads_service
from hangar.models.beads import BeadsTask, BeadsTaskList
from hangar.services.beads import BeadsService

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


class CloseRequest(BaseModel):
    """Request body for closing a task."""

    reason: str


@router.get("")
async def list_tasks(
    service: BeadsService = Depends(get_beads_service),
) -> BeadsTaskList:
    """List all tasks."""
    try:
        return await service.list_tasks()
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))


@router.get("/ready")
async def ready_tasks(
    service: BeadsService = Depends(get_beads_service),
) -> BeadsTaskList:
    """List tasks with no open blockers."""
    try:
        return await service.ready_tasks()
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))


@router.get("/{task_id}")
async def get_task(
    task_id: str,
    service: BeadsService = Depends(get_beads_service),
) -> BeadsTask:
    """Get a single task by ID."""
    try:
        return await service.show_task(task_id)
    except ValueError as e:
        raise HTTPException(status_code=422, detail=str(e))
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))


@router.post("/{task_id}/claim")
async def claim_task(
    task_id: str,
    service: BeadsService = Depends(get_beads_service),
) -> dict:
    """Claim a task (set status to in_progress)."""
    try:
        await service.claim_task(task_id)
        return {"status": "claimed", "task_id": task_id}
    except ValueError as e:
        raise HTTPException(status_code=422, detail=str(e))
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))


@router.post("/{task_id}/close")
async def close_task(
    task_id: str,
    body: CloseRequest,
    service: BeadsService = Depends(get_beads_service),
) -> dict:
    """Close a task with a reason."""
    try:
        await service.close_task(task_id, body.reason)
        return {"status": "closed", "task_id": task_id}
    except ValueError as e:
        raise HTTPException(status_code=422, detail=str(e))
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))
