import { generateObject } from "ai";
import { z } from "zod";
import { resolveModel, type AiConfig } from "../factory";

const DietaryOutputSchema = z.object({
  vegan: z.boolean(),
  vegetarian: z.boolean(),
  glutenFree: z.boolean(),
  dairyFree: z.boolean(),
  nutFree: z.boolean(),
  halal: z.boolean(),
  kosher: z.boolean(),
  reasoning: z.record(z.string(), z.string()).optional(),
});

export type InferredDietaryTags = Omit<z.infer<typeof DietaryOutputSchema>, "reasoning">;

export async function inferDietaryTags(
  ingredients: Array<{ rawName: string; unit?: string | null }>,
  config?: AiConfig
): Promise<InferredDietaryTags> {
  const model = resolveModel(config);

  const ingredientList = ingredients.map((i) => i.rawName).join(", ");

  const { object } = await generateObject({
    model,
    schema: DietaryOutputSchema,
    system:
      "You are a dietary classification expert. Analyze recipe ingredients and determine dietary tags accurately. Be conservative — only mark something as true if you are confident based on the ingredients listed.",
    prompt: `Classify these ingredients for dietary tags: ${ingredientList}`,
  });

  const { reasoning: _reasoning, ...tags } = object;
  return tags;
}
