/**
 * Recipe System — Public API
 *
 * Provides the main entry points for the recipe system:
 *   - loadAllRecipes(): discover all available recipes
 *   - loadRecipeById(id): load a specific recipe
 *   - formatRecipeList(): formatted list for display
 */

export { loadAllRecipes, loadRecipeById } from './recipeLoader.js'
export type {
  Recipe,
  RecipeFrontmatter,
  RecipeStep,
  RecipeExecutionState,
  StepResult,
} from './types.js'

import { loadAllRecipes } from './recipeLoader.js'
import type { Recipe } from './types.js'

/**
 * Format the list of available recipes for terminal display.
 */
export async function formatRecipeList(): Promise<string> {
  const recipes = await loadAllRecipes()

  if (recipes.length === 0) {
    return [
      'No recipes found.',
      '',
      'Add recipes to:',
      '  ~/.sandcode/recipes/     (user-level)',
      '  .sandcode/recipes/       (project-level)',
    ].join('\n')
  }

  const lines: string[] = ['Available recipes:', '']

  // Group by source
  const grouped = groupBySource(recipes)

  for (const [source, sourceRecipes] of Object.entries(grouped)) {
    if (sourceRecipes.length === 0) continue
    const label =
      source === 'bundled'
        ? 'Built-in'
        : source === 'user'
          ? 'User'
          : 'Project'
    lines.push(`  ${label}:`)
    for (const recipe of sourceRecipes) {
      const tags = recipe.metadata.tags?.length
        ? ` [${recipe.metadata.tags.join(', ')}]`
        : ''
      const estimate = recipe.metadata.estimate
        ? ` (~${recipe.metadata.estimate})`
        : ''
      lines.push(
        `    ${recipe.id} — ${recipe.metadata.description}${tags}${estimate}`,
      )
    }
    lines.push('')
  }

  lines.push('Run a recipe: sandcode recipe run <name>')

  return lines.join('\n')
}

function groupBySource(
  recipes: Recipe[],
): Record<string, Recipe[]> {
  const groups: Record<string, Recipe[]> = {
    bundled: [],
    user: [],
    project: [],
  }
  for (const recipe of recipes) {
    groups[recipe.source]!.push(recipe)
  }
  return groups
}
