/**
 * Claude Code Hooks Installer
 *
 * Merges the MORPH-SPEC agent-teams PostToolUse hook into
 * .claude/settings.local.json without overwriting existing config.
 *
 * Called by `morph-spec init` and `morph-spec update`.
 */

import { join } from 'path';
import { readFile, writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';

const DISPATCH_COMMAND = 'node framework/hooks/agent-teams/dispatch.js';

/**
 * Install or update the MORPH-SPEC PostToolUse hook in .claude/settings.local.json.
 *
 * @param {string} targetPath - Project root directory
 * @returns {boolean} true if the hook was newly added, false if it was already present
 */
export async function installClaudeHooks(targetPath) {
  const claudeDir = join(targetPath, '.claude');
  const settingsPath = join(claudeDir, 'settings.local.json');

  // Read existing settings or start empty
  let settings = {};
  if (existsSync(settingsPath)) {
    try {
      settings = JSON.parse(await readFile(settingsPath, 'utf-8'));
    } catch {
      // Malformed JSON — start fresh to avoid corrupting the file
      settings = {};
    }
  }

  // Ensure hooks.PostToolUse array exists
  settings.hooks = settings.hooks || {};
  settings.hooks.PostToolUse = settings.hooks.PostToolUse || [];

  // Check if dispatch.js is already registered (avoid duplicate entries)
  const alreadyRegistered = settings.hooks.PostToolUse.some(entry =>
    Array.isArray(entry.hooks) &&
    entry.hooks.some(h => h.command === DISPATCH_COMMAND)
  );

  if (alreadyRegistered) {
    return false;
  }

  // Add the agent-teams dispatch hook
  settings.hooks.PostToolUse.push({
    matcher: 'Bash',
    hooks: [
      {
        type: 'command',
        command: DISPATCH_COMMAND
      }
    ]
  });

  // Ensure .claude directory exists
  if (!existsSync(claudeDir)) {
    await mkdir(claudeDir, { recursive: true });
  }

  await writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
  return true;
}
