import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { OPERATION_PROFILES, safeBridgeData } from "../safety.js";

export function registerPagesTools(server: McpServer): void {
  server.tool(
    "pages.search",
    "Search for Pages document files by name or content.",
    {
      query: z.string().max(500).describe("Search term to match against file names or content"),
      limit: z
        .number()
        .int()
        .min(1)
        .max(100)
        .optional()
        .describe("Maximum number of results to return"),
    },
    async ({ query, limit }) => {
      const args = ["pages-search", "--query", query];
      if (limit !== undefined) {
        args.push("--limit", String(limit));
      }
      const data = await safeBridgeData(args, OPERATION_PROFILES.fileRead);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.read",
    "Read the body text from a Pages document.",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
    },
    async ({ file }) => {
      const data = await safeBridgeData(
        ["pages-read", "--file", file],
        OPERATION_PROFILES.pages
      );
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.write",
    "Set the body text of a Pages document.",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
      text: z.string().max(5_000_000).describe("Text to write as the document body"),
    },
    async ({ file, text }) => {
      const data = await safeBridgeData([
        "pages-write",
        "--file",
        file,
        "--text",
        text,
      ], OPERATION_PROFILES.pages);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.create",
    "Create a new Pages document. Optionally provide initial text or a template.",
    {
      file: z.string().max(1024).describe("Path for the new Pages file"),
      text: z
        .string()
        .max(5_000_000)
        .optional()
        .describe("Initial body text for the document"),
      template: z
        .string()
        .max(10_000)
        .optional()
        .describe("Template name or path to use"),
    },
    async ({ file, text, template }) => {
      const args = ["pages-create", "--file", file];
      if (text) args.push("--text", text);
      if (template) args.push("--template", template);
      const result = await safeBridgeData(args, OPERATION_PROFILES.pages);
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.find_replace",
    "Find and replace text in a Pages document.",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
      find: z.string().max(10_000).describe("Text to search for"),
      replace: z.string().max(10_000).describe("Replacement text"),
      all: z
        .boolean()
        .optional()
        .describe("Replace all occurrences (default: false, replaces first only)"),
    },
    async ({ file, find, replace, all }) => {
      const args = [
        "pages-find-replace",
        "--file",
        file,
        "--find",
        find,
        "--replace",
        replace,
      ];
      if (all) args.push("--all");
      const data = await safeBridgeData(args, OPERATION_PROFILES.pages);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.insert_table",
    "Insert a table into a Pages document from JSON data.",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
      data: z
        .string()
        .max(1_000_000)
        .describe("Table data as JSON array of arrays (e.g. [[\"Name\",\"Age\"],[\"Alice\",30]])"),
    },
    async ({ file, data: tableData }) => {
      const args = ["pages-insert-table", "--file", file, "--data", tableData];
      const result = await safeBridgeData(args, OPERATION_PROFILES.pages);
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.list_sections",
    "List sections in a Pages document with preview text and word counts.",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
    },
    async ({ file }) => {
      const data = await safeBridgeData(
        ["pages-list-sections", "--file", file],
        OPERATION_PROFILES.pages
      );
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.export",
    "Export a Pages document to another format (PDF, Word, TXT, or EPUB).",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
      format: z
        .enum(["pdf", "docx", "txt", "epub"])
        .describe("Export format: pdf, docx, txt, or epub"),
      dest: z
        .string()
        .max(1024)
        .optional()
        .describe("Output file path (defaults to same directory as input)"),
    },
    async ({ file, format, dest }) => {
      const args = ["pages-export", "--file", file, "--format", format];
      if (dest) args.push("--dest", dest);
      const data = await safeBridgeData(args, OPERATION_PROFILES.pages);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );

  server.tool(
    "pages.info",
    "Get metadata about a Pages document (name, word count, page count).",
    {
      file: z.string().max(1024).describe("Path to the Pages file"),
    },
    async ({ file }) => {
      const data = await safeBridgeData(
        ["pages-info", "--file", file],
        OPERATION_PROFILES.pages
      );
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    }
  );
}
