import type { FluidProductPrototype, ItemProductPrototype, RecipePrototype } from "../factorio-dump.models.ts";
import type { Item } from "../factorio-process-data.models.ts";

export type Ingredient = {
  type: "fluid" | "item";
  itemId: string;
  amount: number;
};

export type Recipe = {
  name: string;
  icon?: string;
  subgroup: string;
  order?: string;
  category?: string;
  additional_categories?: string[];
  allow_productivity?: boolean;
  allow_quality?: boolean;
  allow_speed?: boolean;
  ingredients?: Ingredient[];
  results?: Array<ItemProductPrototype | FluidProductPrototype>;
};

export function getRecipeIcon(recipe: RecipePrototype, mainProduct: Item | undefined): string {
  if (recipe.icons || recipe.icon) return `recipe/${recipe.name}.png`;
  if (mainProduct && mainProduct.icon) return mainProduct.icon;
  console.warn(`No icon found for :${recipe.name}`);
  return "";
}
export function getRecipeSubGroup(recipe: RecipePrototype, mainProduct: Item | undefined): string {
  if (recipe.subgroup) return recipe.subgroup;
  if (mainProduct) return mainProduct.subgroup;

  return "other";
}
export function getMainProductName(recipe: RecipePrototype): string {
  if (recipe.results?.length == 1) {
    return recipe.results[0].name;
  } else if (recipe.results && recipe.main_product) {
    const mainProduct = recipe.main_product;
    const result = recipe.results.find((r) => r.name === mainProduct);
    if (result) {
      return result.name;
    }
    throw new Error(`Main product '${mainProduct}' declared by recipe '${recipe.name}' not found in results`);
  }
  return "";
}

export function parseRecipe(recipe: RecipePrototype, itemsMap: Record<string, Item>): Recipe {
  const rawIngredient = Array.isArray(recipe.ingredients) ? recipe.ingredients : [];
  const ingredients = rawIngredient.map((i) => ({ itemId: i.name, amount: i.amount, type: i.type }));
  const mainProduct = itemsMap[getMainProductName(recipe)];
  const r: Recipe = {
    name: recipe.name,
    icon: getRecipeIcon(recipe, mainProduct),
    subgroup: getRecipeSubGroup(recipe, mainProduct),
    order: recipe.order,
    category: recipe.category,
    additional_categories: recipe.additional_categories,
    ingredients,
    results: recipe.results,
  };
  if (recipe.category) r.category = recipe.category;
  if (recipe.additional_categories) r.additional_categories = recipe.additional_categories;
  if (recipe.allow_productivity) r.allow_productivity = true;
  if (recipe.allow_quality) r.allow_quality = true;
  if (recipe.allow_speed) r.allow_speed = true;
  return r;
}
