-- OutOfFuel.lua
-- FS25: stop the vanilla "min 10% fuel after load" behavior.
-- Replaces Motorized:onPostLoad WITHOUT calling the original.
-- Author: Mander

OutOfFuel = {
    -- set true if you want to *keep* GIANTS' refill (debug switch)
    keepVanillaRefill = false,

    -- optional: print when vehicles would have been refilled
    verbose = false,
    patched = false
}

local function log(msg)  print(("[OutOfFuel] %s"):format(msg)) end
local function safeToString(x) return x and tostring(x) or "nil" end

-- Our replacement for Motorized:onPostLoad
function OutOfFuel.onPostLoad_noRefill(self, superFunc, savegame)
    -- If user asked to keep vanilla logic, just call it and return
    if OutOfFuel.keepVanillaRefill and type(superFunc) == "function" then
        return superFunc(self, savegame)
    end

    local spec = self.spec_motorized
    if spec == nil then
        -- Extremely rare, but keep safe
        if type(superFunc) == "function" then
            return superFunc(self, savegame)
        end
        return
    end

    ----------------------------------------------------------------
    -- VANILLA BLOCK (SERVER) WE ARE **REMOVING** ON PURPOSE:
    --  - GIANTS refills each consumer (Diesel/DEF/Electric/Methane)
    --    up to 10% capacity and charges the farm immediately.
    --
    -- We skip it entirely. Optionally print what would have happened.
    ----------------------------------------------------------------
    if self.isServer and OutOfFuel.verbose then
        -- Mirror the iteration but only log
        local wouldCost = 0
        for _, consumer in pairs(spec.consumersByFillTypeName or {}) do
            local level = self.getFillUnitFillLevel and self:getFillUnitFillLevel(consumer.fillUnitIndex) or 0
            local cap   = self.getFillUnitCapacity and self:getFillUnitCapacity(consumer.fillUnitIndex) or 0
            local minLv = cap * 0.10
            if level < minLv then
                local delta = (minLv - level)
                local perL  = g_currentMission and g_currentMission.economyManager:getCostPerLiter(consumer.fillType) or 0
                local cost  = delta * perL * 2.0
                wouldCost = wouldCost + cost
                log(("-- SKIP REFILL -- %s: fillUnit=%s type=%s level=%.3f/%.3f (would add %.3f, cost %.0f)")
                    :format(safeToString(self.configFileName),
                            safeToString(consumer.fillUnitIndex),
                            safeToString(consumer.fillType),
                            level, cap, delta, cost))
            end
        end
        if wouldCost > 0 then
            log(("Total skipped auto-refill charge: %.0f"):format(wouldCost))
        end
    end

    ----------------------------------------------------------------
    -- Keep the rest of GIANTS postLoad logic (required!)
    ----------------------------------------------------------------
    spec.propellantFillUnitIndices = {}
    for _, fillType in pairs({FillType.DIESEL, FillType.DEF, FillType.ELECTRICCHARGE, FillType.METHANE}) do
        local fillTypeName = g_fillTypeManager:getFillTypeNameByIndex(fillType)
        if spec.consumersByFillTypeName ~= nil
        and spec.consumersByFillTypeName[fillTypeName] ~= nil then
            table.insert(spec.propellantFillUnitIndices, spec.consumersByFillTypeName[fillTypeName].fillUnitIndex)
        end
    end

    if spec.motor ~= nil then
        spec.motor:postLoad(savegame)
    end
end

-- One-time patch installer
local function installPatch()
    if OutOfFuel.patched then return end
    if Motorized == nil or Utils == nil or type(Utils.overwrittenFunction) ~= "function" then
        log("ERROR: Motorized or Utils.overwrittenFunction not available; cannot patch.")
        return
    end

    -- Wrap/replace Motorized:onPostLoad
    Motorized.onPostLoad = Utils.overwrittenFunction(Motorized.onPostLoad, OutOfFuel.onPostLoad_noRefill)
    OutOfFuel.patched = true
    log("Patched Motorized:onPostLoad (vanilla 10% auto-refill disabled).")
end

function OutOfFuel:loadMap()
    installPatch()
end
function OutOfFuel:deleteMap() end
function OutOfFuel:update(dt) end

addModEventListener(OutOfFuel)
