import { generateObject } from "ai";
import { z } from "zod";
import { resolveModel, type AiConfig } from "../factory";
import { dietaryTagsSchema, ingredientSchema, stepSchema } from "./recipe-schema";

const AdaptedRecipeSchema = z.object({
  title: z.string(),
  description: z.string(),
  baseServings: z.number().int().min(1).max(100),
  prepMins: z.number().int().min(0).optional(),
  cookMins: z.number().int().min(0).optional(),
  difficulty: z.enum(["easy", "medium", "hard"]),
  dietaryTags: dietaryTagsSchema,
  ingredients: z.array(ingredientSchema(z.number())),
  steps: z.array(stepSchema),
  adaptationNotes: z.string(),
});

export type AdaptedRecipe = z.infer<typeof AdaptedRecipeSchema>;

const LANG: Record<string, string> = { en: "English", fr: "French" };

export async function adaptRecipe(
  recipe: {
    title: string;
    description?: string | null;
    baseServings: number;
    ingredients: Array<{ rawName: string; quantity?: string | number | null; unit?: string | null }>;
    steps: Array<{ instruction: string }>;
  },
  constraints: {
    excludeIngredients: string[];
    extraConstraints?: string;
  },
  config?: AiConfig & { userContext?: string },
  locale?: string
): Promise<AdaptedRecipe> {
  const model = resolveModel(config);
  const lang = LANG[locale ?? "en"] ?? "English";

  const recipeText = [
    `Title: ${recipe.title}`,
    recipe.description ? `Description: ${recipe.description}` : "",
    `Servings: ${recipe.baseServings}`,
    `Ingredients:\n${recipe.ingredients.map((i) => `  - ${i.quantity ? `${i.quantity} ` : ""}${i.unit ? `${i.unit} ` : ""}${i.rawName}`).join("\n")}`,
    `Steps:\n${recipe.steps.map((s, i) => `  ${i + 1}. ${s.instruction}`).join("\n")}`,
  ].filter(Boolean).join("\n");

  const constraintText = [
    constraints.excludeIngredients.length > 0
      ? `MUST NOT contain or use: ${constraints.excludeIngredients.join(", ")}. Find suitable substitutes that preserve the dish character.`
      : "",
    constraints.extraConstraints?.trim()
      ? `Additional constraints: ${constraints.extraConstraints}`
      : "",
  ].filter(Boolean).join("\n");

  const { object } = await generateObject({
    model,
    schema: AdaptedRecipeSchema,
    system:
      `You are a professional chef specializing in recipe adaptation. When adapting recipes, find the best substitutes that preserve the spirit, flavor profile, and texture of the original. Always explain what changed and why in adaptationNotes. For ingredient quantities: use numbers only, units separately. Respond in ${lang}.${config?.userContext ? `\n\nUser preferences and context:\n${config.userContext}` : ""}`,
    prompt: `Adapt the following recipe with these constraints:\n\n${constraintText}\n\nOriginal recipe:\n${recipeText}`,
  });

  return object;
}
