'use strict';

// Aider approval prompt provider (stub).
// Aider uses inline (Y)es/(N)o prompts, with (D)on't ask again option.

const APPROVE_RE = /Run shell command\?\s*\(Y\)es\/\(N\)o/;
const DONT_ASK_RE = /\(D\)on't ask again/;

module.exports = {
  id: 'aider',
  name: 'Aider',

  detect(text) {
    const allLines = text.split('\n');
    const nonEmpty = allLines.filter(l => l.trim());
    const tail = nonEmpty.slice(-5);
    return tail.some(l => APPROVE_RE.test(l));
  },

  parse(text) {
    const lines = text.split('\n').map(l => l.trim()).filter(Boolean);

    let promptIdx = -1;
    for (let i = lines.length - 1; i >= 0; i--) {
      if (APPROVE_RE.test(lines[i])) { promptIdx = i; break; }
    }
    if (promptIdx < 0) return null;

    const contextLines = [];
    for (let i = promptIdx - 1; i >= Math.max(0, promptIdx - 10); i--) {
      contextLines.unshift(lines[i]);
    }

    const command = contextLines.join('\n').trim();
    const ctxStart = Math.max(0, promptIdx - 5);
    const fullContext = lines.slice(ctxStart, promptIdx + 1).join('\n');

    // Check for (D)on't ask again option
    let hasAllowAll = false;
    for (let i = promptIdx; i < Math.min(promptIdx + 3, lines.length); i++) {
      if (DONT_ASK_RE.test(lines[i])) { hasAllowAll = true; break; }
    }

    return {
      toolName: 'Aider Shell',
      command: command.slice(0, 2000),
      warning: '',
      fullContext: fullContext.slice(0, 2000),
      hasAllowAll,
      providerId: 'aider',
    };
  },

  approveKeystroke(ctx) {
    return ctx.hasAllowAll ? 'd' : 'y';
  },

  approveAllKeystroke(ctx) {
    return ctx.hasAllowAll ? 'd' : null;
  },

  requiresEnter: true,
};
