'use strict';

// Gemini CLI approval prompt provider (stub).
// Gemini CLI uses inline (y/n/always) prompts.

const APPROVE_RE = /\bApprove\?\s*\(y\/n\/always\)/i;

module.exports = {
  id: 'gemini',
  name: 'Gemini CLI',

  detect(text) {
    const allLines = text.split('\n');
    // Only match in last 5 non-empty lines to avoid stale prompts
    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;

    // Look above the prompt for context
    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');

    return {
      toolName: 'Gemini Tool',
      command: command.slice(0, 2000),
      warning: '',
      fullContext: fullContext.slice(0, 2000),
      hasAllowAll: true, // "always" option is always present
      providerId: 'gemini',
    };
  },

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

  approveAllKeystroke(_ctx) {
    return 'always';
  },

  requiresEnter: true,
};
