'use strict';
// Kimi (Moonshot AI) coder CLI approval prompt provider.
// Kimi uses either a numbered-option widget or an inline [Y/n]. We support
// both: the numbered widget looks for "1. Yes" near a "Do you want to"
// prompt; inline falls back to the simple [Y/n] regex.

const YES_RE = /^\s*1\.\s*Yes\b/i;
const PROMPT_RE = /Do you want to .+\?|Kimi\b.*(wants to|needs to)|Allow Kimi/i;
const INLINE_RE = /\[[Yy]\s*\/\s*[Nn]\s*\]/;

module.exports = {
  id: 'kimi',
  name: 'Kimi Coder',

  detect(text) {
    const lines = text.split('\n').filter(l => l.trim());
    if (lines.length < 1) return false;
    const tail = lines.slice(-10);
    if (tail.some(l => PROMPT_RE.test(l)) && tail.some(l => YES_RE.test(l))) return true;
    return tail.some(l => INLINE_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 (PROMPT_RE.test(lines[i]) || INLINE_RE.test(lines[i])) { promptIdx = i; break; }
    }
    if (promptIdx < 0) return null;

    const hasYesWidget = lines.slice(promptIdx + 1, promptIdx + 6).some(l => YES_RE.test(l));

    const ctxStart = Math.max(0, promptIdx - 10);
    const command = lines.slice(ctxStart, promptIdx).join('\n').slice(0, 2000);
    const fullContext = lines.slice(ctxStart, promptIdx + (hasYesWidget ? 5 : 1)).join('\n').slice(0, 2000);

    return {
      toolName: 'Kimi Tool',
      command,
      warning: '',
      fullContext,
      hasAllowAll: false,
      providerId: 'kimi',
      _hasYesWidget: hasYesWidget,
    };
  },

  approveKeystroke(ctx) {
    return ctx && ctx._hasYesWidget ? '1' : 'y';
  },

  approveAllKeystroke() {
    return null;
  },

  requiresEnter: true,
};
