const PAN = 'croptopia:frying_pan'
const COOKING_PAN = 'croptopia:cooking_pan'



function getIngredients(json) {
    // shapeless
    if (json.ingredients) {
        return json.ingredients
    }

    // shaped
    if (json.pattern && json.key) {
        const list = []

        for (const row of json.pattern) {
            for (const symbol of row.split("")) {
                if (symbol === " ") continue
                let ing = json.key[symbol]
                if (ing) list.push(ing)
            }
        }
        return list
    }

    // smelting / campfire
    if (json.ingredient) {
        return [json.ingredient]
    }

    return [];
}



ServerEvents.recipes(event => {
    event.forEachRecipe({ mod: 'croptopia' }, recipe => {

        const json = JSON.parse(recipe.json.toString())

        const ingList = getIngredients(json)

        const usesPan = ingList.some(i => i?.item === PAN)
        if (!usesPan) return

        event.remove({ id: recipe.getId() })

        const newIngredients = ingList.filter(i => i?.item !== PAN)

        const resultItem = json.result?.item ?? json.result
        const resultCount = Math.max(1, json.result?.count ?? 1);

        const resultItems = Array.isArray(resultItem)
            ? resultItem.map(r => r.item)
            : [resultItem.item];

        event.custom({
            type: "farmersdelight:cooking",
            ingredients: newIngredients,
            result: { item: resultItem, count: resultCount },
            cookingtime: 200,
            experience: 0.0,
            fluid: {
                fluid: "minecraft:water",
                amount: 250
            }
        }).id(`kubejs:fd_pot/${recipe.getId().replace(':', '_')}`)
    })

    event.remove({ output: PAN })
    event.remove({ output: COOKING_PAN })
})
