--[[
    Disable Default Towing

    Overrides vanilla ISVehicleMenu.doTowingMenu to prevent car-to-car towing.
    Trailers can still be attached normally.

    Use with Better Towing mod to require proper tow trucks for vehicle recovery.

    Trailer detection uses multiple methods:
    1. Script name contains "Trailer" (vanilla + most mods)
    2. Vehicle has no engine part (trailers don't have engines)
    3. Vehicle has no passenger seats (trailers can't be driven)
    4. Trailer attachment has canAttach property (script-level check)
]]

-- Robust trailer detection - checks multiple indicators
local function isActualTrailer(vehicle)
    if not vehicle then return false end

    local script = vehicle:getScript()
    if not script then return false end

    local scriptName = script:getName() or ""

    -- Method 1: Script name contains "Trailer" (case-insensitive)
    if string.match(string.lower(scriptName), "trailer") then
        return true
    end

    -- Method 2: Check if vehicle has no engine (trailers don't have engines)
    local hasEngine = vehicle:getPartById("Engine") ~= nil

    -- Method 3: Check passenger count (trailers have 0 or no passengers)
    local passengerCount = script:getPassengerCount() or 0

    -- Method 4: Check if trailer attachment has canAttach property
    -- This is the most reliable script-level indicator
    local trailerAttachment = script:getAttachmentById("trailer")
    local hasCanAttach = false
    if trailerAttachment then
        -- canAttach property indicates this IS a towable trailer
        local canAttach = trailerAttachment:getCanAttach()
        hasCanAttach = canAttach ~= nil and canAttach ~= ""
    end

    -- If it has canAttach on trailer attachment, it's definitely a trailer
    if hasCanAttach then
        return true
    end

    -- If no engine AND no passengers, very likely a trailer
    if not hasEngine and passengerCount == 0 then
        return true
    end

    return false
end

-- Keep burnt vehicle detection
local function isBurntVehicle(vehicle)
    if not vehicle then return false end
    return string.contains(vehicle:getScriptName(), "Burnt")
end

-- Helper to add towing menu option
local function addTowOption(playerObj, menu, vehicleA, vehicleB, attachmentA, attachmentB)
    local aName = ISVehicleMenu.getVehicleDisplayName(vehicleA)
    local bName = ISVehicleMenu.getVehicleDisplayName(vehicleB)
    local text = getText("ContextMenu_Vehicle_AttachTrailer", bName, aName)
    menu:addSlice(text, getTexture("media/ui/ZoomIn.png"), ISVehicleMenu.onAttachTrailer, playerObj, vehicleA, attachmentA, attachmentB)
end

-- Find a towable vehicle nearby - ONLY if it's a trailer
local function findTrailerNear(square, vehicle, attachmentA, attachmentB)
    local vehicleB = ISVehicleTrailerUtils.getTowableVehicleNear(square, vehicle, attachmentA, attachmentB)
    if vehicleB and isActualTrailer(vehicleB) then
        return vehicleB
    end
    return nil
end

-- Override doTowingMenu to only allow trailer attachments
ISVehicleMenu.doTowingMenu = function(playerObj, vehicle, menu)
    -- Always allow detaching (both trailers and any existing towed vehicles)
    if vehicle:getVehicleTowing() then
        local bName = ISVehicleMenu.getVehicleDisplayName(vehicle:getVehicleTowing())
        menu:addSlice(getText("ContextMenu_Vehicle_DetachTrailer", bName), getTexture("media/ui/ZoomOut.png"), ISVehicleMenu.onDetachTrailer, playerObj, vehicle, vehicle:getTowAttachmentSelf())
        return
    end

    if vehicle:getVehicleTowedBy() then
        local aName = ISVehicleMenu.getVehicleDisplayName(vehicle)
        menu:addSlice(getText("ContextMenu_Vehicle_DetachTrailer", aName), getTexture("media/ui/ZoomOut.png"), ISVehicleMenu.onDetachTrailer, playerObj, vehicle:getVehicleTowedBy(), vehicle:getVehicleTowedBy():getTowAttachmentSelf())
        return
    end

    -- Check server option for trailer towing (respect server settings)
    if isClient() and getServerOptions():getBoolean("DisableTrailerTowing") then
        return
    end

    -- Only allow attaching TRAILERS, not regular vehicles
    -- The current vehicle being interacted with can be:
    -- 1. A trailer looking for a towing vehicle
    -- 2. A regular vehicle looking for a trailer to tow

    if isActualTrailer(vehicle) then
        -- Current vehicle IS a trailer - find a vehicle to tow it
        local attachmentA, attachmentB = "trailer", "trailer"
        local vehicleB = ISVehicleTrailerUtils.getTowableVehicleNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)

        if not vehicleB then
            attachmentA, attachmentB = "trailer", "trailerfront"
            vehicleB = ISVehicleTrailerUtils.getTowableVehicleNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)
        end

        if vehicleB and not isActualTrailer(vehicleB) then
            -- Found a regular vehicle that can tow this trailer
            addTowOption(playerObj, menu, vehicleB, vehicle, attachmentB, attachmentA)
        end
    else
        -- Current vehicle is NOT a trailer - look for trailers to tow
        -- Try different attachment combinations
        local attachmentA, attachmentB = "trailer", "trailer"
        local trailerB = findTrailerNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)

        if not trailerB then
            attachmentA, attachmentB = "trailer", "trailerfront"
            trailerB = findTrailerNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)
        end

        if not trailerB then
            attachmentA, attachmentB = "trailerfront", "trailer"
            trailerB = findTrailerNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)
        end

        if not trailerB then
            attachmentA, attachmentB = "trailerfront", "trailerfront"
            trailerB = findTrailerNear(vehicle:getSquare(), vehicle, attachmentA, attachmentB)
        end

        if trailerB then
            addTowOption(playerObj, menu, vehicle, trailerB, attachmentA, attachmentB)
        end
    end
end
