function getPotMixingIngredients(json) {
    if (!json.ingredients) return []
    return json.ingredients
}

function getPotMixingResult(json) {
    if (!json.result) return null
    if (typeof json.result === 'string') return { item: json.result, count: 1 }

    const item = json.result.item ?? json.result.id
    if (!item) return null

    return {
        item: item,
        count: Math.max(1, json.result.count ?? 1)
    }
}

function getPotMixingContainer(json) {
    if (json.containerId) return { item: json.containerId }
    if (!json.container) return null
    if (typeof json.container === 'string') return { item: json.container }

    const item = json.container.item ?? json.container.id ?? json.container.containerId
    if (!item) return null

    return { item: item }
}

function addPotMixingContainerIngredient(ingredients, container) {
    if (!container) return ingredients

    const item = container.item ?? container.id ?? container.containerId
    if (!item) return ingredients

    return ingredients.concat([{ item: item }])
}

function getPotMixingRecipeId(recipeId) {
    return `kubejs:mixing/farmersdelight_pot/${recipeId.replace(':', '/')}`
}

ServerEvents.recipes(event => {
    event.forEachRecipe({}, recipe => {
        const recipeId = recipe.getId().toString()
        if (recipeId.startsWith('kubejs:fd_pot/')) return

        const json = JSON.parse(recipe.json.toString())
        if (json.type !== 'farmersdelight:cooking') return

        const ingredients = getPotMixingIngredients(json)
        const container = getPotMixingContainer(json)
        const result = getPotMixingResult(json)

        if (!result) return
        if (ingredients.length === 0) return

        const mixingIngredients = addPotMixingContainerIngredient(ingredients, container)

        event.custom({
            type: 'create:mixing',
            heatRequirement: 'heated',
            ingredients: mixingIngredients,
            results: [
                result
            ],
            processingTime: json.cookingtime ?? 200
        }).id(getPotMixingRecipeId(recipeId))
    })
})
