-- ⚠️ RISKY AI LOCK SCRIPT (FINAL - COMPLETE)
if __RiskyAI_Installed then return end
local ignoredTypes = {
    ["scar_villager"] = true,
    ["scar_monk"] = true,
    ["scar_scout"] = true,
    ["scar_fishing_boat"] = true,
    ["scar_shinobi"] = true
}

-- VILLAGER SPAM REWARD SYSTEM
function VillagerSpamReward(aiPlayer, pbg, productionGroupID)
    return 5000.0  -- Very high priority for villager spam
end

function ScoringFunctions_Gatherer(aiPlayer)
    local result = {
        AIProductionScoring_LuaScoringFunction(aiPlayer, VillagerSpamReward),
        AIProductionScoring_HasProductionQueue(aiPlayer),
        AIProductionScoring_TimeToAcquire(aiPlayer, 300.0, true, false, true),
        AIProductionScoring_MultipleProduced(aiPlayer, 10.0),  -- Increased from 5.0
        AIProductionScoring_PopulationPercentage(aiPlayer, 5.0, 3.0, true, true),  -- Increased
        AIProductionScoring_StrategicIntention(aiPlayer, { ["economy"] = 3.0 }),  -- Increased
    }
    return result
end

function InitAI_EconOnly()
    local player = Game_GetLocalPlayer()
    Game_AIControlLocalPlayer()
    AI_Enable(player, true)
    AI_SetDifficulty(player, 3)
    AI_DisableAllEconomyOverrides(player)
    AI_EnableEconomyOverride(player, "balanced", true)
    
    local lockedSquads = {}
    
    function OnUnitSpawn(event)
        local success, err = pcall(function()
            local entity = event.entity
            if not entity then return end
            
            -- Skip buildings
            if type(Entity_IsBuilding) == "function" then
                local okB, isBuilding = pcall(Entity_IsBuilding, entity)
                if okB and isBuilding then return end
            end
            
            local okSquad, squad = pcall(Entity_GetSquad, entity)
            if not okSquad or not squad then return end
            
            -- Skip dead/dying squads
            if type(Squad_IsAlive) == "function" then
                local okAlive, alive = pcall(Squad_IsAlive, squad)
                if not okAlive or not alive then return end
            end
            
            local okID, squadID = pcall(Squad_GetID, squad)
            if not okID or not squadID or squadID < 0 then return end
            
            if lockedSquads[squadID] then return end
            
            for unitType, _ in pairs(ignoredTypes) do
                local okType, isType = pcall(Squad_IsOfType, squad, unitType)
                if okType and isType then
                    return
                end
            end
            
            local okLock = pcall(AI_LockSquad, player, squad)
            if okLock then
                lockedSquads[squadID] = true
            end
        end)
        
        if not success then
            UI_ShowMessage("OnUnitSpawn error: " .. tostring(err))
        end
    end
    
    Rule_AddPlayerEvent(OnUnitSpawn, player, GE_EntitySpawn)
end
Rule_AddOneShot(InitAI_EconOnly)
__RiskyAI_Installed = true