Decompiled source of Dynamic Quota Cap v1.0.2

BepInEx/plugins/dynamicquotacap/DynamicQuotaCap.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DynamicQuotaCap.Configuration;
using DynamicQuotaCap.Patches;
using DynamicQuotaCap.Services;
using HarmonyLib;
using LethalConstellations.PluginCore;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DynamicQuotaCap
{
	[BepInPlugin("com.example.dynamicquotacap", "Dynamic Quota Cap", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigManager _configManager;

		private LoggingService _loggingService;

		private QuotaCapService _quotaCapService;

		private ConstellationConfigGenerator _constellationConfigGenerator;

		private void Awake()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			_configManager = new ConfigManager(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
			_loggingService = new LoggingService(((BaseUnityPlugin)this).Logger, _configManager);
			_loggingService.LogInfo("Initializing Dynamic Quota Cap plugin");
			try
			{
				_configManager.LoadConfiguration();
				_quotaCapService = new QuotaCapService(_configManager, _loggingService);
				_constellationConfigGenerator = new ConstellationConfigGenerator(_configManager, ((BaseUnityPlugin)this).Logger);
				TimeOfDayPatch.Initialize(_quotaCapService, _loggingService);
				if (!TimeOfDayPatch.ValidatePatchPrerequisites())
				{
					_loggingService.LogError("Failed to validate patch prerequisites. Some functionality may not work.");
				}
				_harmony = new Harmony("com.example.dynamicquotacap");
				_harmony.PatchAll();
				_loggingService.LogInfo("Harmony patches applied");
				GenerateConstellationConfigs();
				_loggingService.LogInfo("Dynamic Quota Cap plugin initialized successfully");
			}
			catch (Exception ex)
			{
				_loggingService.LogError("Failed to initialize plugin: " + ex.Message, ex);
			}
		}

		private void GenerateConstellationConfigs()
		{
			try
			{
				_loggingService.LogMethodStart("GenerateConstellationConfigs");
				bool flag = _constellationConfigGenerator.GenerateConstellationConfigs();
				if (flag)
				{
					_loggingService.LogConfigGeneration(_configManager.ConstellationCaps.Count, success: true);
				}
				else
				{
					_loggingService.LogConfigGeneration(_configManager.ConstellationCaps.Count, success: false, "Initial generation failed, retry may be attempted");
					if (_constellationConfigGenerator.CanRetry())
					{
						_loggingService.LogInfo("Attempting immediate retry for constellation config generation");
						flag = _constellationConfigGenerator.ImmediateRetry();
						if (flag)
						{
							_loggingService.LogConfigGeneration(_configManager.ConstellationCaps.Count, success: true);
						}
						else
						{
							_loggingService.LogError("Failed to generate constellation configs after retry");
						}
					}
				}
				_loggingService.LogMethodEnd("GenerateConstellationConfigs", flag);
			}
			catch (Exception ex)
			{
				_loggingService.LogError("Error in GenerateConstellationConfigs: " + ex.Message, ex);
			}
		}

		public void GenerateConfigs()
		{
			GenerateConstellationConfigs();
		}

		public ConfigManager GetConfigManager()
		{
			return _configManager;
		}

		public QuotaCapService GetQuotaCapService()
		{
			return _quotaCapService;
		}

		public LoggingService GetLoggingService()
		{
			return _loggingService;
		}

		public ConstellationConfigGenerator GetConstellationConfigGenerator()
		{
			return _constellationConfigGenerator;
		}

		private void OnDestroy()
		{
			try
			{
				_loggingService?.LogInfo("Dynamic Quota Cap plugin shutting down");
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				_configManager?.SaveConfiguration();
				_loggingService?.LogInfo("Dynamic Quota Cap plugin shutdown complete");
			}
			catch (Exception ex)
			{
				ManualLogSource logger = ((BaseUnityPlugin)this).Logger;
				if (logger != null)
				{
					logger.LogError((object)("Error during plugin shutdown: " + ex.Message));
				}
			}
		}
	}
}
namespace DynamicQuotaCap.Services
{
	public class LoggingService
	{
		private readonly ManualLogSource _logger;

		private readonly ConfigManager _configManager;

		public LoggingService(ManualLogSource logger, ConfigManager configManager)
		{
			_logger = logger ?? throw new ArgumentNullException("logger");
			_configManager = configManager ?? throw new ArgumentNullException("configManager");
		}

		public void LogDebug(string message)
		{
			ConfigManager configManager = _configManager;
			if (configManager != null && (configManager.EnableDebug?.Value).GetValueOrDefault())
			{
				_logger.LogInfo((object)("[DEBUG] " + message));
			}
		}

		public void LogInfo(string message)
		{
			_logger.LogInfo((object)message);
		}

		public void LogWarning(string message)
		{
			_logger.LogWarning((object)message);
		}

		public void LogError(string message)
		{
			_logger.LogError((object)message);
		}

		public void LogError(string message, Exception exception)
		{
			_logger.LogError((object)(message + ": " + exception.Message));
			if (exception.InnerException != null)
			{
				_logger.LogError((object)("Inner exception: " + exception.InnerException.Message));
			}
		}

		public void LogStructured(LogLevel level, string category, string message, object data = null)
		{
			string text = "[" + category + "] " + message;
			if (data != null)
			{
				text += $" | Data: {data}";
			}
			switch (level)
			{
			case LogLevel.Debug:
				LogDebug(text);
				break;
			case LogLevel.Info:
				LogInfo(text);
				break;
			case LogLevel.Warning:
				LogWarning(text);
				break;
			case LogLevel.Error:
				LogError(text);
				break;
			case LogLevel.Fatal:
				_logger.LogFatal((object)text);
				break;
			default:
				LogInfo(text);
				break;
			}
		}

		public void LogMethodStart(string methodName, object parameters = null)
		{
			string text = "Starting " + methodName;
			if (parameters != null)
			{
				text += $" with parameters: {parameters}";
			}
			LogDebug(text);
		}

		public void LogMethodEnd(string methodName, object result = null)
		{
			string text = "Finished " + methodName;
			if (result != null)
			{
				text += $" with result: {result}";
			}
			LogDebug(text);
		}

		public void LogQuotaCapApplication(string constellation, int originalQuota, int newQuota, int capValue, bool capEnabled)
		{
			if (!capEnabled)
			{
				LogDebug($"Quota cap disabled for constellation '{constellation}'. Original quota: {originalQuota}");
			}
			else if (capValue == -1)
			{
				LogDebug($"Quota cap set to disabled (-1) for constellation '{constellation}'. Original quota: {originalQuota}");
			}
			else if (originalQuota > capValue)
			{
				LogInfo($"Quota capped for constellation '{constellation}': {originalQuota} -> {newQuota} (cap: {capValue})");
			}
			else
			{
				LogDebug($"Quota within cap for constellation '{constellation}': {originalQuota} (cap: {capValue})");
			}
		}

		public void LogConfigGeneration(int constellationCount, bool success, string errorMessage = null)
		{
			if (success)
			{
				LogInfo($"Configuration generation completed successfully for {constellationCount} constellations");
				return;
			}
			LogError($"Configuration generation failed for {constellationCount} constellations");
			if (!string.IsNullOrEmpty(errorMessage))
			{
				LogError("Error details: " + errorMessage);
			}
		}

		public void LogPatchApplication(string patchName, bool success, string errorMessage = null)
		{
			if (success)
			{
				LogInfo("Patch '" + patchName + "' applied successfully");
				return;
			}
			LogError("Patch '" + patchName + "' failed to apply");
			if (!string.IsNullOrEmpty(errorMessage))
			{
				LogError("Patch error details: " + errorMessage);
			}
		}
	}
	public enum LogLevel
	{
		Debug,
		Info,
		Warning,
		Error,
		Fatal
	}
	public class QuotaCapService
	{
		private readonly ConfigManager _configManager;

		private readonly LoggingService _loggingService;

		public QuotaCapService(ConfigManager configManager, LoggingService loggingService)
		{
			_configManager = configManager ?? throw new ArgumentNullException("configManager");
			_loggingService = loggingService ?? throw new ArgumentNullException("loggingService");
		}

		public int CalculateQuotaCap(string constellation, int currentQuota)
		{
			_loggingService.LogMethodStart("CalculateQuotaCap", new { constellation, currentQuota });
			try
			{
				if (string.IsNullOrEmpty(constellation))
				{
					_loggingService.LogDebug("Not in any constellation, skipping quota cap");
					_loggingService.LogMethodEnd("CalculateQuotaCap", currentQuota);
					return currentQuota;
				}
				if (_configManager.ConstellationCaps.Count == 0)
				{
					_loggingService.LogDebug("No constellation configs generated yet, skipping quota cap");
					_loggingService.LogMethodEnd("CalculateQuotaCap", currentQuota);
					return currentQuota;
				}
				int constellationCap = GetConstellationCap(constellation);
				bool flag = IsQuotaCapEnabled(constellation);
				_loggingService.LogDebug($"Constellation '{constellation}' - Cap: {constellationCap}, Enabled: {flag}");
				int num = ApplyQuotaCapLogic(currentQuota, constellationCap, flag, constellation);
				_loggingService.LogQuotaCapApplication(constellation, currentQuota, num, constellationCap, flag);
				_loggingService.LogMethodEnd("CalculateQuotaCap", num);
				return num;
			}
			catch (Exception exception)
			{
				_loggingService.LogError("Error calculating quota cap for constellation '" + constellation + "'", exception);
				_loggingService.LogMethodEnd("CalculateQuotaCap", currentQuota);
				return currentQuota;
			}
		}

		public int GetConstellationCap(string constellation)
		{
			try
			{
				if (_configManager.ConstellationCaps.TryGetValue(constellation, out var value))
				{
					return value.Value;
				}
				_loggingService.LogDebug("No specific config found for constellation '" + constellation + "', using default cap");
				return GetDefaultQuotaCap();
			}
			catch (Exception exception)
			{
				_loggingService.LogError("Error getting constellation cap for '" + constellation + "'", exception);
				return GetDefaultQuotaCap();
			}
		}

		public bool IsQuotaCapEnabled(string constellation)
		{
			try
			{
				if (_configManager.ConstellationCapEnabled.TryGetValue(constellation, out var value))
				{
					return value.Value;
				}
				_loggingService.LogDebug("No enabled config found for constellation '" + constellation + "', defaulting to enabled");
				return true;
			}
			catch (Exception exception)
			{
				_loggingService.LogError("Error checking if quota cap is enabled for constellation '" + constellation + "'", exception);
				return true;
			}
		}

		public int GetDefaultQuotaCap()
		{
			return 4000;
		}

		public bool ValidateQuotaValue(int quota)
		{
			try
			{
				if (quota == -1)
				{
					return true;
				}
				if (quota < 0)
				{
					_loggingService.LogWarning($"Invalid quota value detected: {quota}. Quota should be non-negative.");
					return false;
				}
				if (quota > 1000000)
				{
					_loggingService.LogWarning($"Quota value {quota} seems unusually high. Consider reviewing configuration.");
					return true;
				}
				return true;
			}
			catch (Exception exception)
			{
				_loggingService.LogError($"Error validating quota value: {quota}", exception);
				return false;
			}
		}

		private int ApplyQuotaCapLogic(int currentQuota, int cap, bool enabled, string constellation)
		{
			if (!enabled)
			{
				_loggingService.LogDebug("Quota cap disabled for constellation '" + constellation + "'");
				return currentQuota;
			}
			if (cap == -1)
			{
				_loggingService.LogDebug("Quota cap disabled (-1) for constellation '" + constellation + "'");
				return currentQuota;
			}
			if (!ValidateQuotaValue(cap))
			{
				_loggingService.LogWarning($"Invalid cap value {cap} for constellation '{constellation}', using default");
				cap = GetDefaultQuotaCap();
			}
			if (currentQuota > cap)
			{
				_loggingService.LogDebug($"Quota ({currentQuota}) exceeds cap ({cap}) for constellation '{constellation}', applying cap");
				return cap;
			}
			_loggingService.LogDebug($"Quota ({currentQuota}) is within cap ({cap}) for constellation '{constellation}'");
			return currentQuota;
		}

		public Dictionary<string, (int Cap, bool Enabled)> GetQuotaCapStatus()
		{
			Dictionary<string, (int, bool)> dictionary = new Dictionary<string, (int, bool)>();
			try
			{
				foreach (string key in _configManager.ConstellationCaps.Keys)
				{
					int constellationCap = GetConstellationCap(key);
					bool item = IsQuotaCapEnabled(key);
					dictionary[key] = (constellationCap, item);
				}
			}
			catch (Exception exception)
			{
				_loggingService.LogError("Error getting quota cap status", exception);
			}
			return dictionary;
		}

		public bool ResetAllQuotaCapsToDefaults()
		{
			try
			{
				_loggingService.LogInfo("Resetting all quota caps to default values");
				foreach (string key in _configManager.ConstellationCaps.Keys)
				{
					if (_configManager.ConstellationCaps.TryGetValue(key, out var value))
					{
						value.Value = 4000;
						_loggingService.LogDebug($"Reset cap for constellation '{key}' to {4000}");
					}
					if (_configManager.ConstellationCapEnabled.TryGetValue(key, out var value2))
					{
						value2.Value = true;
						_loggingService.LogDebug("Reset enabled state for constellation '" + key + "' to true");
					}
				}
				_configManager.SaveConfiguration();
				_loggingService.LogInfo("All quota caps reset to default values successfully");
				return true;
			}
			catch (Exception exception)
			{
				_loggingService.LogError("Error resetting quota caps to defaults", exception);
				return false;
			}
		}
	}
}
namespace DynamicQuotaCap.Patches
{
	public static class PatchConstants
	{
		public static class Defaults
		{
			public const int PatchRetryDelayMs = 1000;

			public const int MaxPatchRetries = 3;

			public const int PatchTimeoutMs = 5000;
		}

		public static class ErrorMessages
		{
			public const string TimeOfDayClassNotFound = "TimeOfDay class not found for patching";

			public const string SetNewProfitQuotaMethodNotFound = "SetNewProfitQuota method not found in TimeOfDay class";

			public const string PatchApplicationFailed = "Failed to apply TimeOfDay patch";

			public const string PatchAlreadyApplied = "TimeOfDay patch is already applied";

			public const string QuotaCapServiceNotAvailable = "QuotaCapService is not available for patch execution";
		}

		public static class LogCategories
		{
			public const string PatchApplication = "PatchApplication";

			public const string PatchExecution = "PatchExecution";

			public const string PatchError = "PatchError";

			public const string QuotaCap = "QuotaCap";
		}

		public static class Parameters
		{
			public const string ProfitQuota = "profitQuota";

			public const string ProfitQuotaField = "___profitQuota";
		}

		public const string TimeOfDaySetNewProfitQuotaMethod = "SetNewProfitQuota";

		public const string TimeOfDayClassName = "TimeOfDay";

		public const string TimeOfDayPatchId = "com.example.dynamicquotacap.timedofday.patch";

		public const string TimeOfDayPatchDescription = "Applies quota cap logic to profit quota setting";
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		private static QuotaCapService _quotaCapService;

		private static LoggingService _loggingService;

		public static void Initialize(QuotaCapService quotaCapService, LoggingService loggingService)
		{
			_quotaCapService = quotaCapService ?? throw new ArgumentNullException("quotaCapService");
			_loggingService = loggingService ?? throw new ArgumentNullException("loggingService");
			_loggingService.LogInfo("TimeOfDayPatch initialized with services");
		}

		[HarmonyPatch("SetNewProfitQuota")]
		[HarmonyPostfix]
		private static void SetNewProfitQuotaPostfix(ref int ___profitQuota)
		{
			try
			{
				if (_quotaCapService == null || _loggingService == null)
				{
					Console.WriteLine("[DynamicQuotaCap] QuotaCapService is not available for patch execution");
					return;
				}
				_loggingService.LogMethodStart("SetNewProfitQuotaPostfix", new
				{
					originalQuota = ___profitQuota
				});
				string currentConstellation = Collections.CurrentConstellation;
				_loggingService.LogDebug($"Applying quota cap logic - Current constellation: '{currentConstellation}', New quota: {___profitQuota}");
				int num = _quotaCapService.CalculateQuotaCap(currentConstellation, ___profitQuota);
				if (num != ___profitQuota)
				{
					_loggingService.LogInfo($"Quota modified by patch: {___profitQuota} -> {num}");
					___profitQuota = num;
				}
				_loggingService.LogMethodEnd("SetNewProfitQuotaPostfix", ___profitQuota);
			}
			catch (Exception ex)
			{
				string text = "Exception in TimeOfDayPatch: " + ex.Message;
				Console.WriteLine("[DynamicQuotaCap] " + text);
				_loggingService?.LogError(text, ex);
				if (ex.InnerException != null)
				{
					Console.WriteLine("[DynamicQuotaCap] Inner exception: " + ex.InnerException.Message);
					_loggingService?.LogError("Inner exception in TimeOfDayPatch: " + ex.InnerException.Message, ex.InnerException);
				}
			}
		}

		public static bool IsPatchInitialized()
		{
			return _quotaCapService != null && _loggingService != null;
		}

		public static string GetCurrentConstellationForDebug()
		{
			try
			{
				return Collections.CurrentConstellation ?? "Unknown";
			}
			catch
			{
				return "Error";
			}
		}

		public static bool ValidatePatchPrerequisites()
		{
			try
			{
				Type typeFromHandle = typeof(TimeOfDay);
				if (typeFromHandle == null)
				{
					Console.WriteLine("[DynamicQuotaCap] TimeOfDay class not found for patching");
					return false;
				}
				MethodInfo method = typeFromHandle.GetMethod("SetNewProfitQuota");
				if (method == null)
				{
					Console.WriteLine("[DynamicQuotaCap] SetNewProfitQuota method not found in TimeOfDay class");
					return false;
				}
				Type typeFromHandle2 = typeof(Collections);
				if (typeFromHandle2 == null)
				{
					Console.WriteLine("[DynamicQuotaCap] LethalConstellations.Collections not found");
					return false;
				}
				PropertyInfo property = typeFromHandle2.GetProperty("CurrentConstellation");
				if (property == null)
				{
					Console.WriteLine("[DynamicQuotaCap] CurrentConstellation property not found in LethalConstellations.Collections");
					return false;
				}
				_loggingService?.LogInfo("TimeOfDay patch prerequisites validated successfully");
				return true;
			}
			catch (Exception ex)
			{
				Console.WriteLine("[DynamicQuotaCap] Error validating patch prerequisites: " + ex.Message);
				_loggingService?.LogError("Error validating patch prerequisites: " + ex.Message, ex);
				return false;
			}
		}

		public static bool ApplyPatchManually(Harmony harmony)
		{
			try
			{
				if (!ValidatePatchPrerequisites())
				{
					return false;
				}
				if (!IsPatchInitialized())
				{
					Console.WriteLine("[DynamicQuotaCap] Cannot apply patch: services not initialized");
					return false;
				}
				_loggingService?.LogPatchApplication("com.example.dynamicquotacap.timedofday.patch", success: true);
				return true;
			}
			catch (Exception ex)
			{
				Console.WriteLine("[DynamicQuotaCap] Failed to apply TimeOfDay patch: " + ex.Message);
				_loggingService?.LogError("Failed to apply TimeOfDay patch: " + ex.Message, ex);
				return false;
			}
		}
	}
}
namespace DynamicQuotaCap.Configuration
{
	public static class ConfigConstants
	{
		public static class Sections
		{
			public const string General = "General";

			public const string QuotaCaps = "Quota Caps";

			public const string QuotaCapToggles = "Quota Cap Toggles";
		}

		public static class Keys
		{
			public const string EnableDebug = "EnableDebug";

			public const string ConstellationCapFormat = "{0}_Cap";

			public const string ConstellationEnabledFormat = "{0}_Enabled";
		}

		public static class Descriptions
		{
			public const string EnableDebug = "Toggle the debug stuff";

			public const string ConstellationCap = "Quota cap for {0} {1}";

			public const string ConstellationEnabled = "Enable quota cap for {0} {1}";
		}

		public static class Files
		{
			public const string LethalConstellationsMainConfig = "com.github.darmuh.LethalConstellations.cfg";

			public const string LethalConstellationsGeneratedConfig = "LethalConstellations_Generated.cfg";

			public const string ConstellationWordLineFormat = "ConstellationWord = ";
		}

		public const bool DefaultDebugEnabled = true;

		public const int DefaultQuotaCap = 4000;

		public const int DisabledQuotaCapValue = -1;

		public const string DefaultConstellationWord = "Constellation";
	}
	public class ConfigManager
	{
		private readonly ConfigFile _configFile;

		private readonly ManualLogSource _logger;

		private bool _saveOnConfigSet = true;

		public Dictionary<string, ConfigEntry<int>> ConstellationCaps { get; } = new Dictionary<string, ConfigEntry<int>>();


		public Dictionary<string, ConfigEntry<bool>> ConstellationCapEnabled { get; } = new Dictionary<string, ConfigEntry<bool>>();


		public ConfigEntry<bool> EnableDebug { get; private set; }

		public bool SaveOnConfigSet
		{
			get
			{
				return _saveOnConfigSet;
			}
			set
			{
				_saveOnConfigSet = value;
				_configFile.SaveOnConfigSet = value;
			}
		}

		public ConfigManager(ConfigFile configFile, ManualLogSource logger)
		{
			_configFile = configFile ?? throw new ArgumentNullException("configFile");
			_logger = logger ?? throw new ArgumentNullException("logger");
		}

		public void LoadConfiguration()
		{
			try
			{
				_logger.LogInfo((object)"Loading configuration...");
				LoadGeneralSettings();
				_logger.LogInfo((object)"Configuration loaded successfully");
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error loading configuration: " + ex.Message));
				throw;
			}
		}

		public void SaveConfiguration()
		{
			try
			{
				_configFile.Save();
				_logger.LogInfo((object)"Configuration saved successfully");
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error saving configuration: " + ex.Message));
				throw;
			}
		}

		public void ReloadConfiguration()
		{
			try
			{
				_configFile.Reload();
				_logger.LogInfo((object)"Configuration reloaded successfully");
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error reloading configuration: " + ex.Message));
				throw;
			}
		}

		public ConfigEntry<T> GetConfigEntry<T>(string section, string key, T defaultValue, string description)
		{
			try
			{
				return _configFile.Bind<T>(section, key, defaultValue, description);
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error getting config entry '" + section + "." + key + "': " + ex.Message));
				throw;
			}
		}

		public bool ValidateConfig()
		{
			try
			{
				_logger.LogInfo((object)"Validating configuration...");
				if (EnableDebug == null)
				{
					_logger.LogError((object)"Debug configuration entry is null");
					return false;
				}
				foreach (KeyValuePair<string, ConfigEntry<int>> constellationCap in ConstellationCaps)
				{
					if (constellationCap.Value == null)
					{
						_logger.LogError((object)("Constellation cap entry for '" + constellationCap.Key + "' is null"));
						return false;
					}
					if (constellationCap.Value.Value < -1)
					{
						_logger.LogWarning((object)$"Constellation cap value for '{constellationCap.Key}' is invalid: {constellationCap.Value.Value}");
					}
				}
				foreach (KeyValuePair<string, ConfigEntry<bool>> item in ConstellationCapEnabled)
				{
					if (item.Value == null)
					{
						_logger.LogError((object)("Constellation enabled entry for '" + item.Key + "' is null"));
						return false;
					}
				}
				_logger.LogInfo((object)"Configuration validation completed successfully");
				return true;
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error validating configuration: " + ex.Message));
				return false;
			}
		}

		public void CreateConstellationConfigEntries(string constellationName, string constellationWord)
		{
			try
			{
				if (string.IsNullOrEmpty(constellationName))
				{
					_logger.LogError((object)"Constellation name cannot be null or empty");
					return;
				}
				if (string.IsNullOrEmpty(constellationWord))
				{
					constellationWord = "Constellation";
				}
				string key = $"{constellationName}_Cap";
				string description = $"Quota cap for {constellationName} {constellationWord.ToLower()}";
				ConstellationCaps[constellationName] = GetConfigEntry("Quota Caps", key, 4000, description);
				string key2 = $"{constellationName}_Enabled";
				string description2 = $"Enable quota cap for {constellationName} {constellationWord.ToLower()}";
				ConstellationCapEnabled[constellationName] = GetConfigEntry("Quota Cap Toggles", key2, defaultValue: true, description2);
				_logger.LogInfo((object)("Created configuration entries for constellation: " + constellationName));
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error creating constellation config entries for '" + constellationName + "': " + ex.Message));
			}
		}

		private void LoadGeneralSettings()
		{
			EnableDebug = GetConfigEntry("General", "EnableDebug", defaultValue: true, "Toggle the debug stuff");
		}
	}
	public class ConstellationConfigGenerator
	{
		private readonly ConfigManager _configManager;

		private readonly ManualLogSource _logger;

		private int _retryCount = 0;

		private const int MaxRetries = 3;

		private const int RetryDelayMs = 5000;

		public ConstellationConfigGenerator(ConfigManager configManager, ManualLogSource logger)
		{
			_configManager = configManager ?? throw new ArgumentNullException("configManager");
			_logger = logger ?? throw new ArgumentNullException("logger");
		}

		public bool GenerateConstellationConfigs()
		{
			try
			{
				_logger.LogInfo((object)"Generating constellation configs from LethalConstellations config file");
				string constellationWord = GetConstellationWord();
				_logger.LogInfo((object)("Using constellation word: " + constellationWord));
				List<string> list = ParseConstellationNames(constellationWord);
				if (list.Count == 0)
				{
					_logger.LogWarning((object)"No constellations found in LethalConstellations config file");
					return RetryConfigGeneration();
				}
				_logger.LogInfo((object)$"Found {list.Count} constellations, generating config entries");
				foreach (string item in list)
				{
					_configManager.CreateConstellationConfigEntries(item, constellationWord);
				}
				_configManager.SaveConfiguration();
				_logger.LogInfo((object)$"Constellation quota cap configurations generated and saved - Created {list.Count} entries");
				_retryCount = 0;
				return true;
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error generating constellation configs: " + ex.Message));
				return RetryConfigGeneration();
			}
		}

		private string GetConstellationWord()
		{
			try
			{
				string path = Path.Combine(Paths.ConfigPath, "com.github.darmuh.LethalConstellations.cfg");
				if (!File.Exists(path))
				{
					_logger.LogWarning((object)"LethalConstellations main config file not found, using default constellation word");
					return "Constellation";
				}
				string[] array = File.ReadAllLines(path);
				string[] array2 = array;
				foreach (string text in array2)
				{
					if (text.StartsWith("ConstellationWord = "))
					{
						string text2 = text.Substring("ConstellationWord = ".Length).Trim();
						_logger.LogInfo((object)("Found custom constellation word: " + text2));
						return text2;
					}
				}
				_logger.LogWarning((object)"Constellation word not found in config, using default");
				return "Constellation";
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error getting constellation word: " + ex.Message));
				return "Constellation";
			}
		}

		private List<string> ParseConstellationNames(string constellationWord)
		{
			List<string> list = new List<string>();
			try
			{
				string path = Path.Combine(Paths.ConfigPath, "LethalConstellations_Generated.cfg");
				if (!File.Exists(path))
				{
					_logger.LogWarning((object)"LethalConstellations generated config file not found");
					return list;
				}
				string[] array = File.ReadAllLines(path);
				string text = "[" + constellationWord + " ";
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					if (text2.StartsWith(text))
					{
						int length = text.Length;
						string text3 = text2.Substring(length, text2.Length - length - 1);
						list.Add(text3);
						_logger.LogInfo((object)("Found " + constellationWord.ToLower() + ": " + text3));
					}
				}
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Error parsing constellation names: " + ex.Message));
			}
			return list;
		}

		private bool RetryConfigGeneration()
		{
			if (_retryCount >= 3)
			{
				_logger.LogError((object)"Max retry attempts reached for constellation config generation");
				_retryCount = 0;
				return false;
			}
			_retryCount++;
			_logger.LogInfo((object)$"Will retry constellation config generation in {5} seconds (attempt {_retryCount}/{3})");
			return false;
		}

		public void ResetRetryCount()
		{
			_retryCount = 0;
		}

		public int GetRetryCount()
		{
			return _retryCount;
		}

		public bool CanRetry()
		{
			return _retryCount < 3;
		}

		public bool ImmediateRetry()
		{
			if (!CanRetry())
			{
				return false;
			}
			return GenerateConstellationConfigs();
		}
	}
}