"""API router for openspec operations."""

from fastapi import APIRouter, Depends, HTTPException

from hangar.dependencies import get_openspec_service
from hangar.models.openspec import (
    OpenSpecArtifactContent,
    OpenSpecChangeList,
    OpenSpecChangeStatus,
)
from hangar.services.openspec import OpenSpecService

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


@router.get("")
async def list_specs(
    service: OpenSpecService = Depends(get_openspec_service),
) -> OpenSpecChangeList:
    """List all openspec changes."""
    try:
        return await service.list_changes()
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))


@router.get("/{name}")
async def get_spec(
    name: str,
    service: OpenSpecService = Depends(get_openspec_service),
) -> OpenSpecChangeStatus:
    """Get change status with artifact metadata."""
    try:
        return await service.show_change(name)
    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.get("/{name}/artifacts")
async def get_spec_artifacts(
    name: str,
    service: OpenSpecService = Depends(get_openspec_service),
) -> list[OpenSpecArtifactContent]:
    """Get all artifacts for a change with their content."""
    try:
        return await service.read_all_artifacts(name)
    except ValueError as e:
        raise HTTPException(status_code=422, detail=str(e))
    except FileNotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except RuntimeError as e:
        raise HTTPException(status_code=502, detail=str(e))
