"""A workspace MCP server that combines the cookbook recipes (Python SDK v2).

Tools:
  list_files    paginated, confined to the workspace root
  read_file     line ranges + output budget
  query_db      read-only SQL enforced by SQLite itself, rate limited
  delete_file   two-step: preview returns a token, then confirm with it
Resource:
  db://schema   the database schema as text

Run:  WORKSPACE=/some/dir DB=/some/file.db python examples/workspace_server.py
"""
from __future__ import annotations

import logging
import os
import secrets
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from mcp.server.mcpserver import Context, MCPServer  # noqa: E402
from mcp.server.mcpserver.exceptions import ToolError  # noqa: E402
from mcp.types import ToolAnnotations  # noqa: E402
from pydantic import BaseModel  # noqa: E402

from cookbook.confirm import ConfirmationError, Confirmations  # noqa: E402
from cookbook.pagination import CursorError, paginate  # noqa: E402
from cookbook.paths import PathNotAllowed, safe_resolve  # noqa: E402
from cookbook.ratelimit import TokenBucket  # noqa: E402
from cookbook.sqlguard import QueryRejected, ReadOnlySQLite  # noqa: E402
from cookbook.truncate import slice_lines, truncate_text  # noqa: E402

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("workspace")


class FilePage(BaseModel):
    files: list[str]
    next_cursor: str | None


class QueryResult(BaseModel):
    columns: list[str]
    rows: list[list]
    truncated: bool


class DeleteResult(BaseModel):
    path: str
    deleted: bool
    size_bytes: int
    confirm_token: str | None
    message: str


def build_server(workspace: Path, db_path: Path | None = None) -> MCPServer:
    roots = [workspace]
    cursor_secret = secrets.token_bytes(32)
    confirmations = Confirmations(ttl_seconds=300)
    bucket = TokenBucket(rate_per_sec=2, burst=5)
    db = ReadOnlySQLite(db_path) if db_path else None
    mcp = MCPServer("workspace", instructions=(
        "Files are confined to one workspace folder. Deleting needs two calls: "
        "delete_file without confirm_token to preview, then again with the token after the user agrees."))

    def resolve(path: str, must_exist: bool = True) -> Path:
        try:
            return safe_resolve(path, roots, must_exist=must_exist)
        except FileNotFoundError as exc:
            raise ToolError(f"{path} does not exist") from exc
        except PathNotAllowed as exc:
            raise ToolError(str(exc)) from exc

    @mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
    def list_files(pattern: str = "**/*", cursor: str | None = None) -> FilePage:
        """List files in the workspace matching a glob pattern, 50 per page.
        Pass next_cursor back as cursor to get the next page."""
        if ".." in pattern or pattern.startswith("/"):
            raise ToolError("pattern must be relative and must not contain '..'")
        files = sorted(str(p.relative_to(workspace)) for p in workspace.glob(pattern) if p.is_file())
        try:
            page, nxt = paginate(files, {"pattern": pattern}, cursor_secret, cursor, page_size=50)
        except CursorError as exc:
            raise ToolError(f"{exc}; call list_files again without a cursor") from exc
        return FilePage(files=page, next_cursor=nxt)

    @mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
    def read_file(path: str, offset: int = 0, limit: int = 200) -> str:
        """Read a text file from the workspace with line numbers.
        offset is the 0-based first line, limit the number of lines (max 500)."""
        if not 1 <= limit <= 500 or offset < 0:
            raise ToolError("offset must be >= 0 and limit between 1 and 500")
        real = resolve(path)
        if not real.is_file():
            raise ToolError(f"{path} is not a file")
        try:
            text = real.read_text(encoding="utf-8")
        except UnicodeDecodeError as exc:
            raise ToolError(f"{path} is not a UTF-8 text file") from exc
        body, more = slice_lines(text, offset, limit)
        if more:
            body += f"\n[more lines available: call read_file with offset={offset + limit}]"
        return truncate_text(body, 12_000)

    @mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
    def query_db(sql: str) -> QueryResult:
        """Run one read-only SQL SELECT against the workspace database (SQLite dialect).
        Returns at most 200 rows. Read db://schema first to see the tables."""
        if db is None:
            raise ToolError("no database is configured for this workspace")
        wait = bucket.try_acquire()
        if wait:
            raise ToolError(f"rate limited; try again in {wait:.1f} seconds")
        try:
            return QueryResult(**db.query(sql))
        except QueryRejected as exc:
            raise ToolError(f"query rejected: {exc}") from exc

    @mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=False))
    async def delete_file(path: str, ctx: Context, confirm_token: str | None = None) -> DeleteResult:
        """Delete a workspace file in two steps. Without confirm_token: returns a preview and a token.
        Show the preview to the user; only if they agree, call again with the same path and the token."""
        real = resolve(path)
        rel = str(real.relative_to(workspace.resolve()))
        size = real.stat().st_size
        if confirm_token is None:
            token = confirmations.issue("delete_file", {"path": rel})
            return DeleteResult(path=rel, deleted=False, size_bytes=size, confirm_token=token,
                                message=f"This will permanently delete {rel}. Ask the user to confirm.")
        try:
            confirmations.verify(confirm_token, "delete_file", {"path": rel})
        except ConfirmationError as exc:
            raise ToolError(str(exc)) from exc
        real.unlink()
        await ctx.info({"message": "deleted file", "path": rel})
        log.info("deleted %s", rel)
        return DeleteResult(path=rel, deleted=True, size_bytes=size, confirm_token=None, message=f"deleted {rel}")

    @mcp.resource("db://schema", mime_type="text/plain")
    def db_schema() -> str:
        """CREATE statements for every table and view in the workspace database."""
        return db.schema() if db else "No database configured."

    return mcp


if __name__ == "__main__":
    ws = Path(os.environ.get("WORKSPACE", ".")).resolve()
    dbp = os.environ.get("DB")
    build_server(ws, Path(dbp) if dbp else None).run()
