"""API 路由 — 项目管理"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, HTTPException

from src.blackboard.registry import ProjectRegistry
from src.utils import get_data_root

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


def _registry() -> ProjectRegistry:
    return ProjectRegistry(get_data_root())


@router.get("")
async def list_projects():
    reg = _registry()
    projects = reg.list_projects()
    return {"projects": {pid: info for pid, info in projects.items()
                         if info.get("status") != "archived"}}


@router.post("")
async def create_project(body: Dict[str, Any]):
    reg = _registry()
    try:
        info = reg.create_project(
            body["id"], body["name"],
            agents=body.get("agents", []),
            description=body.get("description", ""),
        )
        return {"ok": True, "project_id": body["id"]}
    except ValueError as e:
        raise HTTPException(409, str(e))


@router.get("/{project_id}")
async def get_project(project_id: str):
    reg = _registry()
    info = reg.get_project(project_id)
    if not info:
        raise HTTPException(404, f"Project not found: {project_id}")
    return info


@router.post("/{project_id}/archive")
async def archive_project(project_id: str):
    reg = _registry()
    if not reg.archive_project(project_id):
        raise HTTPException(404, f"Project not found: {project_id}")
    return {"ok": True}
