'use strict';

// Codex MCP permission form:
//
//   Calling wall-e.walle_memory_status({})
//   Field 1/1 ...
//   Allow the wall-e MCP server to run tool "walle_memory_status"?
//   1. Allow
//   2. Allow for this session
//   3. Always allow
//   4. Cancel
//   enter to submit | esc to cancel

const CALLING_RE = /\bCalling\s+([A-Za-z0-9_.-]+)\.([A-Za-z0-9_.-]+)\s*\(/i;
const QUESTION_RE = /Allow the ([A-Za-z0-9_.-]+) MCP server to run tool ["']?([A-Za-z0-9_.-]+)["']?\?/i;
const ANCHOR_RE = /enter to submit\s*\|\s*esc to cancel/i;
const ALLOW_RE = /^\s*[❯›> ]?\s*1\.\s*Allow\b/i;
const OPTION_RE = /^\s*[❯›> ]?\s*(\d+)\.\s*(Allow for this session|Always allow|Allow|Cancel)\b/i;

function extractMcpTool(lines) {
  for (let i = lines.length - 1; i >= 0; i--) {
    const q = lines[i].match(QUESTION_RE);
    if (q) return { server: q[1], tool: q[2], questionIdx: i };
  }
  for (let i = lines.length - 1; i >= 0; i--) {
    const c = lines[i].match(CALLING_RE);
    if (c) return { server: c[1], tool: c[2], questionIdx: -1 };
  }
  return null;
}

function parseOptions(lines) {
  const out = {
    allowShortcut: '1',
    sessionShortcut: null,
    alwaysShortcut: null,
  };

  for (const line of lines) {
    const match = line.match(OPTION_RE);
    if (!match) continue;
    const index = match[1];
    const label = match[2].toLowerCase();
    if (label === 'allow for this session') out.sessionShortcut = index;
    else if (label === 'always allow') out.alwaysShortcut = index;
    else if (label === 'allow') out.allowShortcut = index;
  }
  return out;
}

module.exports = {
  id: 'codex-mcp',
  name: 'Codex MCP Permission',

  detect(text) {
    const lines = String(text || '').split('\n').map(l => l.trim()).filter(Boolean);
    if (lines.length < 5) return false;
    if (!lines.slice(-5).some(l => ANCHOR_RE.test(l))) return false;
    if (!lines.some(l => ALLOW_RE.test(l))) return false;
    return lines.some(l => QUESTION_RE.test(l)) || lines.some(l => CALLING_RE.test(l));
  },

  parse(text) {
    const lines = String(text || '').split('\n').map(l => l.trim()).filter(Boolean);
    const mcp = extractMcpTool(lines);
    if (!mcp) return null;

    let allowIdx = -1;
    for (let i = 0; i < lines.length; i++) {
      if (ALLOW_RE.test(lines[i])) { allowIdx = i; break; }
    }
    if (allowIdx < 0) return null;

    const options = parseOptions(lines.slice(allowIdx, allowIdx + 8));
    const ctxAnchor = mcp.questionIdx >= 0 ? mcp.questionIdx : allowIdx;
    const ctxStart = Math.max(0, ctxAnchor - 5);
    const ctxEnd = Math.min(lines.length, allowIdx + 8);
    const command = `${mcp.server}.${mcp.tool}({})`;

    return {
      toolName: 'MCP',
      command: command.slice(0, 2000),
      warning: '',
      fullContext: lines.slice(ctxStart, ctxEnd).join('\n').slice(0, 2000),
      hasAllowAll: !!options.sessionShortcut,
      approveShortcut: options.allowShortcut,
      approveAllShortcut: options.sessionShortcut,
      alwaysAllowShortcut: options.alwaysShortcut,
      mcpServer: mcp.server,
      mcpTool: mcp.tool,
      providerId: 'codex-mcp',
    };
  },

  approveKeystroke(ctx) {
    return ctx.approveAllShortcut || ctx.approveShortcut || '1';
  },

  approveAllKeystroke(ctx) {
    return ctx.approveAllShortcut || null;
  },

  requiresEnter: true,
};
