-- Stable, read-only integration boundary for external HUD presentations.
-- AA Damage continues to own DEF gameplay and its default HUD. Consumers only
-- receive freshly detached scalar data and may suppress the legacy visual.

AAHUDPublicAPI = AAHUDPublicAPI or {}
AAHUDPublicAPI.API_VERSION = "1.0"
AAHUDPublicAPI.ownHudVisible = true

local function safe(method, object, ...)
    if type(method) ~= "function" then return nil end
    local ok, value = pcall(method, object, ...)
    return ok and value or nil
end

local function clampRatio(value)
    value = tonumber(value)
    if value == nil then return nil end
    if value < 0 then return 0 end
    if value > 1 then return 1 end
    return value
end

local function vehicleId(vehicle)
    local id = safe(vehicle ~= nil and vehicle.getUniqueId or nil, vehicle)
    if id ~= nil then return tostring(id) end
    if vehicle ~= nil and (vehicle.rootNode ~= nil or vehicle.id ~= nil) then
        return tostring(vehicle.rootNode or vehicle.id)
    end
    return nil
end

function AAHUDPublicAPI:getVehicleHudData(vehicle)
    local spec = type(vehicle)=="table" and vehicle.spec_adblueConsumer or nil
    if type(spec)~="table" or spec.hasAdBlue~=true or spec.fillUnitIndex==nil then
        return {
            available=false, vehicleId=vehicleId(vehicle), adBlueAvailable=false,
            adBlueLevel=nil, adBlueCapacity=nil, adBlueRatio=nil,
            versionToken=self.API_VERSION..":"..tostring(vehicleId(vehicle) or "none")..":unavailable"
        }
    end

    local level=safe(vehicle.getFillUnitFillLevel,vehicle,spec.fillUnitIndex)
    local capacity=safe(vehicle.getFillUnitCapacity,vehicle,spec.fillUnitIndex)
    level=tonumber(level)
    capacity=tonumber(capacity)
    local available=level~=nil and capacity~=nil and capacity>0
    local ratio=available and clampRatio(level/capacity) or nil
    local id=vehicleId(vehicle)
    return {
        available=available,
        vehicleId=id,
        adBlueAvailable=available,
        adBlueLevel=available and level or nil,
        adBlueCapacity=available and capacity or nil,
        adBlueRatio=ratio,
        versionToken=table.concat({self.API_VERSION,tostring(id or "none"),
            available and string.format("%.3f",level) or "-",
            available and string.format("%.3f",capacity) or "-"},":")
    }
end

function AAHUDPublicAPI:setOwnHudVisible(visible)
    self.ownHudVisible=visible~=false
    if self.ownHudVisible~=true and SpeedMeterDisplayExt~=nil then
        SpeedMeterDisplayExt.isPositioningMode=false
        SpeedMeterDisplayExt.isDragging=false
    end
    return self.ownHudVisible
end

function AAHUDPublicAPI:isOwnHudVisible()
    return self.ownHudVisible~=false
end

function AAHUDPublicAPI:reset()
    self.ownHudVisible=true
end
