/** Help tool — answers conceptual questions ("what's a pipeline?", "how do I
 *  install Forge?") from the bundled help docs, so the client can explain Forge
 *  without the user opening the UI. Reads lib/help-docs (synced to <dataDir>/help). */

import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { getDataDir } from '@/lib/dirs';
import { text, fail, guard } from './_shared';

/** Resolve the help-docs directory: the synced runtime copy, else the repo source. */
function helpDir(): string | null {
  const synced = join(getDataDir(), 'help');
  if (existsSync(synced)) return synced;
  const src = join(process.cwd(), 'lib', 'help-docs');
  if (existsSync(src)) return src;
  return null;
}

/** "05-pipelines.md" → "pipelines" */
const slug = (file: string) => file.replace(/\.md$/, '').replace(/^\d+-/, '');

export function registerHelpTools(server: McpServer): void {
  server.tool(
    'forge_help',
    'Explain a Forge concept or feature from the official docs (e.g. topic "pipelines", "connectors", "tasks", "workspace", "overview" for install/setup). Call with no topic to list available topics.',
    { topic: z.string().optional().describe('Doc topic, e.g. "pipelines", "install", "connectors"') },
    (params) => guard(() => {
      const dir = helpDir();
      if (!dir) return fail('Help docs not found.');
      const files = readdirSync(dir).filter((f) => f.endsWith('.md') && f !== 'CLAUDE.md');
      if (!params.topic) {
        const topics = files.map(slug).sort();
        return text(`Available help topics:\n${topics.map((t) => `• ${t}`).join('\n')}\n\nCall forge_help with one of these, e.g. topic="pipelines".`);
      }
      const q = params.topic.toLowerCase().replace(/[\s-]+/g, '');
      const aliases: Record<string, string> = { install: 'overview', setup: 'overview', model: 'settings', agent: 'settings', marketplace: 'skills' };
      const wanted = aliases[q] || q;
      const match = files.find((f) => slug(f).replace(/-/g, '').includes(wanted))
        || files.find((f) => slug(f).replace(/-/g, '').includes(q));
      if (!match) {
        return fail(`No help topic matches "${params.topic}". Try: ${files.map(slug).join(', ')}.`);
      }
      const body = readFileSync(join(dir, match), 'utf-8');
      const clipped = body.length > 6000 ? body.slice(0, 6000) + '\n\n…(truncated)' : body;
      return text(clipped);
    }),
  );
}
