/**
 * Help-doc reader for the chat agent's read_help_doc / list_help_docs tools.
 *
 * Reads the markdown docs synced to <configDir>/help by lib/init.ts on first
 * API request (which runs before any chat call). The source tree at
 * lib/help-docs/ is the authoring location; init.ts copies it out at startup.
 */

import { readFileSync, readdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { getConfigDir } from './dirs';

// Authoritative runtime location — populated by ensureHelpDocs() on init.
// We used to also probe `new URL('./help-docs', import.meta.url)` as a
// dev-mode shortcut, but bundlers (Turbopack/webpack) can't ignore the
// static analysis cleanly and the synced copy is always present in
// practice, so it's gone.
function helpDirs(): string[] {
  return [join(getConfigDir(), 'help')];
}

/** List available help-doc filenames (e.g. ["00-overview.md", ...]), sorted. */
export function listHelpDocs(): string[] {
  for (const dir of helpDirs()) {
    try {
      if (!existsSync(dir)) continue;
      const files = readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
      if (files.length) return files;
    } catch { /* try next dir */ }
  }
  return [];
}

/** Read one help doc by filename. Returns null if not found. Path-traversal safe. */
export function readHelpDoc(name: string): string | null {
  const base = (name || '').split(/[\\/]/).pop() || '';
  if (!base.endsWith('.md')) return null;
  for (const dir of helpDirs()) {
    try {
      const file = join(dir, base);
      if (existsSync(file)) return readFileSync(file, 'utf-8');
    } catch { /* try next dir */ }
  }
  return null;
}
