import type { VoiceCommand, VoiceParseResult } from "./types"

const FILLERS = /\b(please|can you|could you|would you|hey|okay|ok|just|now)\b/gi

const COMMANDS: Array<{ command: VoiceCommand; patterns: RegExp[] }> = [
  { command: "send", patterns: [/^send$/, /^submit$/, /^go$/, /^send (it|that|message|prompt)$/] },
  { command: "run", patterns: [/^run$/, /^execute$/, /^run (it|that|command)$/] },
  { command: "accept", patterns: [/^accept$/, /^approve$/, /^yes$/, /^accept (it|that|changes)$/] },
  { command: "reject", patterns: [/^reject$/, /^deny$/, /^no$/, /^reject (it|that|changes)$/] },
  { command: "clear", patterns: [/^clear$/, /^reset$/, /^erase$/, /^clear (prompt|input|text)$/] },
  { command: "stop", patterns: [/^stop$/, /^cancel$/, /^abort$/, /^stop (it|that|generation)$/] },
  { command: "scroll-up", patterns: [/^scroll up$/, /^page up$/] },
  { command: "scroll-down", patterns: [/^scroll down$/, /^page down$/] },
  { command: "focus", patterns: [/^focus$/, /^focus (prompt|input)$/] },
  { command: "newline", patterns: [/^new line$/, /^newline$/, /^line break$/] },
]

/**
 * Detects short voice-control utterances. Longer phrases are treated as dictation text.
 */
export function parseVoiceInput(raw: string, enabled = true): VoiceParseResult {
  const trimmed = raw.trim()
  if (!trimmed) return { type: "text", text: "" }
  if (!enabled) return { type: "text", text: trimmed }

  const normalized = trimmed
    .toLowerCase()
    .replace(FILLERS, " ")
    .replace(/[^\w\s-]/g, " ")
    .replace(/\s+/g, " ")
    .trim()

  // Only treat short phrases as commands to avoid false positives in dictation
  if (normalized.split(" ").length > 4) return { type: "text", text: trimmed }

  for (const entry of COMMANDS) {
    if (entry.patterns.some((pattern) => pattern.test(normalized))) {
      return { type: "command", command: entry.command, raw: trimmed }
    }
  }

  return { type: "text", text: trimmed }
}
