-- Created by: Black Book
-- Discord: Black Book / Rebel Anarchy
-- Version: 1.0 ( First Release )

local Config = nil
local configLoadSuccess, configResult = pcall(require, "config")

if configLoadSuccess then
    Config = configResult
    print("RebelCore: Configuration file loaded successfully.")
else
    print("RebelCore WARNING: Failed to load config.lua: " .. tostring(configResult))
    print("RebelCore: Using default internal settings.")
    Config = { 
        EnableDebugLogging = false, ModifyAgingData = true, TargetMaxAge = 10000, TargetGrowthAges = { 5, 10, 18, 25, 35, 50, 5000, 10000 }, TargetGrowingStepElement = 244,
        ModifyTimeConfig = true, TargetTimeScaleFast = 10.0, TargetTimeScaleVeryFast = 100.0, TargetMaxTimeScale = 100.0
    }
end

local function DebugPrint(...)
    if Config and Config.EnableDebugLogging then
        local args = {...}
        local formatted_args = {}
        for i, v in ipairs(args) do
            table.insert(formatted_args, tostring(v))
        end
        print("RebelCore DEBUG:", table.concat(formatted_args, "\t")) 
    end
end

local componentsToPrintQueue = {}
local isNotifyRegistered_AgingComp = false; local isLoopStarted = false
local LoadedAgingDataAsset = nil; local LoadedGameConfigAsset = nil 
local triedToLoadAssets = false; local dataAssetModified = false; local timeConfigModified = false 

local function ExecuteDelayedPrint(Component)
    if not triedToLoadAssets then
        triedToLoadAssets = true 
        local loadAgingSuccess, loadedAging = pcall(function() return StaticFindObject("/Game/Data/DataAsset/DA_Aging.DA_Aging") end)
        if loadAgingSuccess and loadedAging and loadedAging:IsValid() and loadedAging:IsA("/Script/BlueUtils.B1AgingDataAsset") then
            LoadedAgingDataAsset = loadedAging; print("RebelCore: Successfully loaded DA_Aging.")
            if Config.ModifyAgingData and not dataAssetModified then
                dataAssetModified = true; print("RebelCore: Applying one-time modifications to loaded DA_Aging...")
                local modifiedSomethingAging = false; local maxAgeTarget = Config.TargetMaxAge; local setAgeSuccess, _ = pcall(function() LoadedAgingDataAsset.CharactersMaxAge = maxAgeTarget end); if setAgeSuccess then print(string.format("   - Set DA_Aging.CharactersMaxAge to: %d (Success)", maxAgeTarget)); modifiedSomethingAging = true else print(string.format("   - FAILED to set DA_Aging.CharactersMaxAge: %s", tostring(_))) end
                local activeGrowthAges = nil; if Config and Config.GrowthAgesPresets and Config.SelectedGrowthAgesPreset and Config.GrowthAgesPresets[Config.SelectedGrowthAgesPreset] then activeGrowthAges = Config.GrowthAgesPresets[Config.SelectedGrowthAgesPreset] else activeGrowthAges = { 5, 10, 18, 25, 35, 50, 70, 90 } end; local newGrowthAges = activeGrowthAges; local setArraySuccess, _ = pcall(function() LoadedAgingDataAsset.GrowthStepChangeAges = newGrowthAges end); if setArraySuccess then print(string.format("   - Attempted to set DA_Aging.GrowthStepChangeAges using Preset '%s' (Assignment OK?)", Config.SelectedGrowthAgesPreset or "DefaultFallback")) modifiedSomethingAging = true else print(string.format("   - FAILED to set DA_Aging.GrowthStepChangeAges: %s", tostring(_))) end
                local maxGrowingStepToChange = Config.TargetGrowingStepElement; local setGrowingStepSuccess, _ = pcall(function() LoadedAgingDataAsset.GrowingStepToChangeContentElement = maxGrowingStepToChange end); if setGrowingStepSuccess then print(string.format("   - Set DA_Aging.GrowingStepToChangeContentElement to: %d (Success)", maxGrowingStepToChange)); modifiedSomethingAging = true else print(string.format("   - FAILED to set DA_Aging.GrowingStepToChangeContentElement: %s", tostring(_))) end
                if modifiedSomethingAging then print("RebelCore: Finished DA_Aging modification attempt.") end
            elseif not Config.ModifyAgingData then print("RebelCore: Skipping DA_Aging modification (disabled in config).") end
        else print("RebelCore WARNING: Failed to load DA_Aging. Result: " .. tostring(loadedAging)) end
        local loadConfigSuccess, loadedConfig = pcall(function() return StaticFindObject("/Game/Data/DataAsset/DA_GameConfig.DA_GameConfig") end)
        if loadConfigSuccess and loadedConfig and loadedConfig:IsValid() and loadedConfig:IsA("/Script/BlueUtils.B1GameConfigDataAsset") then
             LoadedGameConfigAsset = loadedConfig; print("RebelCore: Successfully loaded DA_GameConfig.")
             if Config.ModifyTimeConfig and not timeConfigModified then
                 timeConfigModified = true; print("RebelCore: Applying one-time modifications to loaded DA_GameConfig.Time...")
                 local modifiedSomethingTime = false; local getTimeStructSuccess, timeStruct = pcall(function() return LoadedGameConfigAsset.Time end)
                 if getTimeStructSuccess and timeStruct then
                      local newFastSpeed = Config.TargetTimeScaleFast; local setFastSuccess, _ = pcall(function() timeStruct.TimeScaleFast = newFastSpeed end); if setFastSuccess then print(string.format("   - Set Time.TimeScaleFast to: %s (Success?)", tostring(newFastSpeed))); modifiedSomethingTime = true else print(string.format("   - FAILED to set Time.TimeScaleFast: %s", tostring(_))) end
                      local newVeryFastSpeed = Config.TargetTimeScaleVeryFast; local setVFastSuccess, _ = pcall(function() timeStruct.TimeScaleVeryFast = newVeryFastSpeed end); if setVFastSuccess then print(string.format("   - Set Time.TimeScaleVeryFast to: %s (Success?)", tostring(newVeryFastSpeed))); modifiedSomethingTime = true else print(string.format("   - FAILED to set Time.TimeScaleVeryFast: %s", tostring(_))) end
                      local newMaxSpeed = Config.TargetMaxTimeScale; local setMaxSuccess, _ = pcall(function() timeStruct.MaxTimeScale = newMaxSpeed end); if setMaxSuccess then print(string.format("   - Set Time.MaxTimeScale to: %s (Success?)", tostring(newMaxSpeed))); modifiedSomethingTime = true else print(string.format("   - FAILED to set Time.MaxTimeScale: %s", tostring(_))) end
                 else print("   - FAILED to access Time struct within DA_GameConfig: "..tostring(timeStruct)) end
                 if modifiedSomethingTime then print("RebelCore: Finished DA_GameConfig.Time modification attempt.") end
             elseif not Config.ModifyTimeConfig then print("RebelCore: Skipping DA_GameConfig.Time modification (disabled in config).") end
        else print("RebelCore WARNING: Failed to load DA_GameConfig. Result: " .. tostring(loadedConfig)) end
        print("RebelCore: Finished initial asset loading and modification attempts.")
    end

    local currentSuccess, currentErrMsg = pcall(function() 
        if not Component:IsValid() then print("RebelCore WARNING: Skipping processing for an invalid Component."); return end
        local OwningCharacter = Component:GetOwner(); local OwnerName = OwningCharacter and OwningCharacter:IsValid() and OwningCharacter:GetFullName() or "Invalid/NoOwner"; local CompName = Component:GetFullName() or "InvalidComponent"

        if Config and Config.EnableDebugLogging then
            print("----------------------------------------------------")
            print(string.format("RebelCore: Processing %s", CompName))
            print(string.format("   - Owner: %s", OwnerName))

            if LoadedAgingDataAsset then print("   --- Aging Data Asset Info ---"); local daSuccess, daResult; print(string.format("     (Asset: %s)", LoadedAgingDataAsset:GetFullName())); daSuccess, daResult = pcall(function() return LoadedAgingDataAsset.CharactersMaxAge end); print(string.format("     - CharactersMaxAge = %s", daSuccess and tostring(daResult) or "Err")); daSuccess, daResult = pcall(function() local arr = LoadedAgingDataAsset.GrowthStepChangeAges; if not arr then return "Array nil" end; local size = #(arr or {}); local elements = {}; pcall(function() arr:ForEach(function(i, e) table.insert(elements,tostring(pcall(function() return e:get() end) and e:get() or "GetErr")) end) end); return string.format("{%s}(Size:%d)",table.concat(elements,", "), size) end); print(string.format("     - GrowthStepChangeAges = %s", daSuccess and daResult or "Err")); daSuccess, daResult = pcall(function() return LoadedAgingDataAsset.GrowingStepToChangeContentElement end); print(string.format("     - GrowingStepToChangeContentElement = %s", daSuccess and tostring(daResult) or "Err")); daSuccess, daResult = pcall(function() return #(LoadedAgingDataAsset.MaleDeadAgeWeightInfos or {}) end); print(string.format("     - MaleDeadAgeWeightInfos = (Array Size: %s)", daSuccess and tostring(daResult) or "Err")); daSuccess, daResult = pcall(function() return #(LoadedAgingDataAsset.FemaleDeadAgeWeightInfos or {}) end); print(string.format("     - FemaleDeadAgeWeightInfos = (Array Size: %s)", daSuccess and tostring(daResult) or "Err")); print("   -----------------------------") else print("   --- Aging Data Asset: Not loaded ---") end

            if LoadedGameConfigAsset then print("   --- Game Config Time Struct Info ---"); local structSuccess, timeStruct = pcall(function() return LoadedGameConfigAsset.Time end); if structSuccess and timeStruct then local tsSuccess, tsValue; tsSuccess, tsValue = pcall(function() return timeStruct.TimeScaleNormal end); print(string.format("     - TimeScaleNormal = %s", tsSuccess and tostring(tsValue) or "Err")); tsSuccess, tsValue = pcall(function() return timeStruct.TimeScaleFast end); print(string.format("     - TimeScaleFast = %s", tsSuccess and tostring(tsValue) or "Err")); tsSuccess, tsValue = pcall(function() return timeStruct.TimeScaleVeryFast end); print(string.format("     - TimeScaleVeryFast = %s", tsSuccess and tostring(tsValue) or "Err")); tsSuccess, tsValue = pcall(function() return timeStruct.MaxTimeScale end); print(string.format("     - MaxTimeScale = %s", tsSuccess and tostring(tsValue) or "Err")); else print("     - Error accessing Time Struct") end; print("   ----------------------------------") else print("   --- Game Config Data Asset: Not loaded ---") end

            print("   --- Aging Component Info ---"); local propsToLog = {"LastUpdatedAge", "GrowthStep", "PrevGrowthStep", "bIsActive", "bAutoActivate"}; for _, propName in ipairs(propsToLog) do local propSuccess, value = pcall(function() return Component[propName] end); if propSuccess then print(string.format("   - %s = %s", propName, tostring(value))) else print(string.format("   - Error accessing %s: %s", propName, tostring(value))) end end; print("   ----------------------------")
            print("----------------------------------------------------")
        end
    end) 
    if not currentSuccess then print("RebelCore: Error during ExecuteDelayedPrint pcall execution: " .. tostring(currentErrMsg)) end
end

local function PrintAgingComponentState(Component) if Component == nil then return end; local initiallyValid = false; local checkSuccess, isValidResult = pcall(function() return Component:IsValid() end); if checkSuccess and isValidResult then initiallyValid = true else return end; table.insert(componentsToPrintQueue, Component) end
local function ProcessAgingComponentQueue() if #componentsToPrintQueue > 0 then local itemsToProcess = {}; for i = 1, #componentsToPrintQueue do table.insert(itemsToProcess, componentsToPrintQueue[i]) end; componentsToPrintQueue = {}; for i, componentToPrint in ipairs(itemsToProcess) do pcall(ExecuteDelayedPrint, componentToPrint) end end end
local function OnClientRestart_SetupMonitor(PlayerController) if not isNotifyRegistered_AgingComp then isNotifyRegistered_AgingComp = true; print("RebelCore: ClientRestart/LevelLoad triggered. Setting up NotifyOnNewObject..."); if NotifyOnNewObject then NotifyOnNewObject("/Script/BlueClient.B1AgingComponent", PrintAgingComponentState); print("RebelCore: NotifyOnNewObject registration successful.") else print("RebelCore ERROR: NotifyOnNewObject is nil! Cannot monitor components."); isNotifyRegistered_AgingComp = false; return end end; if not isLoopStarted then if LoopAsync then local intervalMs = 5000; LoopAsync(intervalMs, ProcessAgingComponentQueue); print(string.format("RebelCore: Started LoopAsync to process queue every %d ms.", intervalMs)); isLoopStarted = true else print("RebelCore WARNING: LoopAsync function not found. Cannot start automated queue processing.") end end end
local setupTriggerHookPaths = {'/Script/Engine.PlayerController:ClientRestart', '/Script/Engine.PlayerController:RestartLevel'}; if RegisterHook then local anySetupHookFailed = false; print("RebelCore: Registering setup trigger hooks..."); for _, path in ipairs(setupTriggerHookPaths) do local registered = RegisterHook(path, OnClientRestart_SetupMonitor); if not registered then print(string.format("RebelCore Warning: Failed to register setup trigger hook for %s.", path)) anySetupHookFailed = true end end; if not anySetupHookFailed then print("RebelCore: Aging Component Monitor script loaded. Setup trigger hooks registered successfully.\n") else print("RebelCore: Aging Component Monitor script loaded, but SOME setup trigger hooks FAILED to register.\n") end else print("RebelCore Error: RegisterHook is nil! Cannot register setup trigger hooks.\n") end; print("RebelCore: Main script execution finished.")