'use strict';

// Amazon Q CLI approval prompt provider (stub).
// Amazon Q uses inline [y/n/t] prompts where t = trust (allow all).

const APPROVE_RE = /\bAllow this action\?\s*\[y\/n\/t\]/i;

module.exports = {
  id: 'amazon-q',
  name: 'Amazon Q',

  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');

    return {
      toolName: 'Amazon Q Tool',
      command: command.slice(0, 2000),
      warning: '',
      fullContext: fullContext.slice(0, 2000),
      hasAllowAll: true,
      providerId: 'amazon-q',
    };
  },

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

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

  requiresEnter: true,
};
