#!/usr/bin/env node
// Generator: writes the committed canonical maxy MCP tool-name artifact from
// every platform/plugins/<dir>/PLUGIN.md. Run via `npm run gen:canonical-tools`
// (platform). The strong build gate (check-canonical-tool-names.mjs) regenerates
// in-memory and fails the build if the committed artifact has drifted.
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { computeCanonicalToolNames, MAXY_CODE_ROOT } from './lib/canonical-tool-names.mjs'

const OUT = join(
  MAXY_CODE_ROOT, 'platform', 'services', 'claude-session-manager', 'src',
  'canonical-tool-names.generated.ts',
)

// Plain newline-delimited maxy plugin list the deterministic missing-tool hook
// (bash) reads to tell a maxy server (mcp__plugin_<p>_<p>__) from a third-party
// bridge that shares the same long-prefix shape (Playwright etc.).
const PLUGINS_TXT = join(
  MAXY_CODE_ROOT, 'platform', 'plugins', 'admin', 'hooks', 'lib',
  'maxy-mcp-plugins.txt',
)

export function renderPluginsList() {
  const { plugins } = computeCanonicalToolNames()
  return plugins.join('\n') + '\n'
}

export function renderArtifact() {
  const { plugins, names } = computeCanonicalToolNames()
  const body = [
    '// GENERATED — do not edit by hand.',
    '// Source: platform/plugins/*/PLUGIN.md (tools: + hidden: blocks).',
    '// Regenerate: cd platform && npm run gen:canonical-tools',
    '// Gate: platform/scripts/check-canonical-tool-names.mjs fails the build on drift.',
    '//',
    '// Canonical long-prefix names every maxy MCP tool is served under by the',
    '// installed-plugin channel: mcp__plugin_<dir>_<dir>__<tool>.',
    '',
    '/** Directory basenames of maxy platform plugins that expose a tool surface. */',
    'export const MAXY_MCP_PLUGINS: readonly string[] = [',
    ...plugins.map((p) => `  ${JSON.stringify(p)},`),
    ']',
    '',
    '/** Every canonical maxy MCP tool name (long prefix), sorted. */',
    'export const CANONICAL_MAXY_TOOL_NAMES: readonly string[] = [',
    ...names.map((n) => `  ${JSON.stringify(n)},`),
    ']',
    '',
  ].join('\n')
  return body
}

function main() {
  writeFileSync(OUT, renderArtifact(), 'utf8')
  writeFileSync(PLUGINS_TXT, renderPluginsList(), 'utf8')
  const { plugins, names } = computeCanonicalToolNames()
  console.log(`[gen] canonical-tool-names: ${plugins.length} plugins, ${names.length} tools -> ${OUT}`)
  console.log(`[gen] maxy-mcp-plugins.txt -> ${PLUGINS_TXT}`)
}

export { OUT, PLUGINS_TXT }

if (import.meta.url === `file://${process.argv[1]}`) main()
