"""Notes MCP server: a minimal but complete template.

Shows the three MCP primitives:
  - tools      (add_note, search_notes, delete_note): actions the model can call
  - resources  (notes://index, notes://{note_id}): data the client can read
  - prompts    (summarize_notes): reusable prompt templates the user can pick

Run over stdio (what desktop clients and coding agents launch):
    notes-mcp-server
Run over Streamable HTTP:
    notes-mcp-server --http --port 8000
IMPORTANT: in stdio mode never print() to stdout; stdout carries the protocol.
Log to stderr instead.
"""
from __future__ import annotations

import argparse
import logging
import os
import sys

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field

from .store import NoteStore

logging.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
log = logging.getLogger("notes-mcp-server")

store = NoteStore(os.environ.get("NOTES_FILE"))  # in-memory unless NOTES_FILE is set

mcp = MCPServer(
    "notes",
    instructions="A small note store. Use search_notes before add_note to avoid duplicates.",
)


class NoteOut(BaseModel):
    """Typed return values give the tool an output schema and structured content."""

    id: str = Field(description="Note id")
    title: str
    body: str
    tags: list[str]


def _out(note) -> NoteOut:
    return NoteOut(id=note.id, title=note.title, body=note.body, tags=note.tags)


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False))
def add_note(title: str, body: str, tags: list[str] | None = None) -> NoteOut:
    """Create a note and return it with its new id.

    Args:
        title: Short title, up to 200 characters.
        body: Note text, up to 20,000 characters.
        tags: Optional list of lowercase tags.
    """
    try:
        note = store.add(title, body, tags)
    except ValueError as exc:
        # ToolError = an anticipated failure: the model sees this message and can retry.
        # Any other exception is treated as a crash and the model only sees a generic error.
        raise ToolError(str(exc)) from exc
    log.info("added note %s", note.id)
    return _out(note)


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def search_notes(query: str, limit: int = 5, tag: str | None = None) -> list[NoteOut]:
    """Find notes whose title or body contains the query words, best matches first.

    Args:
        query: Words to look for. An empty query lists notes.
        limit: Maximum number of results, 1 to 50.
        tag: Only return notes with this tag.
    """
    try:
        return [_out(n) for n in store.search(query, limit=limit, tag=tag)]
    except ValueError as exc:
        raise ToolError(str(exc)) from exc


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=True))
def delete_note(note_id: str) -> str:
    """Delete a note by id. Returns a confirmation message."""
    if not store.delete(note_id):
        raise ToolError(f"note {note_id} does not exist")
    return f"deleted note {note_id}"


@mcp.resource("notes://index", mime_type="text/markdown")
def notes_index() -> str:
    """A Markdown list of all notes."""
    notes = store.all()
    if not notes:
        return "No notes yet."
    return "\n".join(f"- [{n.id}] {n.title}" for n in notes)


@mcp.resource("notes://{note_id}", mime_type="text/markdown")
def read_note(note_id: str) -> str:
    """One note rendered as Markdown."""
    note = store.get(note_id)
    if note is None:
        raise ResourceNotFoundError(f"note {note_id} does not exist")
    tags = f"\n\nTags: {', '.join(note.tags)}" if note.tags else ""
    return f"# {note.title}\n\n{note.body}{tags}"


@mcp.prompt()
def summarize_notes(topic: str) -> str:
    """Ask the model to summarize everything the notes say about a topic."""
    return (f"Use the search_notes tool to find notes about '{topic}'. "
            "Summarize what they say in five bullet points, citing note ids like [3]. "
            "If the notes disagree, point that out.")


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description="Notes MCP server")
    parser.add_argument("--http", action="store_true", help="serve Streamable HTTP instead of stdio")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8000)
    args = parser.parse_args(argv)
    if args.http:
        mcp.run(transport="streamable-http", host=args.host, port=args.port)
    else:
        mcp.run()


if __name__ == "__main__":
    main()
