"""API router for project management."""

from pathlib import Path

from fastapi import APIRouter, HTTPException

from hangar.dependencies import get_project_path, set_project_path
from hangar.models.project import OpenProjectRequest, ProjectInfo

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


@router.get("/current")
async def get_current_project() -> ProjectInfo:
    """Get the currently loaded project."""
    project_path = get_project_path()
    return ProjectInfo(name=project_path.name, path=str(project_path))


@router.post("/open")
async def open_project(body: OpenProjectRequest) -> dict:
    """Switch to a different project directory."""
    target = Path(body.path).resolve()

    if not target.is_dir():
        raise HTTPException(status_code=404, detail=f"Directory not found: {body.path}")

    has_beads = (target / ".beads").is_dir()
    has_openspec = (target / "openspec").is_dir()

    if not has_beads and not has_openspec:
        raise HTTPException(
            status_code=400,
            detail=f"Not a Hangar project: {body.path} (no .beads/ or openspec/ directory found)",
        )

    set_project_path(target)
    return {
        "status": "ok",
        "project": ProjectInfo(name=target.name, path=str(target)),
    }
