"""PKB MCP server entry point.

Lesson 04 wires the first tool (`pkb.echo`). Subsequent lessons add
`search`, `fetch`, `summarize`, `write`, `export`, plus auth and
observability.
"""

from mcp.server.fastmcp import FastMCP, Context

from pkb.tools import SearchArgs, search as _search, summarize_via_sampling
from pkb.tools import WriteArgs, fetch_note, write_note, summarize_and_save as _summarize_and_save
from pkb.tools import export_notes
from pkb.auth import get_current_user
from pkb.resources import about as _about, get_note as _get_note
from pkb.prompts import welcome as _welcome
from pkb.observability import _configure_logging, log_tool_call

_configure_logging()

mcp = FastMCP("pkb")


@mcp.tool()
@log_tool_call("echo")
def echo(text: str) -> str:
    """Echo the message back."""
    return text


@mcp.tool()
@log_tool_call("search")
def search(args: SearchArgs) -> list[str]:
    """Search notes by full-text query."""
    return _search(args)


@mcp.tool()
@log_tool_call("summarize")
async def summarize(id: str, ctx: Context) -> str:
    """Summarize one note via sampling (calls back to the client's LLM)."""
    return await summarize_via_sampling(id, ctx)


@mcp.tool()
@log_tool_call("fetch")
def fetch(id: str) -> str:
    """Fetch one note's body by id."""
    return fetch_note(id)


@mcp.tool()
@log_tool_call("write")
def write(args: WriteArgs) -> str:
    """Create or overwrite a note."""
    return write_note(args)


@mcp.tool()
@log_tool_call("summarize_and_save")
async def summarize_and_save(id: str, ctx: Context) -> str:
    """Summarize a note and save the result as `{id}-summary`."""
    return await _summarize_and_save(id, ctx)


@mcp.tool()
@log_tool_call("export")
def export(ctx: Context) -> dict[str, str]:
    """Export all of the current user's notes. Requires authentication."""
    user = get_current_user(ctx)
    return export_notes(user)


@mcp.resource("pkb://about")
def about_resource() -> str:
    """About this PKB server."""
    return _about()


@mcp.resource("pkb://notes/{title}")
def note_resource(title: str) -> str:
    """One note by title."""
    return _get_note(title)


@mcp.prompt()
def welcome(name: str = "friend") -> str:
    """Greet the user warmly and offer to summarize today's notes."""
    return _welcome(name)


def main() -> None:
    """Entry point invoked by `pkb` (see pyproject.toml [project.scripts])."""
    mcp.run()


if __name__ == "__main__":
    main()
