"""API router for git diff operations."""

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

from hangar.dependencies import get_gitdiff_service
from hangar.services.gitdiff import GitDiffService, TaskCommit, TaskDiff

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


class CommitInfo(BaseModel):
    """A commit associated with a task."""

    hash: str
    short_hash: str
    subject: str
    author: str
    date: str


class TaskDiffResponse(BaseModel):
    """Git diff information for a task."""

    task_id: str
    commits: list[CommitInfo]
    diff_stat: str
    full_diff: str


@router.get("/{task_id}/diff")
async def get_task_diff(
    task_id: str,
    service: GitDiffService = Depends(get_gitdiff_service),
) -> TaskDiffResponse:
    """Get git diff for all commits mentioning a task ID."""
    try:
        result = await service.get_task_diff(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))
    return TaskDiffResponse(
        task_id=result.task_id,
        commits=[
            CommitInfo(
                hash=c.hash,
                short_hash=c.short_hash,
                subject=c.subject,
                author=c.author,
                date=c.date,
            )
            for c in result.commits
        ],
        diff_stat=result.diff_stat,
        full_diff=result.full_diff,
    )
