"""Project tools: tms_list_projects, tms_get_project."""
from __future__ import annotations

import asyncio
import json

from tms_mcp.api_client import ApiError, client


def register(mcp):
    @mcp.tool()
    async def tms_list_projects(organization_id: int | None = None) -> str:
        """List projects, optionally filtered by organization.

        Args:
            organization_id: Filter projects to a specific organization. If omitted, lists all accessible projects.
        """
        try:
            data = await client.get("/projects/", organization_id=organization_id)
            if not data:
                return "No projects found."
            return json.dumps(data, indent=2, default=str)
        except ApiError as e:
            return str(e)

    @mcp.tool()
    async def tms_get_project(project_id: int, include_members: bool = True) -> str:
        """Get detailed information about a specific project.

        Args:
            project_id: The project ID.
            include_members: If True, also fetches the list of project members with their roles.
        """
        try:
            if include_members:
                project, members = await asyncio.gather(
                    client.get(f"/projects/{project_id}"),
                    client.get(f"/projects/{project_id}/members"),
                )
                project["members"] = members
            else:
                project = await client.get(f"/projects/{project_id}")
            return json.dumps(project, indent=2, default=str)
        except ApiError as e:
            return str(e)
