-- =============================================================
-- Real Fuel Consumption — RFCRegister.lua
-- Registers the RFCEngineModes specialization into every
-- vehicle type that has the Motorized spec, and registers the
-- input action for cycling engine modes.

-- =============================================================
-- Register the specialization with the vehicle type manager
-- =============================================================
local function registerEngineModesSpec(typeManager)
    if typeManager.typeName ~= "vehicle" then return end

    -- Register the specialization class itself
    if g_specializationManager:getSpecializationByName("rfcEngineModes") == nil then
        g_specializationManager:addSpecialization(
            "rfcEngineModes",
            "RFCEngineModes",
            Utils.getFilename("scripts/RFCEngineModes.lua", RealFuelConsumption.MOD_DIR),
            nil
        )
    end

    -- Add it to every motorized vehicle type
    for typeName, typeEntry in pairs(typeManager:getTypes()) do
        if typeEntry ~= nil and typeEntry.specializationsByName ~= nil then
            if typeEntry.specializationsByName["motorized"] ~= nil
               and typeEntry.specializationsByName["rfcEngineModes"] == nil then
                typeManager:addSpecialization(typeName, RealFuelConsumption.MOD_NAME .. ".rfcEngineModes")
            end
        end
    end
end

-- IMPORTANT (v1.2.0.3): appendedFunction, not prependedFunction. The
-- v1.2.0.1 attempt at savegame persistence used prependedFunction here,
-- meaning our registration ran BEFORE the base game's own finalizeTypes
-- body — likely too early for some of what it depends on, and the
-- probable cause of a reported load-screen freeze. Advanced Damage System
-- (a real, published mod doing the same kind of type registration) uses
-- appendedFunction for this exact hook, confirmed by reading its source.
TypeManager.finalizeTypes = Utils.appendedFunction(TypeManager.finalizeTypes, registerEngineModesSpec)

-- =============================================================
-- Register the input action for cycling engine modes
-- =============================================================
local function registerInputActions()
    -- The action is declared in modDesc.xml <actions>. If it did not
    -- register, log it clearly so the keybind failure is diagnosable
    -- instead of failing silently.
    if InputAction.RFC_CYCLE_ENGINE_MODE == nil then
        print("[RFC] WARNING: InputAction RFC_CYCLE_ENGINE_MODE was not registered — check modDesc <actions> block")
    end
end

Mission00.loadMission00Finished = Utils.appendedFunction(
    Mission00.loadMission00Finished,
    function(self, node)
        registerInputActions()
    end
)
