#!/usr/bin/env tsx
/**
 * SessionStart hook — verify the project's REQUIRED plugins are installed AND enabled.
 *
 * Skills/commands/agents/hooks travel with the repo in `.claude/`; PLUGINS do not —
 * they are external per-user installs. This hook is the recurring safety net that
 * complements the native onboarding (`extraKnownMarketplaces` + `enabledPlugins` in
 * `.claude/settings.json`, which prompts install on folder-trust). The native side
 * resolves first-run install; this hook catches "skipped the prompt" / "later
 * disabled it" on every fresh start.
 *
 * Required plugins (see also `.claude/settings.json` enabledPlugins):
 *   - engram@engram                       → persistent memory (custom marketplace)
 *   - superpowers@claude-plugins-official → base skills + TDD discipline
 *   - code-review@claude-plugins-official → Quality Gate verification (/code-review)
 *
 * NON-BLOCKING by design. It NEVER stops the session:
 *   - Acts only on `source == "startup"` (skips resume/clear/compact to avoid noise).
 *   - Reads MERGED runtime state via `claude plugins list --json` (a user-level
 *     `false` overrides a project-level `true`; raw settings files would miss that).
 *   - On any missing/disabled required plugin → emits `systemMessage` (human) +
 *     `additionalContext` (model) with install commands.
 *   - ANY failure (CLI absent, non-zero, unparseable, unexpected throw) → exit 0,
 *     silent. A broken check must never block startup.
 */
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';

interface RequiredPlugin {
  id: string;
  why: string;
}

const REQUIRED: RequiredPlugin[] = [
  { id: 'engram@engram', why: 'memoria persistente' },
  { id: 'superpowers@claude-plugins-official', why: 'skills base + TDD' },
  { id: 'code-review@claude-plugins-official', why: 'verificación Quality Gate' },
];

// engram lives in a CUSTOM marketplace — surface how to register it if install fails.
const ENGRAM_MARKETPLACE = 'Gentleman-Programming/engram';

interface PluginEntry {
  id?: string;
  enabled?: boolean;
}

main();

function main(): void {
  try {
    run();
  } catch {
    // Never let a hook bug block startup.
    process.exit(0);
  }
}

function run(): void {
  // Only on fresh starts — not resume/clear/compact.
  let source = '';
  try {
    const raw = readFileSync(0, 'utf-8');
    if (raw.trim()) source = (JSON.parse(raw) as { source?: string }).source ?? '';
  } catch {
    process.exit(0);
  }
  if (source !== 'startup') process.exit(0);

  // Merged runtime state is the reliable source (CLI reflects the user<project<local
  // merge; reading a single settings.json would not).
  let plugins: PluginEntry[];
  try {
    const out = execFileSync('claude', ['plugins', 'list', '--json'], {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
      timeout: 10_000,
    });
    const parsed: unknown = JSON.parse(out);
    plugins = Array.isArray(parsed) ? (parsed as PluginEntry[]) : [];
  } catch {
    // CLI not on PATH / non-zero / unparseable → degrade to silent (never block).
    process.exit(0);
  }

  const enabledIds = new Set(
    plugins.filter((p) => p.enabled === true && typeof p.id === 'string').map((p) => p.id),
  );
  const missing = REQUIRED.filter((r) => !enabledIds.has(r.id));
  if (missing.length === 0) process.exit(0);

  const human = missing.map((m) => `${m.id} (${m.why})`).join(', ');
  const installCmds = missing.map((m) => `claude plugin install ${m.id}`).join(' && ');
  const needsEngram = missing.some((m) => m.id === 'engram@engram');
  const engramNote = needsEngram
    ? ` engram usa un marketplace custom — si el install falla, ejecuta primero \`claude plugins marketplace add ${ENGRAM_MARKETPLACE}\`.`
    : '';

  const payload = {
    continue: true,
    systemMessage: `⚠ Plugins requeridos por el proyecto no activos: ${human}. Instala con: ${installCmds}.${engramNote}`,
    hookSpecificOutput: {
      hookEventName: 'SessionStart',
      additionalContext:
        `REQUIRED PROJECT PLUGINS MISSING OR DISABLED: ${human}. ` +
        `Immediately tell the user (in their language) that these plugins are required for this project's workflow, ` +
        `and give the install commands: ${installCmds}.${engramNote}`,
    },
  };
  process.stdout.write(JSON.stringify(payload));
  process.exit(0);
}
