"""ACTA MCP server — exposes the board as MCP tools for AI agents."""

from __future__ import annotations

import json
from typing import Optional

from mcp.server.fastmcp import FastMCP

from haeres.board import (
    Severity,
    archive,
    clear,
    clear_all,
    count,
    post,
    read,
)

mcp = FastMCP("haeres_mcp")


@mcp.tool(
    name="acta_post",
    annotations={
        "title": "Post a message to the ACTA board",
        "readOnlyHint": False,
        "destructiveHint": False,
        "idempotentHint": False,
        "openWorldHint": False,
    },
)
async def acta_post(
    message: str,
    sender: str = "unknown",
    to: str = "all",
    severity: Severity = "info",
    subject: Optional[str] = None,
) -> str:
    """Post a message to the ACTA board.

    Creates a timestamped markdown file on the shared board directory.

    Args:
        message: The message body.
        sender: Who is posting (e.g. 'copia', 'vigilia').
        to: Intended recipient, or 'all' for broadcast.
        severity: One of 'action', 'info', 'warning'.
        subject: Optional short subject line (used in filename).

    Returns:
        JSON with the path of the created message file.
    """
    path = post(message=message, sender=sender, to=to, severity=severity, subject=subject)
    return json.dumps({"status": "posted", "path": str(path), "id": path.stem})


@mcp.tool(
    name="acta_read",
    annotations={
        "title": "Read messages from the ACTA board",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def acta_read(to: Optional[str] = None) -> str:
    """Read messages from the ACTA board, newest first.

    Args:
        to: Filter by recipient. If omitted, returns all messages
            (including those addressed to 'all').

    Returns:
        JSON array of message objects with id, from, to, severity, ts, and body.
    """
    msgs = read(to=to)
    return json.dumps(msgs, indent=2) if msgs else "No messages."


@mcp.tool(
    name="acta_clear",
    annotations={
        "title": "Clear (delete) a single message",
        "readOnlyHint": False,
        "destructiveHint": True,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def acta_clear(msg_id: str) -> str:
    """Delete a single message from the board by its ID (filename stem).

    Args:
        msg_id: The message ID (filename without .md extension).

    Returns:
        JSON indicating success or failure.
    """
    ok = clear(msg_id)
    if ok:
        return json.dumps({"status": "cleared", "id": msg_id})
    return json.dumps({"status": "not_found", "id": msg_id})


@mcp.tool(
    name="acta_clear_all",
    annotations={
        "title": "Clear all messages from the board",
        "readOnlyHint": False,
        "destructiveHint": True,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def acta_clear_all() -> str:
    """Delete every message on the board.

    Returns:
        JSON with the count of messages removed.
    """
    n = clear_all()
    return json.dumps({"status": "cleared_all", "count": n})


@mcp.tool(
    name="acta_archive",
    annotations={
        "title": "Archive a single message",
        "readOnlyHint": False,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def acta_archive(msg_id: str) -> str:
    """Move a message to the .archive subdirectory.

    Args:
        msg_id: The message ID (filename without .md extension).

    Returns:
        JSON indicating success or failure.
    """
    ok = archive(msg_id)
    if ok:
        return json.dumps({"status": "archived", "id": msg_id})
    return json.dumps({"status": "not_found", "id": msg_id})


@mcp.tool(
    name="acta_count",
    annotations={
        "title": "Count unread messages on the board",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def acta_count() -> str:
    """Count the number of active (non-archived) messages on the board.

    Returns:
        JSON with the message count.
    """
    n = count()
    return json.dumps({"count": n})


def main() -> None:
    """Entry point for the MCP server."""
    mcp.run()


if __name__ == "__main__":
    main()
