#!/bin/bash

# Appsettings Guard - PreToolUse Hook
# Blocks Write operations that would remove top-level sections from appsettings*.json
# Uses node -e for JSON parsing (no jq dependency)

set -euo pipefail

# Read hook input from stdin
HOOK_INPUT=$(cat)

# Quick exit: only care about appsettings*.json files (~2ms for non-matching calls)
case "$HOOK_INPUT" in
  *appsettings*) ;; # proceed to full check
  *) exit 0 ;;      # fast exit - not an appsettings file
esac

# Full check using node (guaranteed available in SmartStack projects)
RESULT=$(echo "$HOOK_INPUT" | node -e "
  const fs = require('fs');
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));

  const toolName = input.tool_name || '';
  const filePath = (input.tool_input && input.tool_input.file_path) || '';
  const basename = require('path').basename(filePath);

  // Only guard appsettings*.json files
  if (!/^appsettings.*\.json$/i.test(basename)) {
    process.exit(0);
  }

  // Allow creation of new files (e.g. appsettings.Local.json from /gitflow start)
  if (!fs.existsSync(filePath)) {
    process.exit(0);
  }

  // Only guard Write tool (Edit is safe by design - targeted replacement)
  if (toolName !== 'Write') {
    process.exit(0);
  }

  const newContent = (input.tool_input && input.tool_input.content) || '';

  try {
    const currentContent = fs.readFileSync(filePath, 'utf8');
    const currentObj = JSON.parse(currentContent);
    const newObj = JSON.parse(newContent);

    const currentKeys = Object.keys(currentObj);
    const newKeys = new Set(Object.keys(newObj));
    const missing = currentKeys.filter(k => !newKeys.has(k));

    if (missing.length > 0) {
      const output = {
        continue: true,
        hookSpecificOutput: {
          hookEventName: 'PreToolUse',
          permissionDecision: 'block',
          permissionDecisionReason: 'APPSETTINGS GUARD: Write supprimerait ' + missing.length + ' section(s) top-level: ' + missing.join(', ') + '. Utilise le tool Edit pour modifier des valeurs specifiques au lieu de reecrire le fichier entier. Si tu dois ajouter une section, utilise Edit pour inserer avant le } fermant.'
        }
      };
      process.stdout.write(JSON.stringify(output));
      process.exit(2);
    }
  } catch (e) {
    // JSON parse error on current or new content - allow (tool will handle the error)
    process.exit(0);
  }
" 2>/dev/null) || true

if [ -n "$RESULT" ]; then
  echo "$RESULT"
  exit 2
fi

exit 0
