if isClient() then return end

if not TowBarMod then TowBarMod = {} end
TowBarMod.Landtrain = TowBarMod.Landtrain or {}
if TowBarMod.Landtrain._serverTowAttachmentsLoaded then return end
TowBarMod.Landtrain._serverTowAttachmentsLoaded = true

local function log(msg)
    print("[Landtrain][Server] " .. tostring(msg))
end

local function addMissingTowAttachments(script)
    if not script then return 0 end

    local wheelCount = script:getWheelCount()
    local yOffset = -0.5
    if wheelCount > 0 then
        local wheel = script:getWheel(0)
        if wheel and wheel:getOffset() then
            yOffset = wheel:getOffset():y() + 0.1
        end
    end

    local chassis = script:getPhysicsChassisShape()
    if not chassis then return 0 end

    local changed = 0

    if script:getAttachmentById("trailer") == nil then
        local rearAttach = ModelAttachment.new("trailer")
        rearAttach:getOffset():set(0, yOffset, -chassis:z() / 2 - 0.1)
        rearAttach:setZOffset(-1)
        script:addAttachment(rearAttach)
        changed = changed + 1
    end

    if script:getAttachmentById("trailerfront") == nil then
        local frontAttach = ModelAttachment.new("trailerfront")
        frontAttach:getOffset():set(0, yOffset, chassis:z() / 2 + 0.1)
        frontAttach:setZOffset(1)
        script:addAttachment(frontAttach)
        changed = changed + 1
    end

    return changed
end

local function ensureTowAttachmentsServer()
    local sm = getScriptManager()
    if sm == nil then
        log("ScriptManager unavailable; skipping tow attachment bootstrap")
        return
    end

    local scripts = sm:getAllVehicleScripts()
    if scripts == nil then
        log("Vehicle script list unavailable; skipping tow attachment bootstrap")
        return
    end

    local patchedScripts = 0
    local addedAttachments = 0
    for i = 0, scripts:size() - 1 do
        local script = scripts:get(i)
        local added = addMissingTowAttachments(script)
        if added > 0 then
            patchedScripts = patchedScripts + 1
            addedAttachments = addedAttachments + added
        end
    end

    log("Tow attachment bootstrap complete: scripts=" .. tostring(patchedScripts) .. ", attachments=" .. tostring(addedAttachments))
end

Events.OnGameBoot.Add(ensureTowAttachmentsServer)

log("LandtrainTowAttachmentsServer loaded")
