// Visit the wiki for more info - https://kubejs.com/
console.info('Hello, World! (Loaded server example script)')
console.log("Server script LOADED");

const metalTier = global.metalTier;
const hammerByTier = global.hammerByTier;
const tongsByTier = global.tongsByTier;
const tfcMetals = global.tfcMetals;

const toolMetals = [
    "copper",
    "bronze",
    "bismuth_bronze",
    "black_bronze",
    "wrought_iron",
    "steel",
    "black_steel",
    "blue_steel",
    "red_steel"
];

const toolItemByType = {
    hammer: (metal) => `tfc:metal/hammer/${metal}`,
    chisel: (metal) => `tfc:metal/chisel/${metal}`,
    tongs:  (metal) => `tfc:metal/hoe/${metal}`
};


const blankMap = {
    "knife_blade": "kubejs:blank_knife_blade",
    "pickaxe_head": "kubejs:blank_pickaxe_head",
    "chisel_head": "kubejs:blank_chisel_head",
    "saw_blade": "kubejs:blank_saw_blade",
    "axe_head": "kubejs:blank_axe_head",
    "hoe_head": "kubejs:blank_hoe_head",
    "sword_blade": "kubejs:blank_sword_blade",
    "scythe_blade": "kubejs:blank_scythe_blade"
};

//All TFC Wood types as a constant
const tfc_woodtypes = [
    "acacia",
    "ash",
    "aspen",
    "birch",
    "blackwood",
    "chestnut",
    "douglas_fir",
    "hickory",
    "kapok",
    "maple",
    "oak",
    "palm",
    "pine",
    "rosewood",
    "sequoia",
    "spruce",
    "sycamore",
    "white_cedar",
    "willow"
];
//all Arborfirmacraft trees as a constant
const afc_woodtypes = [
    "baobab",
    "hevea",
    "cypress",
    "ipe",
    "ginkgo",
    "eucalyptus",
    "tualang",
    "fig",
    "araucaria",
    "mahoe",
    "mahogany",
    "teak",
    "ironwood",
    "beech"
];
//========
//General Fixes
//========
ServerEvents.recipes(event => {
    //Remove Broken/incompatable/superfulious recipes
    event.remove([{id: 'tfcambiental:sewing/wool_hat'},
        {id: 'tfcambiental:sewing/wool_pants'},
        {id: 'tfcambiental:sewing/wool_sweater'},
        {id: 'tfcambiental:sewing/wool_boots'},
        {id: 'firmasupps:crafting/functional/sconce_haunting'},
        {id: 'firmasupps:sewing/dragon_banner_pattern'},
        {id: 'firmasupps:cutting/lapis_bricks'},
        {id: 'firmasupps:cutting/ash_bricks'},
        {id: 'farmersdelight:pie_crust_with_pie_dough'},
        {id: 'tfc_textile_legacy:clothing/crocodile/crocodile_shirt'},
        {id: "create:crafting/materials/andesite_alloy"},
        {id: "create:crafting/materials/andesite_alloy_from_zinc"},
        {id: "tfcambiental:sewing/burlap_shirt"},
        {id: "tfcambiental:sewing/burlap_cowl"},
        {id: "tfcambiental:sewing/burlap_pants"},
        {id: "tfcambiental:sewing/burlap_shoes"},
        {id: 'create:crafting/materials/copper_ingot'},
        {id: 'minecraft:gold_ingot_from_nuggets'},
        {id: 'minecraft:iron_ingot_from_nuggets'},
        {id: 'create:crafting/materials/zinc_ingot_from_compacting'},
        {id: 'create:crafting/materials/brass_ingot_from_compacting'},
        {id: 'create:crafting/materials/brass_block_from_compacting'},
        {id: 'create:crafting/materials/brass_ingot_from_decompacting'},
        {id: 'create:crafting/materials/zinc_ingot_from_decompacting'},
        {id: 'minecraft:copper_ingot_from_waxed_copper_block'},
        {id: 'minecraft:gold_ingot_from_gold_block'},
        {id: 'create:crafting/materials/zinc_block_from_compacting'},
        {id: 'minecraft:iron_bars'},
        {id: 'minecraft:gold_bars'},
        {id: 'supplementaries:gold_bars'},
        {id: 'minecraft:copper_block'},
        {id: 'minecraft:gold_block'},
        {id: 'minecraft:iron_block'},
        {id: 'minecraft:copper_ingot'},
        {id: 'supplementaries:gold_gate'},
        {id: 'minecraft:white_wool_from_string'},
        {id: 'create:crushing/wool'},
        {id: 'firmasupps:crafting/soap/clean_tfc_bricks_alabaster'},
        {id: 'firmasupps:crafting/soap/clean_tfc_candle'},
        {id: 'createlowheated:basic_burner'},
        {id: 'create:sequenced_assembly/track'},
        //{id: 'tfchotornot:heating/insulating_items'},
        {id: 'afc:pot/rubber'},
        {id: 'create:crafting/appliances/chain_from_zinc'},
        {id: 'minecraft:chain'},
        {id: 'minecraft:copper_trapdoor'},
        {id: 'farmersdelight:integration/create/filling/chocolate_pie'},
        {id: 'minecraft:blast_furnace'},
        {id: 'aeronautics:mechanical_crafting/mounted_potato_cannon'},
        {id: 'simulated:mechanical_crafting/docking_connector'},
        {id: 'simulated:sequenced_assembly/engine_assembly'},
        {id: 'simulated:sequenced_assembly/gyroscopic_mechanism'},
        {id: 'simulated:mechanical_crafting/linked_typewriter'},
        {id: 'create_jetpack:jetpack'},
        {id: 'simulated:filled/honey_glue'}
    ]);
    //TFC anvil recipe to make Createlowheated:basic_burner
    event.custom({
        type: "tfc:welding",
        first_input: {
            item: "tfc:metal/double_sheet/cast_iron"
        },
        second_input: {
            item: "tfc:metal/double_sheet/cast_iron"
        },
        result: {
            id: "createlowheated:basic_burner",
            count: 1
        },
        tier: 2 // optional: cast iron is tier 2 (wrought iron tier)
    }).id("kubejs:tfc_welding/basic_burner");
    // Wrought Iron Track Recipe (8 output)
    event.custom({
        type: "create:sequenced_assembly",
        ingredient: {
            tag: "c:stones/smooth_slabs"
        },
        results: [
            { id: "create:track", count: 8 }
        ],
        transitional_item: { id: "create:incomplete_track" },
        sequence: [
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_track" },
                    { item: "tfc:metal/rod/wrought_iron" }
                ],
                results: [{ id: "create:incomplete_track" }]
            },
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_track" },
                    { item: "tfc:metal/rod/wrought_iron" }
                ],
                results: [{ id: "create:incomplete_track" }]
            },
            {
                type: "create:pressing",
                ingredients: [
                    { item: "create:incomplete_track" }
                ],
                results: [{ id: "create:incomplete_track" }]
            }
        ]
    }).id("kubejs:track_from_wrought_iron");
    // Steel Track Recipe (16 output) 
    event.custom({
        type: "create:sequenced_assembly",
        ingredient: {
            tag: "c:stones/smooth_slabs"
        },
        results: [
            { id: "create:track", count: 16 }
        ],
        transitional_item: { id: "create:incomplete_track" },
        sequence: [
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_track" },
                    { item: "tfc:metal/rod/steel" }
                ],
                results: [{ id: "create:incomplete_track" }]
            },
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_track" },
                    { item: "tfc:metal/rod/steel" }
                ],
                results: [{ id: "create:incomplete_track" }]
            },
            {
                type: "create:pressing",
                ingredients: [
                    { item: "create:incomplete_track" }
                ],
                results: [{ id: "create:incomplete_track" }]
            }
        ]
    }).id("kubejs:track_from_steel");
	event.shaped('16x minecraft:chain', [
		" N ",
		" I ",
        " N "
	], {
		N: 'minecraft:iron_nugget',
		I: 'tfc:metal/ingot/wrought_iron'
	});

    //Adjusts Create Andesite Alloy Recipes to use TFC raw andesite & loose Andesite
    // TODO: add molten Andesite Alloy and Molten Andesite, make a TFC Alloy recipes
    event.shapeless(
        ('create:andesite_alloy'),
        [   'tfc:rock/raw/andesite',
            'create:zinc_nugget'
        ]
    );
    event.shapeless(
        ('create:andesite_alloy'),
        [   '4x tfc:rock/loose/andesite',
            'create:zinc_nugget'
        ] 
    );
    // Replace Vanilla Iron/Gold/Copper with TFC versions
    event.replaceInput({}, 'minecraft:iron_ingot', '#c:ingots/irons')
    event.replaceInput({}, 'minecraft:iron_bars', 'tfc:metal/bars/wrought_iron')
    event.replaceInput({}, 'minecraft:gold_ingot', '#c:ingots/gold')
	event.replaceInput({}, 'minecraft:copper_ingot', '#c:ingots/copper')
    event.replaceInput({}, 'minecraft:copper_block', 'tfc:metal/block/copper')
    event.replaceInput({}, 'minecraft:gold_block', 'tfc:metal/block/gold')
    event.replaceInput({}, 'minecraft:iron_block', 'tfc:metal/block/wrought_iron')
    event.replaceInput({}, 'minecraft:iron_bars', 'tfc:metal/bars/wrought_iron')
    event.replaceOutput({}, 'minecraft:gold_ingot', 'tfc:metal/ingot/gold')
	event.replaceOutput({}, 'minecraft:copper_ingot', 'tfc:metal/ingot/copper')
    //Other Vanilla Changes//
    //Stonecutter uses TFC raw Stone
    event.replaceInput({id:'minecraft:stonecutter'}, 'minecraft:stone', '#c:stones/raw')
    //Create Adjustments
    event.replaceInput({}, 'create:iron_sheet', 'tfc:metal/sheet/wrought_iron')
    event.replaceInput({}, 'create:iron_sheet', 'tfc:metal/sheet/wrought_iron')
    event.replaceInput({}, 'create:golden_sheet', 'tfc:metal/sheet/gold')
    event.replaceInput({}, 'create:golden_sheet', 'tfc:metal/sheet/gold')
    event.replaceInput({}, 'create:copper_sheet', 'tfc:metal/sheet/copper')
    event.replaceInput({}, 'create:copper_sheet', 'tfc:metal/sheet/copper')
    event.replaceInput({}, 'create:brass_sheet', 'tfc:metal/sheet/brass')
    event.replaceInput({}, 'create:brass_sheet', 'tfc:metal/sheet/brass')
    event.replaceInput({}, 'minecraft:slime_ball', '#forge:slimy')
    event.replaceInput({}, 'minecraft:crafting_table', '#tfc:workbenches')
    event.replaceInput({}, 'minecraft:amethyst_shard', '#c:gems/amethyst')
    event.replaceInput({ id: 'create:crafting/appliances/copper_backtank'}, 'tfc:metal/block/copper', 'create:fluid_tank')
    event.replaceInput({ id: 'create:oak_window'}, 'minecraft:oak_planks', 'tfc:wood/planks/oak')
    event.replaceInput({ id: 'create:spruce_window'}, 'minecraft:spruce_planks', 'afc:wood/planks/cypress')
    event.replaceInput({ id: 'create:birch_window'}, 'minecraft:birch_planks', 'afc:wood/planks/eucalyptus')
    event.replaceInput({ id: 'create:jungle_window'}, 'minecraft:jungle_planks', 'afc:wood/planks/teak')
    event.replaceInput({ id: 'create:acacia_window'}, 'minecraft:acacia_planks', 'afc:wood/planks/baobab')
    event.replaceInput({ id: 'create:dark_oak_window'}, 'minecraft:dark_oak_planks', 'tfc:wood/planks/hickory')
    event.replaceInput({ id: 'create:mangrove_window'}, 'minecraft:mangrove_planks', 'tfc:wood/planks/mangrove')
    event.replaceInput({ id: 'create:crimson_window'}, 'minecraft:crimson_planks', 'afc:wood/planks/mahogany')
    event.replaceInput({ id: 'create:warped_window'}, 'minecraft:warped_planks', 'afc:wood/planks/ginkgo')
    event.replaceInput({ id: 'create:cherry_window'}, 'minecraft:cherry_planks', 'afc:wood/planks/fig')
    event.replaceInput({ id: 'create:bamboo_window'}, 'minecraft:bamboo_planks', 'tfc:golden_bamboo_block')
    event.replaceInput({ id: 'create:crafting/logistics/redstone_contact'}, 'minecraft:cobblestone', '#c:cobblestones')
    event.replaceInput({ id: 'create:crafting/logistics/item_hatch'}, 'minecraft:iron_trapdoor', 'tfc:metal/trapdoor/wrought_iron')
    // event.replaceInput({ id: 'create:crafting/kinetics/empty_blaze_burner'}, 'minecraft:netherrack', '#c:magma_block')
    event.replaceInput({ id: 'minecraft:coal_block'}, 'minecraft:coal', 'tfc:ore/bituminous_coal')
    event.replaceOutput({ id: 'minecraft:coal'}, 'minecraft:coal', 'tfc:ore/bituminous_coal')
    event.remove({ id: 'create:crafting/kinetics/empty_blaze_burner'})
   
    // createbigcannons balancing
    event.remove({ id: 'createbigcannons:melting/melt_steel_block'})
    event.remove({ id: 'createbigcannons:melting/melt_bronze_block'})
    event.remove({ id: 'createbigcannons:melting/melt_cast_iron_block'})
    event.replaceInput({}, 'magistuarmory:steel_ingot', 'tfc:metal/ingot/steel')
    event.replaceInput({}, 'createbigcannons:steel_ingot', 'tfc:metal/ingot/steel')
    event.replaceInput({}, 'createbigcannons:cast_iron_ingot', 'tfc:metal/ingot/cast_iron')

    // 1. Remove the default Create Mod Precision Mechanism recipe
    event.remove({ id: 'create:sequenced_assembly/precision_mechanism' })

    // 2. Recreate it with TFC materials using stable event.custom syntax
    event.custom({
        type: "create:sequenced_assembly",
        ingredient: { 
            item: "tfc:metal/sheet/gold"
        },
        transitional_item: { 
            id: "create:incomplete_precision_mechanism" 
        },

        // The Step-by-Step Sequence (Loops 5 times)
        sequence: [
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_precision_mechanism" },
                    { item: "create:cogwheel" }
                ],
                results: [{ id: "create:incomplete_precision_mechanism" }]
            },

            // Step 2 — Deploy Large Cogwheel
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_precision_mechanism" },
                    { item: "create:large_cogwheel" }
                ],
                results: [{ id: "create:incomplete_precision_mechanism" }]
            },

            // Step 3
            {
                type: "create:deploying",
                ingredients: [
                    { item: "create:incomplete_precision_mechanism" },
                    { item: "minecraft:gold_nugget" } 
                ],
                results: [{ id: "create:incomplete_precision_mechanism" }]
            }
        ],

        // Output Pool with TFC Scrap/Failures
        results: [
            // Main Success Output (80% Chance)
            { id: "create:precision_mechanism", count: 1, chance: 0.8 },
            
            // Failure Junk Outputs (Totaling 20% Chance)
            { id: "tfc:metal/sheet/wrought_iron", count: 1, chance: 0.08 },       // 8% chance
            { id: "tfc:metal/ingot/wrought_iron", count: 1, chance: 0.05 },       // 5% chance
            { id: "create:cogwheel", count: 1, chance: 0.05 },                    // 5% chance
            { id: "minecraft:gold_nugget", count: 1, chance: 0.02 }             // 2% chance
        ],

        loops: 5

    }).id("create:sequenced_assembly/precision_mechanism_tfc")

    // Create: Aeronautics recipes changes
    event.remove({ output: 'offroad:small_tire' });
	event.shaped('offroad:small_tire', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'create:shaft',
		B: 'afc:rubber_bar'
	});
    event.remove({ output: 'offroad:tire' });
	event.shaped('offroad:tire', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'offroad:small_tire',
		B: 'afc:rubber_bar'
	});
    event.remove({ output: 'offroad:large_tire' });
	event.shaped('offroad:large_tire', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'offroad:tire',
		B: 'afc:rubber_bar'
	});
    event.remove({ output: 'offroad:monstrous_tire' });
	event.shaped('offroad:monstrous_tire', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'offroad:large_tire',
		B: 'afc:rubber_bar'
	});
    event.remove({ output: 'tracks:small_suspension_track' });
	event.shaped('tracks:small_suspension_track', [
		" B ",
		" A ",
        "   "
	], {
		A: 'create:shaft',
		B: 'afc:rubber_bar'
	});
    event.remove({ output: 'create_submarine:underwater_mine' });
	event.shaped('create_submarine:underwater_mine', [
		"CBC",
		"BAB",
        "CBC"
	], {
		A: 'minecraft:lodestone',
		B: 'createbigcannons:nitropowder',
        C: 'tfc:metal/block/steel'
	});
    event.replaceInput(
    { id: 'simulated:redstone_magnet' },         // Arg 1: the filter
    'create:industrial_iron_block',                    // Arg 2: the item to replace
    Ingredient.of('electroenergetics:magnet')  // Arg 3: the item to replace it with 
    )
    event.remove({ output: 'create:propeller' });
	event.shaped('create:propeller', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'create:andesite_alloy',
		B: 'tfc:metal/sheet/steel'
	});
    event.replaceInput(
    { id: 'aeronautics:propeller_bearing' },         // Arg 1: the filter
    'tfc:metal/sheet/wrought_iron',                    // Arg 2: the item to replace
    Ingredient.of('create:propeller')  // Arg 3: the item to replace it with 
    )
    event.remove({ output: 'create:steam_engine' });
	event.shaped('create:steam_engine', [
		" A ",
		" B ",
        "DCD"
	], {
		A: 'tfc_items:steel_ring',
		B: 'tfc:metal/rod/steel',
        C: 'tfc:metal/double_sheet/steel',
        D: 'tfc:metal/sheet/copper'
	});
    event.replaceInput(
    { id: 'simulated:red_portable_engine' },         // Arg 1: the filter
    'minecraft:blast_furnace',                    // Arg 2: the item to replace
    Ingredient.of('createdieselgenerators:burner')  // Arg 3: the item to replace it with 
    )
    event.replaceInput(
    { id: 'offroad:rockcutting_wheel' },         // Arg 1: the filter
    'tfc:metal/sheet/wrought_iron',                    // Arg 2: the item to replace
    Ingredient.of('tfc:metal/double_sheet/steel')  // Arg 3: the item to replace it with 
    )
    event.replaceInput(
    { id: 'create:mechanical_crafting/crushing_wheel' },         // Arg 1: the filter
    'create:andesite_alloy',                    // Arg 2: the item to replace
    Ingredient.of('tfc:metal/sheet/steel')  // Arg 3: the item to replace it with 
    )
    
    // WoodenCog
    event.replaceInput({ id: 'woodencog:crafting/kinetics/ct_transformer' }, 'create:clutch', 'tfc:brass_mechanisms')
    event.replaceInput({ id: 'woodencog:crafting/kinetics/wooden_generator' }, 'create:clutch', 'tfc:brass_mechanisms')

    // Create: Electro Energetics recipe changes
    event.replaceInput({}, 'electroenergetics:iron_wire', 'tfc_items:wrought_iron_wire')
    event.remove({ output: 'electroenergetics:iron_wire' });
    event.replaceInput({}, 'electroenergetics:copper_wire', '#c:wires/copper')
    // event.remove({ output: 'electroenergetics:copper_wire' });
    event.remove({ output: 'electroenergetics:red_electric_motor' });
	event.shaped('electroenergetics:red_electric_motor', [
		"EB ",
		"CAD",
        "EB "
	], {
		A: 'tfc:metal/double_sheet/steel',
		B: 'electroenergetics:copper_wire_spool',
        C: 'electroenergetics:commutator',
        D: '#c:dyes/red',
        E: 'electroenergetics:connector'
	});
    event.shaped('electroenergetics:iron_rail_spool', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'electroenergetics:empty_spool',
		B: 'tfc:metal/sheet/wrought_iron'
	});
    event.remove({ output: 'minecraft:lodestone' });
	event.shaped('minecraft:lodestone', [
		"BBB",
		"BAB",
        "BBB"
	], {
		A: 'electroenergetics:magnet',
		B: '#minecraft:stone_bricks'
	});
    event.remove({ output: 'electroenergetics:magnet' });
	event.shaped('electroenergetics:magnet', [
		" B ",
		"BAB",
        " B "
	], {
		A: 'tfcorewashing:briquet_magnetite',
		B: 'create:industrial_iron_block'
	});
    event.remove({ output: 'electroenergetics:iron_wire_strand' });
	event.shaped('electroenergetics:iron_wire_strand', [
		"AA ",
		"   ",
        "   "
	], {
		A: 'tfc_items:wrought_iron_wire'
	});

    // Create: Diesel Generators recipe changes
    event.remove({ output: 'createdieselgenerators:engine_piston' });
	event.shaped('createdieselgenerators:engine_piston', [
		" A ",
		" B ",
        " C "
	], {
		A: 'tfc:metal/ingot/steel',
		B: 'tfc:metal/rod/steel',
        C: 'tfc_items:steel_ring'
	});
    event.replaceInput(
    { id: 'createdieselgenerators:crafting/burner' },         // Arg 1: the filter
    'create:empty_blaze_burner',                    // Arg 2: the item to replace
    Ingredient.of('createlowheated:basic_burner')  // Arg 3: the item to replace it with 
    )

    // create recipes changes
    event.remove({ output: 'create:copper_valve_handle' });
	event.shaped('2x create:copper_valve_handle', [
		"C C",
		" A "
	], {
		A: 'create:andesite_alloy',
		C: 'tfc:metal/sheet/copper'
	});
    event.remove({ output: 'create:encased_chain_drive' });
	event.shaped('3x create:encased_chain_drive', [
		"AA",
		"AI"
	], {
		A: 'create:andesite_casing',
		I: 'tfc:metal/ingot/wrought_iron'
	});
    event.remove({ output: 'create:white_sail' });
	event.shaped('create:white_sail', [
		"CS",
		"SA"
	], {
		C: '#forge:cloth',
		S: '#c:rods/wooden',
		A: 'create:andesite_alloy'
	});
    event.remove({ output: 'create:mechanical_crafter' });
	event.shaped('3x create:mechanical_crafter', [
		"T",
		"C",
		"W"
	], {
		T: 'create:electron_tube',
		C: 'create:brass_casing',
		W: '#tfc:workbenches'
	});
    event.remove({ output: 'create:whisk' });
	event.shaped('2x create:whisk', [
		" A ",
		"SAS",
		"SSS"
	], {
		S: 'tfc:metal/sheet/wrought_iron',
		A: 'create:andesite_alloy'
	});
    event.remove({ output: 'create:brass_hand' });
	event.shaped('2x create:brass_hand', [
		" A ",
		"BBB",
		" B "
	], {
		B: 'tfc:metal/sheet/brass',
		A: 'create:andesite_alloy'
	});
    event.remove({ output: 'create:attribute_filter' });
	event.shaped('2x create:attribute_filter', [
		"BWB"
	], {
		B: 'tfc:metal/rod/brass',
		W: '#forge:cloth'
	});
    event.remove({ output: 'create:package_filter' });
	event.shaped('2x create:package_filter', [
		"BWB"
	], {
		B: 'tfc:metal/rod/zinc',
		W: '#forge:cloth'
	});
    event.remove({ output: 'create:filter' });
	event.shaped('2x create:filter', [
		"BWB"
	], {
		B: 'tfc:metal/rod/wrought_iron',
		W: '#forge:cloth'
	});
    event.remove({ id: 'create:crafting/kinetics/mechanical_saw' });
	event.shaped('create:mechanical_saw', [
        "   ",
		" D ",
        " C "
	], {
		D: 'tfc:metal/double_sheet/wrought_iron',
		C: 'create:andesite_casing'
	});

    event.replaceInput({id: 'create:crafting/kinetics/fluid_tank'}, 'minecraft:barrel', '#tfc:barrels')
    event.replaceInput({id: 'create:crafting/materials/sand_paper'}, 'minecraft:sand', '#c:sands')
    event.replaceInput({id: 'create:crafting/materials/rose_quartz'}, 'minecraft:quartz', '#c:rose_quartz_valid')
    event.replaceInput({id: 'create:crafting/kinetics/mechanical_press'}, 'tfc:metal/block/wrought_iron', 'tfc:metal/double_sheet/wrought_iron')
    event.replaceInput({id: 'create:crafting/kinetics/steam_engine'}, 'tfc:metal/block/copper', 'tfc:metal/double_sheet/copper')
    event.remove({output:[
        'create:iron_sheet',
        'create:golden_sheet',
        'create:copper_sheet',
        'create:brass_sheet']
    })

    //Vanilla & Create nuggets give TFC Metal and are 9 to a ingot
    event.remove({id:"create:crafting/materials/copper_nugget"})
    event.shapeless(('9x create:copper_nugget'),
        ["#forge:ingots/copper"])
    event.custom({
        "type":"tfc:heating",
        "ingredient":
        {
            "item": "create:copper_nugget"
        },
        "result_fluid":{
            "amount": 10,
            "id":"tfc:metal/copper"
        },
        "temperature":1080.0
    })
    event.remove({id:"create:crafting/materials/zinc_nugget_from_decompacting"})
    event.shapeless(('9x create:zinc_nugget'),
        ["#forge:ingots/zinc"])
    event.custom({
        "type":"tfc:heating",
        "ingredient":
        {
            "item": "create:zinc_nugget"
        },
        "result_fluid":{
            "amount": 10,
            "id":"tfc:metal/zinc"
        },
        "temperature":420.0
    })
    event.remove({id:"create:crafting/materials/brass_nugget_from_decompacting"})
    event.shapeless(('9x create:brass_nugget'),
        ["#forge:ingots/brass"])
    event.custom({
        "type":"tfc:heating",
        "ingredient":
        {
            "item": "create:brass_nugget"
        },
        "result_fluid":{
            "amount": 10,
            "id":"tfc:metal/brass"
        },
        "temperature":930.0
    })
    event.remove({id:"minecraft:iron_nugget"})
    event.shapeless(('9x minecraft:iron_nugget'),
        ["#forge:ingots/iron"])
    event.custom({
        "type":"tfc:heating",
        "ingredient":
        {
            "item": "minecraft:iron_nugget"
        },
        "result_fluid":{
            "amount": 10,
            "id":"tfc:metal/cast_iron"
        },
        "temperature":1535.0
    })
    event.remove({id:"minecraft:gold_nugget"})
    event.shapeless(('9x minecraft:gold_nugget'),
        ["#forge:ingots/gold"])
    event.custom({
        "type":"tfc:heating",
        "ingredient":
        {
            "item": "minecraft:gold_nugget"
        },
        "result_fluid":{
            "amount": 10,
            "id":"tfc:metal/gold"
        },
        "temperature":1060.0
    })
    //costom Electron Tube deployer recipe
    event.custom({
        type: "create:deploying",
        ingredients: [
            { item: "create:polished_rose_quartz" },
            { item: "tfc:metal/sheet/wrought_iron" }
        ],
        results: [
            { id: "create:electron_tube", count: 1}
        ]
    }).id("kubejs:deploying/electron_tube");
    
    //Firamlife drying recipes to get minecraft:dried_kelp for 
    // Winged Kelp → Dried Kelp
    event.custom({
        type: "firmalife:drying",
        ingredient: { item: "tfc:plant/winged_kelp" },
        result: {
            id: "minecraft:dried_kelp",
            count: 1
        }
    }).id("kubejs:drying/winged_kelp_to_dried_kelp");
    // Leafy Kelp → Dried Kelp
    event.custom({
        type: "firmalife:drying",
        ingredient: { item: "tfc:plant/leafy_kelp" },
        result: {
            id: "minecraft:dried_kelp",
            count: 1
        }
    }).id("kubejs:drying/leafy_kelp_to_dried_kelp");
    //Create: Aeronautics changes
    event.custom({
        type: "create:mechanical_crafting",
        accept_mirrored: true,
        category: "misc",
        key: {
            C: { item: "tfc:metal/sheet/copper" },
            D: { item: "minecraft:dried_kelp_block" },
            R: { item: "minecraft:redstone" },
            G: { item: "create:cogwheel"},
            S: { item: "create:fluid_pipe" }
        },
        pattern: [
            "CR  ",
            "DGSS",
            "CR  "
        ],
        result: {
            id: "aeronautics:mounted_potato_cannon",
            count: 1
        }
    }).id("kubejs:mechanical_crafting/mounted_potato_cannon");
    event.custom({
        type: "create:mechanical_crafting",
        accept_mirrored: true,
        category: "misc",
        key: {
            W: { item: "tfc:metal/sheet/wrought_iron" },
            C: { item: "create:chute" },
            P: { item: "minecraft:piston" },
            A: { item: "create:brass_casing"},
            B: { item: "tfc:metal/sheet/brass" },
            E: { item: "create:electron_tube" }
        },
        pattern: [
            "WCW",
            " C ",
            "PAP",
            "BEB"
        ],
        result: {
            id: "simulated:docking_connector",
            count: 1
        }
    }).id("kubejs:docking_connector");
    //aeronotics engine assembly
    event.custom({
        type: "create:sequenced_assembly",

        // Input item
        ingredient: { item: "tfc:metal/double_sheet/wrought_iron" },

        // Transitional item
        transitional_item: { id: 'simulated:incomplete_engine_assembly' },

        // Sequence steps
        sequence: [
            // Step 1: Mechanical Saw
            {
                type: "create:cutting",
                ingredients: [
                    { item: 'simulated:incomplete_engine_assembly' }
                ],
                results: [
                    { id: 'simulated:incomplete_engine_assembly' }
                ]
            },

            // Step 2: Mechanical Press
            {
                type: "create:pressing",
                ingredients: [
                    { item: 'simulated:incomplete_engine_assembly' }
                ],
                results: [
                    { id: 'simulated:incomplete_engine_assembly' }
                ]
            },
            
            //step 3: Deploy metal
            {
                type: "create:deploying",
                ingredients: [
                    { item: 'simulated:incomplete_engine_assembly' },
                    { item: "tfc:metal/sheet/wrought_iron" }
                ],
                results: [{ id: 'simulated:incomplete_engine_assembly' }]
            }
        ],

        // Output pool (50/50)
        results: [
            { id: "simulated:engine_assembly", count: 1, chance: 0.8 },
            { id: "tfc:metal/double_sheet/wrought_iron", count: 1, chance: 0.2 }
        ],

        // Loop count
        loops: 8

    }).id("kubejs:assembly/engine_assembly");
    //aeronautics gyroscpic mechanism
    event.custom({
        type: "create:sequenced_assembly",
        ingredient: { item: "tfc:metal/sheet/steel" },
        transitional_item: { id: 'simulated:incomplete_gyroscopic_mechanism' },

        // Sequence: 3 deployers
        sequence: [

            // Step 1 — Deploy cogwheel
            {
                type: "create:deploying",
                ingredients: [
                    { item: 'simulated:incomplete_gyroscopic_mechanism' },
                    { item: "create:cogwheel" }
                ],
                results: [{ id: 'simulated:incomplete_gyroscopic_mechanism' }]
            },

            // Step 2 — Deploy shaft
            {
                type: "create:deploying",
                ingredients: [
                    { item: 'simulated:incomplete_gyroscopic_mechanism' },
                    { item: "create:shaft" }
                ],
                results: [{ id: 'simulated:incomplete_gyroscopic_mechanism' }]
            },

            // Step 3 — Deploy brass nugget
            {
                type: "create:deploying",
                ingredients: [
                    { item: 'simulated:incomplete_gyroscopic_mechanism' },
                    { item: "create:brass_nugget" }
                ],
                results: [{ id: 'simulated:incomplete_gyroscopic_mechanism' }]
            }
        ],

        // Output pool (weighted)
        results: [
            { id: "simulated:gyroscopic_mechanism", count: 1, chance: 0.9 },
            { id: "create:brass_nugget", count: 1, chance: 0.1 }
        ],

        // Loop count
        loops: 5

    }).id("kubejs:assembly/gyroscopic_mechanism");
    //mechanical crafting simulated linked typewriter
    event.custom({
        type: "create:mechanical_crafting",
        accept_mirrored: false,
        category: "misc",
        key: {
            B: { tag: 'minecraft:buttons' },
            R: { item: 'create:transmitter' },
            G: { item: 'tfc:metal/sheet/gold'},
            P: { item: 'create:precision_mechanism' }
        },
        pattern: [
            "BBBBR",
            "BBBBB",
            "GPG  "
        ],
        result: {
            id: 'simulated:linked_typewriter',
            count: 1
        }
    }).id("kubejs:mechanical_crafting/linked_typewriter");
    event.shaped('simulated:honey_glue', [
        "HW",
		"NH"
	], {
		W: 'tfc:metal/sheet/wrought_iron',
		N: 'minecraft:iron_nugget',
        H: 'firmalife:food/raw_honey'
	});
    //aeronautics end_stone_powder
    event.custom({
        type: "create:mixing",
        heat_requirement: "none",

        ingredients: [
            { item: "tfc:powder/pyrite", count: 2 },
            { item: "tfc:powder/diamond", count: 2 },
            { item: "minecraft:redstone", count: 1 },
            { item: "tfc:powder/sulfur", count: 1 },
            { item: "tfc:powder/graphite", count: 1 },
            { item: "tfc:powder/kaolinite", count: 1 },
            { item: "tfc:powder/charcoal", count: 1 }
        ],

        results: [
            { id: "aeronautics:end_stone_powder", count: 1 }
        ]
    }).id("kubejs:mixing/end_stone_powder");

})
//========
// Tag Changes
//========
ServerEvents.tags('item', event => {
    // Add tags to wrought iron, gold & copper
    event.add('forge:ingots/irons', ['minecraft:iron_ingot','tfc:metal/ingot/wrought_iron']),
    event.add('forge:ingots/iron', ['tfc:metal/ingot/wrought_iron'])
    event.add('forge:ingots/gold', ['tfc:metal/ingot/gold'])
    event.add('forge:ingots/copper', ['tfc:metal/ingot/copper'])
    event.add('forge:ingots/brass', ['tfc:metal/ingot/brass'])
    event.add('forge:ingots/zinc', ['tfc:metal/ingot/zinc'])
    event.add('forge:cloth', ['tfc:burlap_cloth','tfc:silk_cloth','tfc:wool_cloth'])
    event.add('c:plates/gold', ['tfc:metal/sheet/gold'])
    event.add('forge:slimy',['minecraft:slime_ball', 'tfc:glue'])
    event.add('tfc:candles',['tfc:candle','tfc:candle/'])
    event.add('createlowheated:burner_starters',['tfc:flint_and_pyrite']),
    event.add('afc:kauri_logs',['afc:wood/log/kauri','afc:wood/wood/kauri']),
    event.add('tfc:food/wheat_flour',['tfc:food/wheat_flour']),
    event.add('tfc:sweeteners',['minecraft:sugar','afc:maple_sugar','afc:birch_sugar','firmalife:food/raw_honey'])
    event.add('c:rose_quartz_valid',['#c:gems/quartz', 'tfc:rock/raw/quartzite'])

    tfc_woodtypes.forEach(wood => {
		event.add('forge:stripped_logs', 'tfc:wood/stripped_log/' + wood);
        event.add('c:stripped_logs', 'tfc:wood/stripped_log/' + wood);
		event.add('forge:stripped_woods', 'tfc:wood/stripped_wood/' + wood);
        event.add('c:stripped_woods', 'tfc:wood/stripped_wood/' + wood);
    })
    afc_woodtypes.forEach(wood => {
		event.add('forge:stripped_logs', 'afc:wood/stripped_log/' + wood);
        event.add('c:stripped_logs', 'afc:wood/stripped_log/' + wood);
		event.add('forge:stripped_woods', 'afc:wood/stripped_wood/' + wood);
        event.add('c:stripped_woods', 'afc:wood/stripped_wood/' + wood);
    })

})

//Origonal code done by SeriousCreeper, update by ArcWolf Gaming
//Adds create sawmill recipe for all TFC wood types. Logs-> stripped, Stripped -> Lumber or Supports, Planks -> Lumber
//Also does all ArborFirmaCraft Trees
ServerEvents.recipes(event => {
	tfc_woodtypes.forEach(wood => {
		const logs = "tfc:wood/log/" + wood ;
		const stripped_logs = "tfc:wood/stripped_log/" + wood;
		const lumber = 'tfc:wood/lumber/' + wood;
		const planks = 'tfc:wood/planks/' + wood;
		const support = 'tfc:wood/support/' + wood;

		event.custom({type: 'create:cutting', ingredients: [{item: logs}], processing_time: 100, results: [{id: stripped_logs}]})
        event.custom({type: 'create:cutting', ingredients: [{item: stripped_logs}], processing_time: 100, results: [{count:8, id: lumber}]})
        event.custom({type: 'create:cutting', ingredients: [{item: stripped_logs}], processing_time: 100, results: [{count:4, id: support}]})
        event.custom({type: 'create:cutting', ingredients: [{item: planks}], processing_time: 100, results: [{ count:4, id: lumber}]})
	})
// Arborfirmacraft versio of above
    afc_woodtypes.forEach(wood => {
		const logs2 = "afc:wood/log/" + wood ;
		const stripped_logs2 = "afc:wood/stripped_log/" + wood;
		const lumber2 = 'afc:wood/lumber/' + wood;
		const planks2 = 'afc:wood/planks/' + wood;
		const support2 = 'afc:wood/support/' + wood;

		event.custom({type: 'create:cutting', ingredients: [{item: logs2}], processing_time: 100, results: [{id: stripped_logs2}]})
        event.custom({type: 'create:cutting', ingredients: [{item: stripped_logs2}], processing_time: 100, results: [{count:8, id: lumber2}]})
        event.custom({type: 'create:cutting', ingredients: [{item: stripped_logs2}], processing_time: 100, results: [{count:4, id: support2}]})
        event.custom({type: 'create:cutting', ingredients: [{item: planks2}], processing_time: 100, results: [{ count:4, id: lumber2}]})
	})
})
//========
//create: milling TFC grain in Flour
//========
const tfc_grains = [
    'barley',
    'wheat',
    'oat',
    'rye',
    'rice',
    'maize'
];
ServerEvents.recipes(event => {
    tfc_grains.forEach(grain => {
        const grainItem = `tfc:food/${grain}_grain`;
        const flourItem = `tfc:food/${grain}_flour`;

        event.custom({
            type: 'create:milling',
            ingredients: [
                { item: grainItem }
            ],
            processing_time: 150,
            results: [
                { id: flourItem, count: 1 }
            ]
        }).id(`create:milling/kubejs/${grain}_flour`);
    });
});
//========
//Create:milling all TFC flowers for TFC dyes
//========
const tfc_dye_plants = {
    blue: [
        "tfc:plant/blue_orchid",
        "tfc:plant/grape_hyacinth",
        "tfc:plant/cornflower"
    ],
    green: [
        "tfc:plant/barrel_cactus",
        "tfc:plant/reindeer_lichen",
        "tfc:plant/silken_pincushion_cactus",
        "tfc:plant/prickly_pear",
        "tfc:plant/prickly_pear_purple"
    ],
    brown: [
        "tfc:plant/field_horsetail",
        "tfc:plant/sargassum"
    ],
    light_blue: [
        "tfc:plant/labrador_tea",
        "tfc:plant/sapphire_tower",
        "tfc:plant/mountain_hullwort",
        "tfc:plant/penwortel"
    ],
    light_gray: [
        "tfc:plant/yucca",
        "tfc:plant/silver_bromeliad"
    ],
    lime: [
        "tfc:plant/moss"
    ],
    magenta: [
        "tfc:plant/athyrium_fern",
        "tfc:plant/morning_glory",
        "tfc:plant/pulsatilla",
        "tfc:plant/lilac",
        "tfc:plant/silver_spurflower",
        "tfc:plant/azalea"
    ],
    orange: [
        "tfc:plant/butterfly_milkweed",
        "tfc:plant/canna",
        "tfc:plant/nasturtium",
        "tfc:plant/strelitzia",
        "tfc:plant/tulip_orange",
        "tfc:plant/water_canna",
        "tfc:plant/marigold",
        "tfc:plant/flame_vine",
        "tfc:plant/palash",
        "tfc:plant/qantu"
    ],
    pink: [
        "tfc:plant/foxglove",
        "tfc:plant/sacred_datura",
        "tfc:plant/tulip_pink",
        "tfc:plant/snapdragon_pink",
        "tfc:plant/hibiscus",
        "tfc:plant/lotus",
        "tfc:plant/maiden_pink",
        "tfc:plant/moss_campion",
        "tfc:plant/ramunda"
    ],
    purple: [
        "tfc:plant/allium",
        "tfc:plant/black_orchid",
        "tfc:plant/perovskia",
        "tfc:plant/blue_ginger",
        "tfc:plant/pickerelweed",
        "tfc:plant/heather",
        "tfc:plant/purple_water_lily",
        "tfc:plant/shawiash"
    ],
    red: [
        "tfc:plant/guzmania",
        "tfc:plant/poppy",
        "tfc:plant/rose",
        "tfc:plant/snapdragon_red",
        "tfc:plant/tropical_milkweed",
        "tfc:plant/tulip_red",
        "tfc:plant/vriesea",
        "tfc:plant/anthurium",
        "tfc:plant/blood_lily",
        "tfc:plant/heliconia",
        "tfc:plant/kangaroo_paw",
        "tfc:plant/tank_bromeliad",
        "tfc:plant/kinnikinnick",
    ],
    white: [
        "tfc:plant/houstonia",
        "tfc:plant/oxeye_daisy",
        "tfc:plant/primrose",
        "tfc:plant/snapdragon_white",
        "tfc:plant/trillium",
        "tfc:plant/spanish_moss",
        "tfc:plant/tulip_white",
        "tfc:plant/white_water_lily",
        "tfc:plant/lily_of_the_valley",
        "tfc:plant/edelweiss",
        "tfc:plant/beachgrass"
    ],
    yellow: [
        "tfc:plant/calendula",
        "tfc:plant/dandelion",
        "tfc:plant/meads_milkweed",
        "tfc:plant/goldenrod",
        "tfc:plant/snapdragon_yellow",
        "tfc:plant/desert_flame",
        "tfc:plant/yellow_water_lily",
        "tfc:plant/elegant_sunburst_lichen",
        "tfc:plant/yellow_saxifrage",
        "tfc:plant/buttercup",
        "tfc:plant/sunflower"
    ]
}
ServerEvents.recipes(event => {
    Object.entries(tfc_dye_plants).forEach(([color, plants]) => {
        const dye = `minecraft:${color}_dye`;

        plants.forEach(plant => {
            event.custom({
                type: "create:milling",
                ingredients: [
                    { item: plant }
                ],
                processing_time: 150,
                results: [
                    { id: dye, count: 2 }
                ]
            }).id(`create:milling/kubejs/${color}_dye_from_${plant.replace(":", "_").replace("/", "_")}`);
        });
    });
});

// Map ore names to their powder output and counts per grade
const tfc_ore_powders = {
    bismuthinite: { small: 2, poor: 3, normal: 5, rich: 7 },
    cassiterite:  { small: 2, poor: 3, normal: 5, rich: 7 },
    garnierite:   { small: 2, poor: 3, normal: 5, rich: 7 },
    hematite:     { small: 2, poor: 3, normal: 5, rich: 7 },
    limonite:     { small: 2, poor: 3, normal: 5, rich: 7 },
    magnetite:    { small: 2, poor: 3, normal: 5, rich: 7 },
    malachite:    { small: 2, poor: 3, normal: 5, rich: 7 },
    native_copper:{ small: 2, poor: 3, normal: 5, rich: 7 },
    native_gold:  { small: 2, poor: 3, normal: 5, rich: 7 },
    native_silver:{ small: 2, poor: 3, normal: 5, rich: 7 },
    sphalerite:   { small: 2, poor: 3, normal: 5, rich: 7 },
    tetrahedrite: { small: 2, poor: 3, normal: 5, rich: 7 },

    // Gem ores
    diamond:      { gem: 4, raw: 4 },
    emerald:      { gem: 4, raw: 4 },
    lapis_lazuli: { gem: 4, raw: 4 },
    amethyst:     { gem: 4, raw: 4 },
    pyrite:       { gem: 4, raw: 4 },
    ruby:         { gem: 4, raw: 4 },
    sapphire:     { gem: 4, raw: 4 },
    topaz:        { gem: 4, raw: 4 },
    opal:         { gem: 4, raw: 4 },

    // Flux & salts
    borax:    { raw: 6, powder: "flux" },
    halite:   { raw: 4, powder: "salt" },
    saltpeter:{ raw: 4 },
    sulfur:   { raw: 4 },
    sylvite:  { raw: 4 },
    graphite: { raw: 4 },

    charcoal: { item: "minecraft:charcoal", count: 4, powder: "charcoal" },

    cryolite: { item: "tfc:ore/cryolite", count: 8, powder: "minecraft:redstone" },
    cinnabar: { item: "tfc:ore/cinnabar", count: 8, powder: "minecraft:redstone" }

};
//=======
//TFC quarn to create: milling
//=======
ServerEvents.recipes(event => {
    event.remove({id: 'create:milling/charcoal'})
    event.remove({id: 'create:milling/coal'})
    event.remove({id: 'create:milling/wool'})
    Object.entries(tfc_ore_powders).forEach(([ore, grades]) => {

        //Special Cases & Overrides
        if (grades.item) {

            // Support full item IDs (minecraft:redstone)
            var powder;
            if (grades.powder && grades.powder.indexOf(":") !== -1) {
                powder = grades.powder;
            } else {
                var powderName = grades.powder ? grades.powder : ore;
                powder = "tfc:powder/" + powderName;
            }

            event.custom({
                type: "create:milling",
                ingredients: [{ item: grades.item }],
                processing_time: 150,
                results: [{ id: powder, count: grades.count }]
            }).id("create:milling/kubejs/" + ore + "_special");

            return; // Skip grade logic
        }
        
        // "Normal" TFC Ores
        ["small", "poor", "normal", "rich", "raw", "gem"].forEach(function(grade) {
            if (!grades[grade]) return;

            var input;

            if (grade === "small") {
                input = "tfc:ore/small_" + ore;
            } else if (grade === "gem") {
                input = "tfc:gem/" + ore;
            } else if (grade === "raw") {
                input = "tfc:ore/" + ore;
            } else {
                input = "tfc:ore/" + grade + "_" + ore;
            }

            // Powder override logic
            var powder;
            if (grades.powder && grades.powder.indexOf(":") !== -1) {
                powder = grades.powder;
            } else {
                var powderName = grades.powder ? grades.powder : ore;
                powder = "tfc:powder/" + powderName;
            }

            var count = grades[grade];

            event.custom({
                type: "create:milling",
                ingredients: [{ item: input }],
                processing_time: 150,
                results: [{ id: powder, count: count }]
            }).id("create:milling/kubejs/" + ore + "_" + grade);
        });
    
    });
});
// TFC anvil -> Create sequence assembly for Double ingot -> sheets
ServerEvents.recipes(event => {
    tfcMetals.forEach(function (metal) {

        const input = `${metalMod(metal)}:metal/double_ingot/${metal}`;
        const output = `${metalMod(metal)}:metal/sheet/${metal}`;
        const transitional = `kubejs:incomplete_sheet_${metal}`;

        const tier = metalTier[metal];
        if (tier === undefined) return;

        // ANY hammer of same tier or higher
        const hammerChoices = hammerByTier[tier].map(function (h) {
            return { item: h, keepHeldItem: true };
        });

        const sequence = [];

        // Hammer hit #1
        sequence.push({
            type: "create:deploying",
            ingredients: [
                { item: transitional },
                hammerChoices
            ],
            results: [{ id: transitional }]
        });

        // Hammer hit #2
        sequence.push({
            type: "create:deploying",
            ingredients: [
                { item: transitional },
                hammerChoices
            ],
            results: [{ id: transitional }]
        });

        // Hammer hit #3
        sequence.push({
            type: "create:deploying",
            ingredients: [
                { item: transitional },
                hammerChoices
            ],
            results: [{ id: transitional }]
        });

        event.custom({
            type: "create:sequenced_assembly",
            ingredient: { item: input },
            results: [{ id: output }],
            transitional_item: { id: transitional },
            sequence: sequence
        }).id("kubejs:assembly/sheet_" + metal);
    });
});
//=======
//TFC welding using Create
//=======
// Unified welding definitions
function metalMod(metal) {
    if (metal === "chromium" || metal === "stainless_steel") {
        return "firmalife";
    }
    return "tfc";
}
var weldingTypes = {
    ingot: {
        input: (metal) => `${metalMod(metal)}:metal/ingot/${metal}`,
        output: (metal) => `${metalMod(metal)}:metal/double_ingot/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_ingot_${metal}`
    },
    sheet: {
        input: (metal) => `${metalMod(metal)}:metal/sheet/${metal}`,
        output: (metal) => `${metalMod(metal)}:metal/double_sheet/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_sheet_${metal}`
    },
    armor_boots: {
        armor: true,
        first_input: (metal) => `tfc:metal/unfinished_boots/${metal}`,
        second_input: (metal) => `tfc:metal/sheet/${metal}`,
        output: (metal) => `tfc:metal/boots/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_armor_boots_${metal}`,
        tier: (metal) => metalTier[metal],
        metalLoop: true
    },
    armor_chestplate: {
        armor: true,
        first_input: (metal) => `tfc:metal/unfinished_chestplate/${metal}`,
        second_input: (metal) => `tfc:metal/double_sheet/${metal}`,
        output: (metal) => `tfc:metal/chestplate/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_armor_chestplate_${metal}`,
        tier: (metal) => metalTier[metal],
        metalLoop: true
    },
    armor_greaves: {
        armor: true,
        first_input: (metal) => `tfc:metal/unfinished_greaves/${metal}`,
        second_input: (metal) => `tfc:metal/sheet/${metal}`,
        output: (metal) => `tfc:metal/greaves/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_armor_greaves_${metal}`,
        tier: (metal) => metalTier[metal],
        metalLoop: true
    },
    armor_helmet: {
        armor: true,
        first_input: (metal) => `tfc:metal/unfinished_helmet/${metal}`,
        second_input: (metal) => `tfc:metal/sheet/${metal}`,
        output: (metal) => `tfc:metal/helmet/${metal}`,
        transitional: (metal) => `kubejs:incomplete_weld_armor_helmet_${metal}`,
        tier: (metal) => metalTier[metal],
        metalLoop: true
    },
    basic_burner: {
        armor: false,
        metalLoop: false,
        first_input: () => "tfc:metal/double_sheet/cast_iron",
        second_input: () => "tfc:metal/double_sheet/cast_iron",
        output: () => "createlowheated:basic_burner",
        transitional: () => "kubejs:incomplete_basic_burner",
        tier: () => metalTier["wrought_iron"]
    }
        
}; 
// Welding using Create
ServerEvents.recipes(event => {

    // --- Shared welding recipe builder ---
    function buildWeldingRecipe(id, tier, input, second, output, transitional) {

        const hammerChoices = hammerByTier[tier].map(h => ({
            item: h,
            keepHeldItem: true
        }));

        const sequence = [
            {
                type: "create:deploying",
                ingredients: [
                    { item: transitional },
                    { item: "tfc:powder/flux" }
                ],
                results: [{ id: transitional }]
            },
            {
                type: "create:deploying",
                ingredients: [
                    { item: transitional },
                    { item: second }
                ],
                results: [{ id: transitional }]
            },
            {
                type: "create:deploying",
                ingredients: [
                    { item: transitional },
                    hammerChoices
                ],
                results: [{ id: transitional }]
            }
        ];

        event.custom({
            type: "create:sequenced_assembly",
            ingredient: { item: input },
            results: [{ id: output }],
            transitional_item: { id: transitional },
            sequence: sequence
        }).id(id);
    }

    // --- OUTLIER HANDLER (isolated scope) ---
    function handleOutlier(typeName, type) {

        const tier = type.tier();
        const input = type.first_input();
        const second = type.second_input();
        const output = type.output();
        const transitional = type.transitional();

        buildWeldingRecipe(
            `kubejs:welding/${typeName}`,
            tier,
            input,
            second,
            output,
            transitional
        );
    }

    // --- MAIN LOOP ---
    Object.keys(weldingTypes).forEach(typeName => {
        const type = weldingTypes[typeName];

        if (type.metalLoop === false) {
            handleOutlier(typeName, type);
            return;
        }

        tfcMetals.forEach(metal => {

            if (type.armor && toolMetals.indexOf(metal) === -1) return;

            const tier = metalTier[metal];
            if (tier === undefined) return;

            const isArmor = type.first_input !== undefined;

            const input = isArmor ? type.first_input(metal) : type.input(metal);
            const second = isArmor ? type.second_input(metal) : input;
            const output = type.output(metal);
            const transitional = type.transitional(metal);

            buildWeldingRecipe(
                `kubejs:welding/${typeName}_${metal}`,
                tier,
                input,
                second,
                output,
                transitional
            );
        });
    });

});


// var actionMap = {
//     hit:        "hammer",        // tier‑or‑higher
//     heavy_hit:  "hammer",        // tier‑or‑higher
//     weld:       "hammer",        // tier‑or‑higher (final step)
//     punch:      "chisel",        // tfc:metal/chisel/<metal>
//     bend:       "wrench",        // create:wrench
//     shrink:     "jacks",         // tfc:jacks
//     upset:      "press",         // create:press
//     draw:       "tongs"          // tfchotornot:tongs/<metal> (tier‑or‑higher)
// };

//======
//TFC Forging using Create
//======
ServerEvents.recipes(function (event) {

    // 1. Action → tool type
    var actionMap = {
        hit:        "hammer",        // tier-or-higher
        heavy_hit:  "hammer",        // tier-or-higher
        weld:       "hammer",        // tier-or-higher (final step)
        punch:      "chisel",        // tfc:metal/chisel/<metal>
        bend:       "wrench",        // create:wrench
        shrink:     "jacks",         // tfc:jacks
        upset:      "press",         // create:press
        draw:       "tongs"          // tfchotornot:tongs/<metal> (tier-or-higher)
    };

    // 2. Metals that actually have hammer/chisel/tongs
    // var toolMetals = [
    const toolMetals = [
        "copper",
        "bronze",
        "bismuth_bronze",
        "black_bronze",
        "wrought_iron",
        "steel",
        "black_steel",
        "blue_steel",
        "red_steel"
    ];
    // 3. Tool item resolvers
    var toolItemByType = {
        hammer: (metal) => `tfc:metal/hammer/${metal}`,
        chisel: (metal) => `tfc:metal/chisel/${metal}`,
        wrench: () => "create:wrench",
        jacks:  () => "tfc:jacks",
        press:  () => "create:press",
        tongs:  (metal) => `tfc:metal/hoe/${metal}`
    };
    // 4. Static forging rules 
    var forgingRules = {
        knife_blade: ["hit_last","draw_second_last","draw_third_last"],
        pickaxe_head: ["punch_last","draw_not_last","bend_not_last"],
        hammer_head: ["punch_last","shrink_not_last"],
        axe_head: ["punch_last","hit_second_last","upset_third_last"],
        chisel_head: ["hit_last","draw_not_last","hit_not_last"],
        hoe_head: ["punch_last","hit_not_last","bend_not_last"],
        javelin_head: ["hit_last","hit_second_last","draw_third_last"],
        mace_head: ["hit_last","bend_not_last","shrink_not_last"],
        propick_head: ["punch_last","bend_not_last","draw_not_last"],
        saw_blade: ["hit_last","hit_second_last"],
        scythe_blade: ["hit_last","draw_second_last","bend_third_last"],
        shovel_head: ["punch_last","hit_not_last"],
        sword_blade: ["hit_last","bend_second_last","bend_third_last"],
        tuyere: ["bend_last","bend_second_last"],
        bars: ["upset_last","punch_second_last","punch_third_last"],
        chain: ["hit_any","draw_not_last"],
        rod: {rules:["hit_last","hit_second_last","hit_third_last"], skipBlank: true},
        fish_hook: ["hit_any","bend_any","draw_not_last"],
        unfinished_lamp: ["bend_last","bend_second_last","draw_third_last"],
        raw_iron_bloom: {rules:["hit_last","hit_second_last","hit_third_last"], skipBlank: true},        
        refined_iron_bloom: {rules:["hit_last","hit_second_last","hit_third_last"], skipBlank: true},
        bucket_blue_steel: {rules: ["hit_last", "bend_second_last", "bend_third_last"],skipBlank: true},
        bucket_red_steel: {rules: ["hit_last", "bend_second_last", "bend_third_last"], skipBlank: true},
        unfinished_boots: {rules: ["bend_last", "bend_second_last", "shrink_third_last"], skipBlank: true},       
        unfinished_chestplate: {rules: ["hit_last", "hit_second_last", "upset_third_last"], skipBlank: true},        
        unfinished_greaves: {rules: ["hit_any", "draw_any", "bend_any"], skipBlank: true},        
        unfinished_helmet: {rules: ["hit_last", "bend_second_last", "bend_third_last"], skipBlank: true},
        high_carbon_black_steel: {rules: ["hit_last", "hit_second_last", "hit_third_last"], skipBlank: true},
        high_carbon_blue_steel: {rules: ["hit_last", "hit_second_last", "hit_third_last"], skipBlank: true},
        high_carbon_red_steel: {rules: ["hit_last", "hit_second_last", "hit_third_last"], skipBlank: true},
        high_carbon_steel: {rules: ["hit_last", "hit_second_last", "hit_third_last"], skipBlank: true},
        pig_iron: {rules: ["hit_last", "hit_second_last", "hit_third_last"], skipBlank: true},
        stainless_steel_jar_lid: {rules: ["hit_last", "hit_second_last", "punch_third_last"], skipBlank: true},
        tin_jar_lid: {rules: ["hit_last", "hit_second_last", "punch_third_last"], skipBlank: true},
        pie_pan: {rules: ["hit_last", "hit_second_last", "draw_third_last"], skipBlank: true},
        copper_pipe: {rules: ["draw_last", "bend_not_last"], skipBlank: true},
        sprinkler: { rules: ["hit_last", "hit_second_last", "punch_third_last"], skipBlank: true},
        iron_door: {rules: ["hit_last","punch_not_last","draw_not_last"],skipBlank: true},
        copper_door: {rules: ["hit_last","punch_not_last","draw_not_last"],skipBlank: true},
        trapdoor: {rules: ["bend_last","draw_second_last","draw_third_last"],skipBlank: true},
        minecart: {rules: ["bend_last","not_not_last","not_not_last"],skipBlank: true},
        steel_pipe: {rules: ["draw_last"],skipBlank: true}
    };
    // 5. Ingredient resolver per head type 
    var ingredientVariantsByHeadType = {
        knife_blade: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        pickaxe_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        axe_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        hammer_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        chisel_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        hoe_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        javelin_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        mace_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        propick_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        saw_blade: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        scythe_blade: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        shovel_head: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        sword_blade: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        tuyere: [{ ingredient: (metal) => ({ item: `tfc:metal/double_sheet/${metal}` }), count: 1 }],
        bars: [
            { ingredient: (metal) => ({ item: `tfc:metal/sheet/${metal}` }), count: 8 },
            { ingredient: (metal) => ({ item: `tfc:metal/double_sheet/${metal}` }), count: 16 }
        ],
        chain: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 16 }],
        rod:   [{ ingredient: (metal) => ({ item: `${metalMod(metal)}:metal/ingot/${metal}` }), count: 2 }],
        //tong_part: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        fish_hook:[{ ingredient: (metal) => ({ item: `tfc:metal/sheet/${metal}` }), count: 1 }],
        raw_iron_bloom: [{ ingredient: () => ({ item: "tfc:raw_iron_bloom" }), count: 1 }],
        refined_iron_bloom: [{ ingredient: () => ({ item: "tfc:refined_iron_bloom" }), count: 1 }],
        bucket_blue_steel: [{ ingredient: () => ({ item: "tfc:metal/sheet/blue_steel" }), count: 1 }],        
        bucket_red_steel: [{ ingredient: () => ({ item: "tfc:metal/sheet/red_steel" }), count: 1 }],
        unfinished_lamp: [{ ingredient: (metal) => ({ item: `tfc:metal/ingot/${metal}` }), count: 1 }],
        unfinished_boots: [{ ingredient: (metal) => ({ item: `tfc:metal/sheet/${metal}` }), count: 1 }],       
        unfinished_chestplate: [{ ingredient: (metal) => ({ item: `tfc:metal/double_sheet/${metal}` }), count: 1 }],
        unfinished_greaves: [{ ingredient: (metal) => ({ item: `tfc:metal/double_sheet/${metal}` }), count: 1 }],      
        unfinished_helmet: [{ ingredient: (metal) => ({ item: `tfc:metal/double_sheet/${metal}` }), count: 1 }],       
        high_carbon_black_steel: [{ ingredient: () => ({ tag: "c:ingots/high_carbon_black_steel" }), count: 1 }],
        high_carbon_blue_steel: [{ ingredient: () => ({ tag: "c:ingots/high_carbon_blue_steel" }), count: 1 }], 
        high_carbon_red_steel: [{ ingredient: () => ({ tag: "c:ingots/high_carbon_red_steel" }), count: 1 }], 
        high_carbon_steel: [{ ingredient: () => ({ tag: "c:ingots/high_carbon_steel" }), count: 1 }], 
        pig_iron: [{ ingredient: () => ({ tag: "c:ingots/pig_iron" }), count: 1 }],
        stainless_steel_jar_lid: [{ ingredient: () => ({ item: "firmalife:metal/ingot/stainless_steel" }), count: 16 }],
        tin_jar_lid: [{ ingredient: () => ({ item: "tfc:metal/ingot/tin" }), count: 16 }],
        pie_pan: [{ ingredient: () => ({ item: "tfc:metal/sheet/cast_iron" }), count: 4 }],
        copper_pipe: [{ ingredient: () => ({ item: "tfc:metal/sheet/copper" }), count: 8 }],
        sprinkler: [{ ingredient: () => ({ item: "tfc:metal/sheet/copper" }), count: 1 }],
        iron_door: [{ ingredient: () => ({ item: "tfc:metal/sheet/wrought_iron" }), count: 1 }],
        copper_door: [{ ingredient: () => ({ item: "tfc:metal/sheet/copper" }), count: 1 }],
        trapdoor: [{ ingredient: (metal) => ({ item: `tfc:metal/sheet/${metal}` }), count: 1 }],
        minecart: [
            { ingredient: () => ({ item: "tfc:metal/sheet/steel" }), count: 1 },
            { ingredient: () => ({ item: "tfc:metal/double_sheet/wrought_iron" }), count: 1 }
        ],
        steel_pipe: [{ ingredient: () => ({ item: "tfc:metal/sheet/steel" }), count: 8 }]
    };

    // 6. Tier‑or‑higher tool logic (using your global metalTier)
    const metalTier = global.metalTier;

    // 7. Tier‑or‑higher AND must be a real tool metal
    function validToolMetalsFor(metal) {
        var tier = metalTier[metal];
        var list = [];
    
        for (var m in metalTier) {
            // must be tier-or-higher AND must be a real tool metal
            if (metalTier[m] >= tier && toolMetals.indexOf(m) !== -1) {
                list.push(m);
            }
        }
        return list;
    }
    //Output overrides for items that do not fit the "tfc:metal/*tool*/*metal*" format
    var outputIdOverride = {
        //tong_part: (metal) => `tfchotornot:tong_part/${metal}`,
        raw_iron_bloom: () => "tfc:refined_iron_bloom",
        refined_iron_bloom: () => "tfc:metal/ingot/wrought_iron",
        bucket_blue_steel: () => "tfc:metal/bucket/blue_steel",
        bucket_red_steel: () => "tfc:metal/bucket/red_steel",
        unfinished_boots:     (metal) => `tfc:metal/unfinished_boots/${metal}`,
        unfinished_chestplate:(metal) => `tfc:metal/unfinished_chestplate/${metal}`,
        unfinished_greaves:   (metal) => `tfc:metal/unfinished_greaves/${metal}`,
        unfinished_helmet:    (metal) => `tfc:metal/unfinished_helmet/${metal}`,
        unfinished_lamp: (metal) => `tfc:metal/unfinished_lamp/${metal}`,
        high_carbon_black_steel: () => "tfc:metal/ingot/black_steel",
        high_carbon_blue_steel: () => "tfc:metal/ingot/blue_steel",
        high_carbon_red_steel: () => "tfc:metal/ingot/red_steel",
        high_carbon_steel: () => "tfc:metal/ingot/steel",
        pig_iron: () => "tfc:metal/ingot/high_carbon_steel",
        stainless_steel_jar_lid: () => "firmalife:stainless_steel_jar_lid",
        tin_jar_lid: () => "tfc:jar_lid",
        pie_pan: () => "firmalife:pie_pan",
        copper_pipe: () => "firmalife:copper_pipe",
        sprinkler: () => "firmalife:sprinkler",
        iron_door: () => "minecraft:iron_door",
        copper_door: () => "minecraft:copper_door",
        minecart: () => "minecraft:minecart",
        steel_pipe: () => "tfc:steel_pipe"
    };
    var toolMetalOverride = {
        bucket_blue_steel: ["blue_steel", "red_steel"],
        bucket_red_steel: ["blue_steel", "red_steel"]
    };
    
    // 8. Generate Create sequenced_assembly recipes
    for (var headType in forgingRules) {
        if (!forgingRules.hasOwnProperty(headType)) continue;

        var ruleEntry = forgingRules[headType];
        var rules = ruleEntry.rules || ruleEntry;   // supports both formats
        var skipBlank = ruleEntry.skipBlank || false;

        var variants = ingredientVariantsByHeadType[headType];

        var isMetalBased = !(
            headType === "raw_iron_bloom" ||
            headType === "refined_iron_bloom" ||
            headType === "bucket_blue_steel" ||
            headType === "bucket_red_steel" ||
            headType === "high_carbon_black_steel" ||
            headType === "high_carbon_blue_steel" ||
            headType === "pig_iron" ||
            headType === "high_carbon_red_steel" ||
            headType === "high_carbon_steel" ||
            headType === "stainless_steel_jar_lid" ||
            headType === "tin_jar_lid" ||
            headType === "pie_pan" ||
            headType === "copper_pipe" ||
            headType === "sprinkler" ||
            headType === "iron_door" ||
            headType === "copper_door" ||
            headType === "minecart" ||
            headType === "steel_pipe"
        );
        
        // var metalsToProcess = isMetalBased ? toolMetals : [null];
        var metalsToProcess;

        if (headType === "rod") {
            metalsToProcess = tfcMetals;
        } else if (isMetalBased) {
            metalsToProcess = toolMetals;
        } else {
            metalsToProcess = [null];
        }

        for (var m = 0; m < metalsToProcess.length; m++) {
            var metal = metalsToProcess[m];
            var output = outputIdOverride[headType]
                ? outputIdOverride[headType](metal)
                : `${metalMod(metal)}:metal/${headType}/${metal}`;
            var transitional = output;

            for (var v = 0; v < variants.length; v++) {
                var variant = variants[v];
    
                // Ingredient + output count for this variant
                var ingredient = variant.ingredient(metal);
                var outputCount = variant.count;

            // First step: apply the tool head blank
            var sequence = [];

            if (!skipBlank) {
                sequence.push({
                    type: "create:deploying",
                    ingredients: [ingredient, { item: output }],
                    results: [{ id: transitional }]
                });
            }

            // Build tool steps (reverse order)
            var steps = [];
            var reversed = rules.slice().reverse();
            if (!rules || !rules.length) {
                console.log("FORGING ERROR: rules missing for", headType, JSON.stringify(ruleEntry));
            }

            for (var i = 0; i < reversed.length; i++) {
                var rule = reversed[i];
                var action = rule.split("_")[0];
                var toolType = actionMap[action];
                if (!toolType) continue;

                // Get valid tool metals for this forging metal
                var valid = toolMetalOverride[headType]
                    ? toolMetalOverride[headType]
                    : (isMetalBased ? validToolMetalsFor(metal) : toolMetals);

                // Build multi-item ingredient for this action
                var toolIngredientArray = [];

                for (var t = 0; t < valid.length; t++) {
                    var toolMetal = valid[t];
                
                    var toolItem =
                        (toolType === "hammer" || toolType === "chisel" || toolType === "tongs")
                        ? toolItemByType[toolType](toolMetal)
                        : toolItemByType[toolType]();
                    toolIngredientArray.push({ item: toolItem });
                }

                // ONE deploying step for this action
                if (toolType === "press") {
                    // Create Mechanical Press step
                    steps.push({
                        type: "create:pressing",
                        ingredients: [{ item: transitional }],
                        results: [{ id: transitional }]
                    });
                } else {
                    // Normal deployer step
                    steps.push({
                        type: "create:deploying",
                        ingredients: [{ item: transitional }, toolIngredientArray],
                        results: [{ id: transitional }]
                    });
                }
            }

            // var sequence = [ firstStep ].concat(steps);
            sequence = sequence.concat(steps);
            var metalId = metal === null ? "nom" : metal;
            var recipeId = `kubejs:forging_${headType}_${metalId}_v${v}`;

            event.custom({
                type: "create:sequenced_assembly",
                ingredient: ingredient,
                transitionalItem: transitional,          
                transitional_item: { id: transitional }, 
                sequence: sequence,
                results: [{ id: output, count: outputCount }],
                loops: 1
            })
            .id(recipeId);

            // console.log("FORGING: REGISTERED CREATE RECIPE", recipeId);
        
        }
    }
    }
});

TFCEvents.data(event => {
    const hugeHeavyItems = [
        'create:white_toolbox',
        'create:orange_toolbox',
        'create:magenta_toolbox',
        'create:light_blue_toolbox',
        'create:yellow_toolbox',
        'create:lime_toolbox',
        'create:pink_toolbox',
        'create:gray_toolbox',
        'create:light_gray_toolbox',
        'create:cyan_toolbox',
        'create:purple_toolbox',
        'create:blue_toolbox',
        'create:brown_toolbox',
        'create:green_toolbox',
        'create:red_toolbox',
        'create:black_toolbox',
        'createdieselgenerators:track_layers_bag'
    ];
    hugeHeavyItems.forEach(item => {
        event.itemSize({
            ingredient: item,
            weight: 'very_heavy',
            size: 'huge'
        });
    });
});