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

from pathlib import Path

from fastapi import APIRouter, HTTPException, Query

from hangar.dependencies import get_project_path, set_project_path
from hangar.installer import detect_full_init_status, run_init_headless
from hangar.models.project import (
    InitCheck,
    InitRequest,
    InitResponse,
    InitStatusResponse,
    InitStepResult,
    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.

    If force=true, opens even if the directory is not fully initialized.
    Otherwise, returns 409 with init status if prerequisites are missing.
    """
    target = Path(body.path).resolve()

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

    if not body.force:
        status = detect_full_init_status(target)
        if not status["ready"]:
            raise HTTPException(
                status_code=409,
                detail="Project not initialized",
            )

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


@router.get("/init-status")
async def get_init_status(path: str = Query(..., description="Directory path to check")) -> InitStatusResponse:
    """Check init prerequisites for a directory."""
    target = Path(path).resolve()

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

    status = detect_full_init_status(target)

    return InitStatusResponse(
        path=str(target),
        checks=[InitCheck(**c) for c in status["checks"]],
        ready=status["ready"],
        plan=status["plan"],
    )


@router.post("/init")
async def init_project(body: InitRequest) -> InitResponse:
    """Initialize a project directory (git, skills, AGENTS.md)."""
    target = Path(body.path).resolve()

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

    steps = run_init_headless(target)

    all_ok = all(s["ok"] for s in steps)

    # If init succeeded, also switch to this project
    if all_ok:
        set_project_path(target)

    return InitResponse(
        status="ok" if all_ok else "partial",
        steps=[InitStepResult(**s) for s in steps],
        project=ProjectInfo(name=target.name, path=str(target)),
    )
