import { COAUTHOR_ACTIONS, isCoauthorAction, type CoauthorAction } from './coauthor-client.js'

/**
 * Cmd+K slash-command parsing for the AI co-author.
 *
 * Recognized syntax (case-insensitive, leading whitespace tolerated):
 *
 *     /ai <action> [text...]
 *
 * `<action>` is one of `COAUTHOR_ACTIONS`. `text` is the payload handed to
 * `/ai/coauthor`; it may be empty while the user is still typing.
 *
 * The parser is pure so we can unit-test every edge case (case folding,
 * trailing whitespace, partial input, unknown actions) without spinning up
 * `cmdk` or the rest of the palette.
 */

export interface AiSlashCommand {
  action: CoauthorAction
  text: string
}

const SLASH_HEAD = /^\s*\/\s*ai(?:\s+|$)/i

/**
 * Returns the matched `{ action, text }` when `input` is a complete
 * slash command (`/ai rewrite ...`), or `null` otherwise. `text` may be
 * empty when the user has typed `/ai rewrite` with no payload yet.
 */
export function parseAiSlashCommand(input: string): AiSlashCommand | null {
  if (typeof input !== 'string') return null
  if (!SLASH_HEAD.test(input)) return null
  const after = input.replace(SLASH_HEAD, '')
  if (after.length === 0) return null

  const firstWhitespace = after.search(/\s/)
  const head = (firstWhitespace === -1 ? after : after.slice(0, firstWhitespace)).toLowerCase()
  if (!isCoauthorAction(head)) return null

  const tail = firstWhitespace === -1 ? '' : after.slice(firstWhitespace + 1)
  return { action: head, text: tail.trim() }
}

/**
 * Returns true when `input` looks like the start of an AI slash command
 * — even when the action isn't typed yet (`/`, `/a`, `/ai`, `/ai re`).
 * The palette uses this to switch into "AI mode" (hide nav results,
 * show the four action suggestions).
 */
export function isAiSlashCommandInput(input: string): boolean {
  if (typeof input !== 'string') return false
  const trimmed = input.trim()
  if (trimmed.length === 0) return false
  if (trimmed === '/') return true
  return /^\/\s*a(i\b|i?[a-z]*|)?(\s.*)?$/i.test(trimmed)
}

/**
 * Ordered list of actions to show in AI mode. When the user has typed a
 * valid command, that command's action is hoisted to the top so it gets
 * the default keyboard focus (and Enter runs it).
 */
export function orderedAiActions(input: string): CoauthorAction[] {
  const parsed = parseAiSlashCommand(input)
  if (!parsed) return [...COAUTHOR_ACTIONS]
  return [parsed.action, ...COAUTHOR_ACTIONS.filter((a) => a !== parsed.action)]
}
