/**
 * Prompt recipe loader：從 RECIPES KV 抓 prompt_recipe 定義並驗證
 * SDD: matrix/arcrun/.agents/specs/recipe-system/design.md Phase 1.3
 *
 * KV key 格式：prompt_recipe:{name}
 * KV value：JSON 字串（不用 YAML，避免引入 yaml parser 進 worker）
 */

import { PromptRecipeSchema, type PromptRecipe } from './prompt-recipe-schema';

type KvBinding = { get: (key: string) => Promise<string | null> };

export class RecipeLoadError extends Error {
  constructor(message: string, public readonly recipe: string) {
    super(message);
  }
}

/** 從 RECIPES KV 抓 + parse + validate */
export async function loadPromptRecipe(
  recipeRef: string, // 完整 key 如 "prompt_recipe:wiki_synthesis"，或裸名 "wiki_synthesis"
  recipesKv: KvBinding,
): Promise<PromptRecipe> {
  const key = recipeRef.startsWith('prompt_recipe:')
    ? recipeRef
    : `prompt_recipe:${recipeRef}`;

  const raw = await recipesKv.get(key);
  if (!raw) {
    throw new RecipeLoadError(`找不到 recipe: ${key}`, key);
  }

  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch (e) {
    throw new RecipeLoadError(
      `recipe ${key} 不是合法 JSON: ${e instanceof Error ? e.message : String(e)}`,
      key,
    );
  }

  const result = PromptRecipeSchema.safeParse(parsed);
  if (!result.success) {
    const issues = result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');
    throw new RecipeLoadError(`recipe ${key} schema 驗證失敗: ${issues}`, key);
  }

  return result.data;
}
