-- Fix 1: Base game bug in AIAutomaticSteering:onWriteUpdateStream
-- When foldable is added to a tractor-based vehicle type, the first
-- multiplayer update stream fires while steeringFieldCourse is nil,
-- causing a nil dereference crash.

local function fix_onWriteUpdateStream(self, streamId, connection, dirtyMask)
    local spec = self.spec_aiAutomaticSteering
    if not connection:getIsServer() then
        if streamWriteBool(streamId, bit32.band(dirtyMask, spec.dirtyFlag) ~= 0 and spec.steeringFieldCourse ~= nil) then
            spec.steeringFieldCourse:writeSegmentStatesToStream(streamId, connection)
        end
    end
end

-- Fix 2: Base game bug in Drivable:onReadUpdateStream
-- Missing 'local spec = self.spec_drivable' means axisSide is never stored
-- in spec_drivable on the server, so rotatedTime stays 0.
--
-- On the client, axisSide is intentionally NOT stored from the server's stream.
-- The server runs Drivable.onUpdate with axisSteer=0 (no local player), so it
-- auto-returns its spec.axisSide toward 0 and echoes back this reduced value.
-- Storing it would corrupt the client's locally-built axisSide and cause slow
-- steering. The client's Drivable.onUpdate correctly builds axisSide from player
-- input and must not be overwritten.

local function fix_drivable_onReadUpdateStream(self, streamId, timestamp, connection)
    local spec = self.spec_drivable
    local hasDirty = streamReadBool(streamId)
    if hasDirty then
        spec.axisForward = streamReadUIntN(streamId, 10) / 1023 * 2 - 1
        if math.abs(spec.axisForward) < 0.00099 then
            spec.axisForward = 0
        end
        local axisSideStream = streamReadUIntN(streamId, 10) / 1023 * 2 - 1
        if math.abs(axisSideStream) < 0.00099 then
            axisSideStream = 0
        end
        -- Only store on server (reading the client's sent value for physics).
        -- On client, discard the server's auto-returned value to preserve local input.
        if self.isServer then
            spec.axisSide = axisSideStream
        end
        spec.doHandbrake = streamReadBool(streamId)
        spec.idleTurningActive = streamReadBool(streamId)
    end
end

local function install()
    if AIAutomaticSteering ~= nil then
        AIAutomaticSteering.onWriteUpdateStream = fix_onWriteUpdateStream
        print("[9RX Fix] Fix 1 APPLIED: AIAutomaticSteering.onWriteUpdateStream patched")
    else
        print("[9RX Fix] Fix 1 SKIPPED: AIAutomaticSteering is nil")
    end

    if Drivable ~= nil then
        Drivable.onReadUpdateStream = fix_drivable_onReadUpdateStream
        print("[9RX Fix] Fix 2 APPLIED: Drivable.onReadUpdateStream patched")
    else
        print("[9RX Fix] Fix 2 SKIPPED: Drivable is nil")
    end
end

install()
