/**
 * `cerefox_get_help` — return curated agent guidance.
 *
 * Layer 3 of the MCP discoverability response (design doc §10d). Bundles
 * `AGENT_QUICK_REFERENCE.md` whole so remote / hosted-MCP / Edge-Function-only
 * agents — who can't read the repo filesystem — have an in-protocol way to
 * discover Cerefox conventions.
 *
 * The bundle is generated by `scripts/bundle_help.ts` from
 * `AGENT_QUICK_REFERENCE.md` and CI-checked by `scripts/check_help_bundle.ts`.
 *
 * Topic filter: case-insensitive substring match against H2 headings (e.g.
 * `topic="links"` matches the section whose heading contains "links",
 * `topic="update"` matches both "Update Workflow" sections). No topic →
 * the full file plus an index of section headings.
 */

import type { MCPSupabaseClient } from "./types.ts";

import { logUsage } from "./_utils.ts";
import {
  HELP_FULL,
  HELP_SECTION_HEADINGS,
  HELP_SECTIONS,
} from "./get-help-content.ts";
import type { ToolContext, ToolDefinition } from "./types.ts";

async function handler(
  supabase: MCPSupabaseClient,
  args: Record<string, unknown>,
  ctx: ToolContext,
): Promise<string> {
  const topic = (args.topic as string | undefined)?.trim();

  logUsage(supabase, {
    operation: "get_help",
    accessPath: ctx.accessPath,
    requestor: args.requestor as string | undefined,
    query_text: topic ?? null,
    result_count: 1,
  });

  if (!topic) {
    const idx = HELP_SECTION_HEADINGS.map((h) => `  - ${h}`).join("\n");
    return (
      HELP_FULL +
      "\n\n---\n\n" +
      "## Available topics\n\n" +
      "Call `cerefox_get_help(topic: \"<heading>\")` to retrieve a single section.\n\n" +
      idx +
      "\n\n(Topic match is case-insensitive substring on the headings above.)"
    );
  }

  const t = topic.toLowerCase();
  const matched = HELP_SECTION_HEADINGS.filter((h) => h.toLowerCase().includes(t));

  if (matched.length === 0) {
    return (
      `No help topic matched "${topic}".\n\n` +
      `Available topics:\n` +
      HELP_SECTION_HEADINGS.map((h) => `  - ${h}`).join("\n") +
      "\n\nCall `cerefox_get_help()` with no topic for the full document."
    );
  }

  return matched.map((h) => HELP_SECTIONS[h]).join("\n\n---\n\n");
}

export const getHelpTool: ToolDefinition = {
  name: "cerefox_get_help",
  description:
    "Retrieve Cerefox's own agent-usage guidance (the AGENT_QUICK_REFERENCE.md content). Call with no arguments to get the full reference + a section index. Call with `topic` to get a single section (case-insensitive substring match against H2 headings). Use this whenever you're uncertain about Cerefox conventions — link forms, project-membership semantics, update workflows, etc.",
  inputSchema: {
    type: "object",
    properties: {
      topic: {
        type: "string",
        description:
          'Optional. Case-insensitive substring against H2 headings (e.g. "links", "update", "metadata"). Omit for the full reference.',
      },
      requestor: {
        type: "string",
        description:
          'Name of the agent or user making this request. Recorded in the usage log. Defaults to "mcp-agent".',
      },
    },
  },
  handler,
};
