'use strict';
// OpenCode (opencode.ai) approval prompt provider.
// OpenCode uses a numbered widget with "1. Approve" / "2. Deny" and shows
// context above. We require both the prompt text and the "1. Approve"
// marker near the bottom to avoid false positives.

const APPROVE_RE = /^\s*1\.\s*Approve\b/i;
const PROMPT_RE = /Tool call:|Execute:|Apply changes\?|OpenCode wants/i;
const ALLOW_ALL_RE = /2\.\s*(Approve,?\s*(always|all)|Always approve)/i;

module.exports = {
  id: 'opencode',
  name: 'OpenCode',

  detect(text) {
    const lines = text.split('\n').filter(l => l.trim());
    if (lines.length < 2) return false;
    const tail = lines.slice(-10);
    return tail.some(l => APPROVE_RE.test(l)) && tail.some(l => PROMPT_RE.test(l));
  },

  parse(text) {
    const lines = text.split('\n').map(l => l.trim()).filter(Boolean);
    let approveIdx = -1;
    for (let i = lines.length - 1; i >= 0; i--) {
      if (APPROVE_RE.test(lines[i])) { approveIdx = i; break; }
    }
    if (approveIdx < 0) return null;

    // Find the prompt that triggered this widget (within 10 lines above).
    let promptIdx = -1;
    for (let i = approveIdx - 1; i >= Math.max(0, approveIdx - 10); i--) {
      if (PROMPT_RE.test(lines[i])) { promptIdx = i; break; }
    }
    if (promptIdx < 0) promptIdx = Math.max(0, approveIdx - 3);

    const hasAllowAll = lines.slice(approveIdx, approveIdx + 4).some(l => ALLOW_ALL_RE.test(l));
    const ctxStart = Math.max(0, promptIdx - 5);
    const command = lines.slice(ctxStart, approveIdx).join('\n').slice(0, 2000);
    const fullContext = lines.slice(ctxStart, approveIdx + 3).join('\n').slice(0, 2000);

    return {
      toolName: 'OpenCode Tool',
      command,
      warning: '',
      fullContext,
      hasAllowAll,
      providerId: 'opencode',
    };
  },

  approveKeystroke(ctx) {
    return ctx.hasAllowAll ? '2' : '1';
  },

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

  requiresEnter: true,
};
