/**
 * Recipe CLI Command Handlers
 *
 * Handles `sandcode recipe list` and `sandcode recipe run <name>`.
 */

import chalk from 'chalk'
import { loadAllRecipes, loadRecipeById, formatRecipeList } from '../../recipes/index.js'
import type { Recipe } from '../../recipes/types.js'

/**
 * List all available recipes.
 */
export async function recipeListHandler(options: { json?: boolean }): Promise<void> {
  if (options.json) {
    const recipes = await loadAllRecipes()
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(JSON.stringify(recipes.map(r => ({
      id: r.id,
      name: r.metadata.name,
      description: r.metadata.description,
      tags: r.metadata.tags,
      steps: r.metadata.steps.length,
      source: r.source,
      estimate: r.metadata.estimate,
    })), null, 2))
    return
  }

  const formatted = await formatRecipeList()
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(formatted)
}

/**
 * Show details of a specific recipe.
 */
export async function recipeShowHandler(id: string): Promise<void> {
  const recipe = await loadRecipeById(id)
  if (!recipe) {
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.error(chalk.red(`Recipe "${id}" not found.`))
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.error('Run `sandcode recipe list` to see available recipes.')
    process.exitCode = 1
    return
  }

  printRecipeDetails(recipe)
}

/**
 * Run a recipe by ID.
 * Outputs each step as a prompt the user can execute in the REPL.
 */
export async function recipeRunHandler(
  id: string,
  options: { dry?: boolean },
): Promise<void> {
  const recipe = await loadRecipeById(id)
  if (!recipe) {
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.error(chalk.red(`Recipe "${id}" not found.`))
    process.exitCode = 1
    return
  }

  if (options.dry) {
    printRecipeDetails(recipe)
    return
  }

  // Output the recipe as a multi-step prompt
  const steps = recipe.metadata.steps
  const prompts: string[] = []

  for (let i = 0; i < steps.length; i++) {
    const step = steps[i]!
    const label = step.name ?? `Step ${i + 1}`
    prompts.push(`## ${label}\n${step.prompt}`)
  }

  // Combine all steps into a single comprehensive prompt
  const fullPrompt = [
    `# Recipe: ${recipe.metadata.name}`,
    '',
    recipe.metadata.description,
    '',
    ...prompts,
  ].join('\n')

  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(fullPrompt)
}

function printRecipeDetails(recipe: Recipe): void {
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(chalk.bold(`\n${recipe.metadata.name}`))
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(chalk.dim(recipe.metadata.description))
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log('')

  if (recipe.metadata.tags?.length) {
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(chalk.dim(`Tags: ${recipe.metadata.tags.join(', ')}`))
  }
  if (recipe.metadata.estimate) {
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(chalk.dim(`Estimated time: ${recipe.metadata.estimate}`))
  }
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(chalk.dim(`Source: ${recipe.source} (${recipe.sourcePath})`))
  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log('')

  // biome-ignore lint/suspicious/noConsole:: intentional output
  console.log(chalk.bold('Steps:'))
  for (let i = 0; i < recipe.metadata.steps.length; i++) {
    const step = recipe.metadata.steps[i]!
    const label = step.name ?? `Step ${i + 1}`
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(`  ${chalk.hex('#F5A623')(`${i + 1}.`)} ${label}`)
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(chalk.dim(`     ${step.prompt.slice(0, 80)}${step.prompt.length > 80 ? '...' : ''}`))
  }

  if (recipe.body) {
    // biome-ignore lint/suspicious/noConsole:: intentional output
    console.log(`\n${recipe.body}`)
  }
}
