-- ============================================================
-- REA_engineRealism.lua
-- LS25 – Motorrealismus (Temperatur, Winter, Schäden)
-- FINAL STABLE FIX
-- ============================================================

REA_engineRealism = {}
local mt = Class(REA_engineRealism)

--------------------------------------------------------------
-- KONFIGURATION
--------------------------------------------------------------
REA_engineRealism.WARN_TEMP     = 95
REA_engineRealism.ALARM_TEMP    = 100
REA_engineRealism.CRITICAL_TEMP = 110
REA_engineRealism.SHUTDOWN_TEMP = 120

REA_engineRealism.DAMAGE_RATE_HOT  = 0.000002
REA_engineRealism.DAMAGE_RATE_COLD = 0.0000015

REA_engineRealism.COOL_IDLE  = 0.00004
REA_engineRealism.COOL_DRIVE = 0.00009

REA_engineRealism.WARMUP_TIME = 180000 -- 3 Minuten

--------------------------------------------------------------
-- KONSTRUKTOR
--------------------------------------------------------------
function REA_engineRealism.new()
    local self = setmetatable({}, mt)
    return self
end

--------------------------------------------------------------
-- UPDATE (LS25-SICHER)
--------------------------------------------------------------
function REA_engineRealism:update(dt)
    if g_currentMission == nil then return end
    if g_currentMission.vehicles == nil then return end

    for _, vehicle in ipairs(g_currentMission.vehicles) do
        if vehicle ~= nil and vehicle.spec_motorized ~= nil then
            self:updateVehicle(vehicle, dt)
        end
    end
end

--------------------------------------------------------------
-- FAHRZEUGLOGIK
--------------------------------------------------------------
function REA_engineRealism:updateVehicle(vehicle, dt)
    local spec = vehicle.spec_motorized
    if spec.motorTemperature == nil then return end

    -- persistente Werte
    vehicle.reaEngineDamage = vehicle.reaEngineDamage or 0
    vehicle.reaWarmupTime   = vehicle.reaWarmupTime or 0

    local temp  = spec.motorTemperature
    local speed = vehicle:getLastSpeed() or 0
    local load  = spec.smoothedLoadPercentage or 0

    ----------------------------------------------------------
    -- AUSSENTEMPERATUR (LS25-kompatibel)
    ----------------------------------------------------------
    local ambient = 15
    if g_currentMission.environment ~= nil
        and g_currentMission.environment.weather ~= nil
        and g_currentMission.environment.weather.temperature ~= nil then
        ambient = g_currentMission.environment.weather.temperature
    end

    local ambientFactor = 1
    if ambient < 0 then
        ambientFactor = 0.7
    elseif ambient > 25 then
        ambientFactor = 1.3
    end

    ----------------------------------------------------------
    -- WARMUP
    ----------------------------------------------------------
    if vehicle:getIsMotorStarted() then
        vehicle.reaWarmupTime =
            math.min(vehicle.reaWarmupTime + dt, REA_engineRealism.WARMUP_TIME)
    else
        vehicle.reaWarmupTime = 0
    end

    local warmFactor =
        math.min(vehicle.reaWarmupTime / REA_engineRealism.WARMUP_TIME, 1)

    ----------------------------------------------------------
    -- KÜHLUNG
    ----------------------------------------------------------
    if not vehicle:getIsMotorStarted() then
        temp = temp - dt * REA_engineRealism.COOL_IDLE * ambientFactor
    elseif speed > 10 then
        temp = temp - dt * REA_engineRealism.COOL_DRIVE * ambientFactor
    end

    ----------------------------------------------------------
    -- LASTHITZE
    ----------------------------------------------------------
    if load > 0.85 then
        temp = temp + dt * 0.00012 * ambientFactor
    end

    ----------------------------------------------------------
    -- KALTSTART-VERSCHLEISS
    ----------------------------------------------------------
    if warmFactor < 1 and load > 0.6 then
        vehicle.reaEngineDamage =
            math.min(vehicle.reaEngineDamage + dt * REA_engineRealism.DAMAGE_RATE_COLD, 1)
    end

    ----------------------------------------------------------
    -- HITZESCHÄDEN
    ----------------------------------------------------------
    if temp >= REA_engineRealism.CRITICAL_TEMP then
        vehicle.reaEngineDamage =
            math.min(vehicle.reaEngineDamage + dt * REA_engineRealism.DAMAGE_RATE_HOT, 1)
    end

    ----------------------------------------------------------
    -- LEISTUNGSDROSSELUNG
    ----------------------------------------------------------
    if spec.motor ~= nil then
        spec.reaOrigTorque = spec.reaOrigTorque or spec.motor.torqueScale or 1

        local factor = 1
        if temp >= REA_engineRealism.ALARM_TEMP then
            factor = math.max(0.5, 1 - vehicle.reaEngineDamage * 0.6)
        end

        -- Rolling resistance from REAwheels (e.g. low tire pressure "walk" losses).
        -- Neutral is 1.0; higher values reduce available torque slightly.
        local rr = vehicle.reaPressureRollMul or 1.0
        rr = MathUtil.clamp(rr, 0.85, 2.0)

        spec.motor.torqueScale = (spec.reaOrigTorque * factor * warmFactor) / rr
    end

    ----------------------------------------------------------
    -- ABSCHALTUNG
    ----------------------------------------------------------
    if temp >= REA_engineRealism.SHUTDOWN_TEMP then
        if vehicle:getIsMotorStarted() then
            vehicle:stopMotor()
        end
    end

    spec.motorTemperature = temp
end

--------------------------------------------------------------
-- REGISTRIERUNG
--------------------------------------------------------------
addModEventListener(REA_engineRealism.new())
