-- Fragile All Aircraft Script
-- Makes all aircraft explode when damage arguments reach certain thresholds
-- Based on the Fw190 fragility script but applied universally

local aircraft_exploded = {}

-- Settings
local DAMAGE_THRESHOLD_MIN = 0.419
local DAMAGE_THRESHOLD_MAX = 1.0
local EXPLOSION_SIZE = 25
local CHECK_INTERVAL = 0.1  -- seconds between damage checks
local ENABLE_DESTRUCTION = false  -- set to true if you want aircraft to disappear after explosion

local function inDamageRange(val)
    return val and val >= DAMAGE_THRESHOLD_MIN and val <= DAMAGE_THRESHOLD_MAX
end

local function checkAircraftExplosion(unit)
    if not unit or not unit:isExist() then return end
    
    local name = unit:getName()
    if aircraft_exploded[name] then return end
    
    -- Check various damage arguments that typically indicate critical damage
    local arg215 = unit:getDrawArgumentValue(215)  -- Wing/structural damage
    local arg225 = unit:getDrawArgumentValue(225)  -- Engine/fuel damage  
    local arg298 = unit:getDrawArgumentValue(298)  -- Critical component damage
    local arg233 = unit:getDrawArgumentValue(233)  -- Additional damage state
    local arg267 = unit:getDrawArgumentValue(267)  -- Additional damage state
    
    -- Check if any critical damage arguments are in the danger zone
    if inDamageRange(arg215) or inDamageRange(arg225) or inDamageRange(arg298) or 
       inDamageRange(arg233) or inDamageRange(arg267) then
        
        local pos = unit:getPoint()
        local typeName = unit:getTypeName() or "Unknown"
        
        -- Create explosion effect at aircraft position
        trigger.action.explosion(pos, EXPLOSION_SIZE)
        
        -- Log the explosion
        env.info("Fragile Aircraft: " .. typeName .. " (" .. name .. ") exploded due to damage")
        env.info("Damage args: 215=" .. (arg215 or 0) .. ", 225=" .. (arg225 or 0) .. 
                ", 298=" .. (arg298 or 0) .. ", 233=" .. (arg233 or 0) .. ", 267=" .. (arg267 or 0))
        
        -- Mark as exploded to prevent repeated explosions
        aircraft_exploded[name] = true
        
        -- Optional: Destroy the aircraft completely (uncomment if desired)
        if ENABLE_DESTRUCTION then
            timer.scheduleFunction(function()
                if unit and unit:isExist() then
                    unit:destroy()
                end
            end, {}, timer.getTime() + 0.5)  -- Small delay for visual effect
        end
    end
end

local function scanAllAircraft()
    -- Clean up exploded aircraft list periodically to prevent memory bloat
    if math.random() < 0.01 then  -- 1% chance each scan cycle
        for name, _ in pairs(aircraft_exploded) do
            local unit = Unit.getByName(name)
            if not unit or not unit:isExist() then
                aircraft_exploded[name] = nil
            end
        end
    end
    
    -- Scan all coalitions for aircraft
    for coalitionId = 0, 2 do  -- Neutral = 0, Red = 1, Blue = 2
        local groups = coalition.getGroups(coalitionId, Group.Category.AIRPLANE)
        if groups then
            for _, group in ipairs(groups) do
                if group:isExist() then
                    local units = group:getUnits()
                    if units then
                        for _, unit in ipairs(units) do
                            checkAircraftExplosion(unit)
                        end
                    end
                end
            end
        end
    end
    
    return timer.getTime() + CHECK_INTERVAL
end

-- Alternative version using MIST library (if available)
local function scanAllAircraft_MIST()
    if not mist then
        env.error("Fragile Aircraft: MIST library not found, falling back to standard version")
        return scanAllAircraft()
    end
    
    -- Clean up exploded list periodically
    if math.random() < 0.01 then
        for name, _ in pairs(aircraft_exploded) do
            local unit = Unit.getByName(name)
            if not unit or not unit:isExist() then
                aircraft_exploded[name] = nil
            end
        end
    end
    
    -- Use MIST to get all aircraft
    local allPlanes = mist.makeUnitTable({"[all][plane]"})
    
    for _, name in ipairs(allPlanes) do
        local unit = Unit.getByName(name)
        checkAircraftExplosion(unit)
    end
    
    return timer.getTime() + CHECK_INTERVAL
end

-- Function to manually set aircraft as fragile (optional enhancement)
function setAircraftFragile(unitName, fragile)
    if fragile == false then
        aircraft_exploded[unitName] = true  -- Mark as "exploded" to exempt from checks
    else
        aircraft_exploded[unitName] = nil   -- Remove from exploded list to re-enable checks
    end
end

-- Function to adjust damage threshold (optional enhancement)
function setDamageThreshold(min, max)
    DAMAGE_THRESHOLD_MIN = min or 0.419
    DAMAGE_THRESHOLD_MAX = max or 1.0
    env.info("Fragile Aircraft: Damage threshold set to " .. DAMAGE_THRESHOLD_MIN .. " - " .. DAMAGE_THRESHOLD_MAX)
end

-- Start monitoring
-- Choose one version based on whether you have MIST loaded

-- Standard version (works without MIST):
timer.scheduleFunction(scanAllAircraft, {}, timer.getTime() + 1)

-- MIST version (uncomment if you have MIST loaded):
-- timer.scheduleFunction(scanAllAircraft_MIST, {}, timer.getTime() + 1)

env.info("Fragile All Aircraft Script: Monitoring all aircraft for damage - explosions enabled!")
env.info("Settings: Damage threshold " .. DAMAGE_THRESHOLD_MIN .. "-" .. DAMAGE_THRESHOLD_MAX .. 
        ", Explosion size " .. EXPLOSION_SIZE .. ", Check interval " .. CHECK_INTERVAL .. "s")