/**
 * lib/help/registry.js — single source of truth for the Help Center + smart search.
 *
 * TWO collections, both pure data (safe to import on client AND server — no fs,
 * no node:sqlite, no secrets):
 *
 *   SETTING_ACTIONS    — "set a value" results. Each one renders a single-field
 *                        inline modal in the smart-search palette and writes
 *                        through an existing audited API route.
 *   HELP_ARTICLE_META  — "read a doc" results. Metadata only; article bodies live
 *                        in content/help/<slug>.md and are loaded server-side by
 *                        lib/help/articles.js (keeps the client search index small).
 *
 * Security: this file NEVER contains or resolves secret values. The smart-search
 * value modal POSTs the value the user types straight to the API route; the route
 * (admin/owner-gated, audited) is the only thing that ever sees it. /api/help
 * resolves *current* state as status only for secrets ('set' / 'unset').
 */

// ---------------------------------------------------------------------------
// Setting actions
// ---------------------------------------------------------------------------
// kind:
//   'secret'     → POST /api/secrets        { name, value, scope:'global' }
//   'config'     → PUT  /api/config         { [configKey]: value }
//   'trust-mode' → PATCH /api/settings/trust-mode { mode }
//
// field.type: 'password' | 'text' | 'select'
//   - 'password' masks input + never echoes the value back (secrets).
//   - 'select'   requires field.options [{ value, label }].
//
// settingsHref: deep link to the full Settings page that shows this value/status.
// docSlug:      related how-to article (must resolve in HELP_ARTICLE_META).

const SECRET_SCOPE = 'global';

/** Build the write request for an action + the value the user entered. */
export function resolveWrite(action, value) {
  switch (action.kind) {
    case 'secret':
      return {
        endpoint: '/api/secrets',
        method: 'POST',
        body: { name: action.secretName, value, scope: SECRET_SCOPE, source: 'help-modal' },
      };
    case 'config':
      return {
        endpoint: '/api/config',
        method: 'PUT',
        body: { [action.configKey]: value },
      };
    case 'trust-mode':
      // Enabling `auto` is a deliberate safety gate server-side: the route
      // rejects it without confirm:true. The field help text warns the user
      // and the explicit Save click is the confirming gesture.
      return {
        endpoint: '/api/settings/trust-mode',
        method: 'PATCH',
        body: value === 'auto' ? { mode: value, confirm: true } : { mode: value },
      };
    default:
      throw new Error(`unknown action kind: ${action.kind}`);
  }
}

export const SETTING_ACTIONS = [
  // ---- Credentials / secrets -------------------------------------------------
  {
    id: 'set-anthropic-key',
    title: 'Set Anthropic API key',
    category: 'Credentials',
    keywords: ['anthropic', 'api key', 'claude', 'apikey', 'llm', 'token', 'cloud engine'],
    kind: 'secret',
    secretName: 'ANTHROPIC_API_KEY',
    field: { label: 'ANTHROPIC_API_KEY', type: 'password', placeholder: 'sk-ant-…', help: 'Used by the Anthropic cloud engine. Stored encrypted in the secrets vault.' },
    settingsHref: '/settings/tools',
    docSlug: 'set-anthropic-key',
  },
  {
    id: 'set-resend-key',
    title: 'Set Resend API key (email)',
    category: 'Credentials',
    keywords: ['resend', 'email', 'api key', 'smtp', 'send mail'],
    kind: 'secret',
    secretName: 'RESEND_API_KEY',
    field: { label: 'RESEND_API_KEY', type: 'password', placeholder: 're_…', help: 'Enables the email tool. Encrypted at rest.' },
    settingsHref: '/settings/connectors',
    docSlug: 'set-resend-key',
  },
  {
    id: 'set-github-token',
    title: 'Set GitHub token',
    category: 'Credentials',
    keywords: ['github', 'token', 'pat', 'api key', 'git', 'repo'],
    kind: 'secret',
    secretName: 'GITHUB_TOKEN',
    field: { label: 'GITHUB_TOKEN', type: 'password', placeholder: 'ghp_… / github_pat_…', help: 'Personal access token for the GitHub tool adapter.' },
    settingsHref: '/settings/connectors',
    docSlug: 'set-github-token',
  },
  {
    id: 'set-supabase-url',
    title: 'Set Supabase URL',
    category: 'Credentials',
    keywords: ['supabase', 'url', 'database', 'project url', 'connect'],
    kind: 'secret',
    secretName: 'SUPABASE_URL',
    field: { label: 'SUPABASE_URL', type: 'text', placeholder: 'https://xxxx.supabase.co', help: 'Project URL for Supabase writes + shared cloud layer.' },
    settingsHref: '/settings/connectors',
    docSlug: 'connect-supabase',
  },
  {
    id: 'set-supabase-service-key',
    title: 'Set Supabase service-role key',
    category: 'Credentials',
    keywords: ['supabase', 'service role', 'key', 'api key', 'secret', 'database'],
    kind: 'secret',
    secretName: 'SUPABASE_SERVICE_ROLE_KEY',
    field: { label: 'SUPABASE_SERVICE_ROLE_KEY', type: 'password', placeholder: 'eyJ…', help: 'Server-side service-role key. Never exposed to the browser.' },
    settingsHref: '/settings/connectors',
    docSlug: 'connect-supabase',
  },

  // ---- Agent runtime config --------------------------------------------------
  {
    id: 'set-default-model',
    title: 'Set default model',
    category: 'Agent runtime',
    keywords: ['model', 'default model', 'llm', 'opus', 'sonnet', 'haiku', 'picker'],
    kind: 'config',
    configKey: 'model',
    field: {
      label: 'Default model',
      type: 'select',
      help: 'Model the main agent uses by default.',
      // IDs MUST match lib/agent-config.js ANTHROPIC_MODELS — PUT /api/config
      // validates against getModels() and rejects anything else with a 400.
      options: [
        { value: 'claude-opus-4-7', label: 'Opus 4.7' },
        { value: 'claude-sonnet-4-6', label: 'Sonnet 4.6' },
        { value: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5' },
      ],
    },
    settingsHref: '/settings/engines',
    docSlug: 'choose-agent-engine',
  },
  {
    id: 'set-design-style',
    title: 'Set artifact design style',
    category: 'Agent runtime',
    keywords: ['design', 'style', 'aesthetic', 'minimal', 'bold', 'soft', 'balanced', 'artifact'],
    kind: 'config',
    configKey: 'designStyle',
    field: {
      label: 'Design style',
      type: 'select',
      help: 'Visual style agents use when producing artifacts.',
      options: [
        { value: 'balanced', label: 'Balanced' },
        { value: 'minimal', label: 'Minimal' },
        { value: 'bold', label: 'Bold' },
        { value: 'soft', label: 'Soft' },
      ],
    },
    settingsHref: '/settings/brand',
    docSlug: null,
  },
  {
    id: 'set-trust-mode',
    title: 'Set main-agent trust mode',
    category: 'Agent runtime',
    keywords: ['trust', 'trust mode', 'auto', 'approval', 'safety', 'permission', 'gate'],
    kind: 'trust-mode',
    field: {
      label: 'Trust mode',
      type: 'select',
      help: 'Warning: auto lets the main agent run high-and-below risk tool calls WITHOUT asking you first (irreversible_external is always gated). Saving auto confirms this. approval_required is the safe default.',
      options: [
        { value: 'approval_required', label: 'Approval required (safe default)' },
        { value: 'auto', label: 'Auto (skip gate for ≤ high risk)' },
      ],
    },
    settingsHref: '/settings/advanced',
    docSlug: 'set-trust-mode',
  },
];

// ---------------------------------------------------------------------------
// Help articles (metadata only — bodies in content/help/<slug>.md)
// ---------------------------------------------------------------------------
export const HELP_ARTICLE_META = [
  {
    id: 'start-whatsapp-bridge',
    slug: 'start-whatsapp-bridge',
    title: 'Start the WhatsApp bridge',
    summary: 'Pair a dedicated WhatsApp number and run the gateway daemon so agents can send and receive messages.',
    category: 'Channels',
    keywords: ['whatsapp', 'bridge', 'gateway', 'baileys', 'pair', 'daemon', 'messages'],
    related: ['secrets-vault-overview'],
  },
  {
    id: 'set-api-key',
    slug: 'set-api-key',
    title: 'Set an API key',
    summary: 'How API keys and secrets are stored, and the fastest way to add one from anywhere with Cmd+K.',
    category: 'Credentials',
    keywords: ['api key', 'secret', 'credential', 'token', 'vault', 'set key'],
    related: ['set-anthropic-key', 'connect-supabase', 'secrets-vault-overview'],
  },
  {
    id: 'set-anthropic-key',
    slug: 'set-anthropic-key',
    title: 'Set the Anthropic API key',
    summary: 'Add the Anthropic key that powers the cloud engine.',
    category: 'Credentials',
    keywords: ['anthropic', 'api key', 'claude', 'cloud engine', 'llm'],
    related: ['choose-agent-engine', 'set-api-key'],
  },
  {
    id: 'set-resend-key',
    slug: 'set-resend-key',
    title: 'Set the Resend API key (email)',
    summary: 'Enable the email tool by adding a Resend key.',
    category: 'Credentials',
    keywords: ['resend', 'email', 'api key', 'send mail'],
    related: ['set-api-key'],
  },
  {
    id: 'set-github-token',
    slug: 'set-github-token',
    title: 'Set a GitHub token',
    summary: 'Add a personal access token to unlock the GitHub tool adapter.',
    category: 'Credentials',
    keywords: ['github', 'token', 'pat', 'repo', 'api key'],
    related: ['set-api-key'],
  },
  {
    id: 'connect-supabase',
    slug: 'connect-supabase',
    title: 'Connect Supabase',
    summary: 'Wire up Supabase URL and keys for database writes and the shared cloud layer.',
    category: 'Credentials',
    keywords: ['supabase', 'database', 'connect', 'url', 'service role', 'shared cloud'],
    related: ['set-api-key', 'secrets-vault-overview'],
  },
  {
    id: 'choose-agent-engine',
    slug: 'choose-agent-engine',
    title: 'Choose an agent engine',
    summary: 'Pick between claude-code, anthropic, ollama, codex, and hermes — and what each needs.',
    category: 'Agent runtime',
    keywords: ['engine', 'model', 'claude-code', 'ollama', 'codex', 'hermes', 'anthropic', 'local'],
    related: ['set-anthropic-key'],
  },
  {
    id: 'set-trust-mode',
    slug: 'set-trust-mode',
    title: 'Set trust mode',
    summary: 'Control whether the main agent gates risky tool calls or runs them automatically.',
    category: 'Agent runtime',
    keywords: ['trust', 'trust mode', 'auto', 'approval', 'safety', 'risk', 'gate'],
    related: ['create-agent'],
  },
  {
    id: 'create-agent',
    slug: 'create-agent',
    title: 'Create an agent',
    summary: 'Spin up a worker, set its schedule, scope its tools, and run it.',
    category: 'Getting started',
    keywords: ['agent', 'create', 'worker', 'new agent', 'caretaker', 'roster'],
    related: ['schedules-and-cron', 'set-trust-mode'],
  },
  {
    id: 'schedules-and-cron',
    slug: 'schedules-and-cron',
    title: 'Schedules and cron',
    summary: 'How schedules queue durable heartbeat work, backfill missed windows, and run automatically.',
    category: 'Getting started',
    keywords: ['schedule', 'cron', 'daily', 'heartbeat', 'backfill', 'recurring'],
    related: ['create-agent'],
  },
  {
    id: 'secrets-vault-overview',
    slug: 'secrets-vault-overview',
    title: 'Secrets vault overview',
    summary: 'Where credentials live, how they are encrypted, and why values are never shown back.',
    category: 'Credentials',
    keywords: ['secrets', 'vault', 'encryption', 'aes', 'master key', 'security'],
    related: ['set-api-key'],
  },
  {
    id: 'keyboard-shortcuts',
    slug: 'keyboard-shortcuts',
    title: 'Keyboard shortcuts',
    summary: 'Every shortcut, including Cmd+K smart search and the composer keys.',
    category: 'Getting started',
    keywords: ['keyboard', 'shortcut', 'cmd k', 'command', 'hotkey', 'search'],
    related: [],
  },
];

/** Distinct categories across articles, in first-seen order. */
export function helpCategories() {
  const seen = [];
  for (const a of HELP_ARTICLE_META) if (!seen.includes(a.category)) seen.push(a.category);
  return seen;
}

/** Lookup by slug (metadata only). */
export function getArticleMeta(slug) {
  return HELP_ARTICLE_META.find((a) => a.slug === slug) || null;
}
