"""MCP server setup and tool registration."""

from mcp.server.fastmcp import FastMCP

from personal_assistant_mcp.client import AuthClient
from personal_assistant_mcp.config import load_credentials
from personal_assistant_mcp.tools import notes, tags

mcp = FastMCP("personal-assistant")

_client: AuthClient | None = None


def _get_client() -> AuthClient:
    global _client
    if _client is None:
        credentials = load_credentials()
        _client = AuthClient(credentials)
    return _client


@mcp.tool()
async def list_tags(tag_type: str | None = None) -> list[dict]:
    """List tags, areas, or projects.

    Args:
        tag_type: Optional filter — "area", "project", or "tag".
    """
    return await tags.list_tags(_get_client(), tag_type)


@mcp.tool()
async def list_notes(
    tag: str | None = None,
    q: str | None = None,
    page: int = 1,
) -> dict:
    """List notes with optional filters.

    Args:
        tag: Optional tag name to filter by.
        q: Optional search query.
        page: Page number (default 1).
    """
    return await notes.list_notes(_get_client(), tag, q, page)


@mcp.tool()
async def get_note(note_id: str) -> dict:
    """Get a note's full content by its UUID.

    Args:
        note_id: UUID of the note.
    """
    return await notes.get_note(_get_client(), note_id)


@mcp.tool()
async def create_note(
    title: str,
    content: str = "",
    tag_names: list[str] | None = None,
) -> dict:
    """Create a new note.

    Args:
        title: Note title.
        content: Markdown content.
        tag_names: Optional list of tag names to associate.
    """
    return await notes.create_note(_get_client(), title, content, tag_names)


@mcp.tool()
async def update_note(
    note_id: str,
    title: str | None = None,
    content: str | None = None,
    tag_names: list[str] | None = None,
) -> dict:
    """Update an existing note.

    Args:
        note_id: UUID of the note to update.
        title: New title (optional).
        content: New markdown content (optional).
        tag_names: New list of tag names (optional).
    """
    return await notes.update_note(_get_client(), note_id, title, content, tag_names)
