Decompiled source of HavenDevTools v2.1.1

HavenDevTools.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HavenDevTools.API;
using HavenDevTools.Config;
using HavenDevTools.Integrations;
using HavenDevTools.Services;
using HavenDevTools.UI;
using I2.Loc;
using Microsoft.CodeAnalysis;
using SunhavenMods.Shared;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Wish;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("HavenDevTools")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+79057c8571b97b27a9323b455b8f88a51829b688")]
[assembly: AssemblyProduct("HavenDevTools")]
[assembly: AssemblyTitle("HavenDevTools")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 SunhavenMods.Shared
{
	public static class ConfigFileHelper
	{
		public static ConfigFile CreateNamedConfig(string pluginGuid, string configFileName, Action<string> logWarning = null)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			string text = Path.Combine(Paths.ConfigPath, configFileName);
			string text2 = Path.Combine(Paths.ConfigPath, pluginGuid + ".cfg");
			try
			{
				if (!File.Exists(text) && File.Exists(text2))
				{
					File.Copy(text2, text);
				}
			}
			catch (Exception ex)
			{
				logWarning?.Invoke("[Config] Migration to " + configFileName + " failed: " + ex.Message);
			}
			return new ConfigFile(text, true);
		}

		public static bool ReplacePluginConfig(BaseUnityPlugin plugin, ConfigFile newConfig, Action<string> logWarning = null)
		{
			if ((Object)(object)plugin == (Object)null || newConfig == null)
			{
				return false;
			}
			try
			{
				Type typeFromHandle = typeof(BaseUnityPlugin);
				PropertyInfo property = typeFromHandle.GetProperty("Config", BindingFlags.Instance | BindingFlags.Public);
				if (property != null && property.CanWrite)
				{
					property.SetValue(plugin, newConfig, null);
					return true;
				}
				FieldInfo field = typeFromHandle.GetField("<Config>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null)
				{
					field.SetValue(plugin, newConfig);
					return true;
				}
				FieldInfo[] fields = typeFromHandle.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (fieldInfo.FieldType == typeof(ConfigFile))
					{
						fieldInfo.SetValue(plugin, newConfig);
						return true;
					}
				}
			}
			catch (Exception ex)
			{
				logWarning?.Invoke("[Config] ReplacePluginConfig failed: " + ex.Message);
			}
			return false;
		}
	}
	public static class SharedCodeRevision
	{
		public const string Value = "2026.07.28";
	}
	public sealed class ModHealthReport
	{
		public string PluginGuid { get; set; }

		public string DisplayName { get; set; }

		public string PluginVersion { get; set; }

		public string SharedCodeRevision { get; set; }

		public string IntegrationSummary { get; set; }

		public string Mode { get; set; }

		public string CharacterName { get; set; }

		public bool? DataLoaded { get; set; }

		public string LastPersistenceOutcome { get; set; }

		public string LastError { get; set; }

		public DateTime ReportedUtc { get; set; }

		public ModHealthReport Clone()
		{
			return new ModHealthReport
			{
				PluginGuid = PluginGuid,
				DisplayName = DisplayName,
				PluginVersion = PluginVersion,
				SharedCodeRevision = SharedCodeRevision,
				IntegrationSummary = IntegrationSummary,
				Mode = Mode,
				CharacterName = CharacterName,
				DataLoaded = DataLoaded,
				LastPersistenceOutcome = LastPersistenceOutcome,
				LastError = LastError,
				ReportedUtc = ReportedUtc
			};
		}

		public void AppendDiagnosticDump(StringBuilder sb)
		{
			if (sb != null)
			{
				sb.AppendLine("guid: " + (PluginGuid ?? "—"));
				sb.AppendLine("name: " + (DisplayName ?? "—"));
				sb.AppendLine("version: " + (PluginVersion ?? "—"));
				sb.AppendLine("shared: " + (SharedCodeRevision ?? "—"));
				sb.AppendLine("integrations: " + (IntegrationSummary ?? "—"));
				sb.AppendLine("mode: " + (Mode ?? "—"));
				sb.AppendLine("character: " + (string.IsNullOrEmpty(CharacterName) ? "—" : CharacterName));
				sb.AppendLine("data loaded: " + (DataLoaded.HasValue ? DataLoaded.Value.ToString() : "—"));
				sb.AppendLine("last save: " + (LastPersistenceOutcome ?? "—"));
				sb.AppendLine("last error: " + (LastError ?? "—"));
				sb.AppendLine("reported: " + ((ReportedUtc == default(DateTime)) ? "—" : ReportedUtc.ToLocalTime().ToString("u")));
			}
		}
	}
	public static class ModDiagnostics
	{
		private static readonly Dictionary<string, ModHealthReport> ReportsByPluginGuid = new Dictionary<string, ModHealthReport>(StringComparer.OrdinalIgnoreCase);

		private static readonly object Lock = new object();

		public static void ReportStartup(ModHealthReport report)
		{
			if (report == null || string.IsNullOrWhiteSpace(report.PluginGuid))
			{
				return;
			}
			report.ReportedUtc = DateTime.UtcNow;
			if (string.IsNullOrEmpty(report.SharedCodeRevision))
			{
				report.SharedCodeRevision = "2026.07.28";
			}
			lock (Lock)
			{
				ReportsByPluginGuid[report.PluginGuid] = report.Clone();
			}
		}

		public static void ReportRuntime(string pluginGuid, Action<ModHealthReport> update)
		{
			if (string.IsNullOrWhiteSpace(pluginGuid) || update == null)
			{
				return;
			}
			lock (Lock)
			{
				if (!ReportsByPluginGuid.TryGetValue(pluginGuid, out ModHealthReport value))
				{
					value = new ModHealthReport
					{
						PluginGuid = pluginGuid
					};
					ReportsByPluginGuid[pluginGuid] = value;
				}
				update(value);
				value.ReportedUtc = DateTime.UtcNow;
			}
		}

		public static ModHealthReport GetReport(string pluginGuid)
		{
			if (string.IsNullOrWhiteSpace(pluginGuid))
			{
				return null;
			}
			lock (Lock)
			{
				ModHealthReport value;
				return ReportsByPluginGuid.TryGetValue(pluginGuid, out value) ? value.Clone() : null;
			}
		}

		public static IReadOnlyList<ModHealthReport> GetAllReports()
		{
			lock (Lock)
			{
				return ReportsByPluginGuid.Values.Select((ModHealthReport r) => r.Clone()).ToList();
			}
		}

		public static string FormatHealthLogLine(ModHealthReport report)
		{
			if (report == null)
			{
				return "[Health] (empty report)";
			}
			string text = (string.IsNullOrEmpty(report.DisplayName) ? report.PluginGuid : report.DisplayName);
			string text2 = (string.IsNullOrEmpty(report.PluginVersion) ? "?" : report.PluginVersion);
			string text3 = (string.IsNullOrEmpty(report.SharedCodeRevision) ? "?" : report.SharedCodeRevision);
			string text4 = (string.IsNullOrEmpty(report.IntegrationSummary) ? "—" : report.IntegrationSummary);
			string text5 = (string.IsNullOrEmpty(report.Mode) ? "—" : report.Mode);
			string text6 = (string.IsNullOrEmpty(report.CharacterName) ? "—" : report.CharacterName);
			string text7 = ((!report.DataLoaded.HasValue) ? "—" : (report.DataLoaded.Value ? "loaded" : "none"));
			string text8 = (string.IsNullOrEmpty(report.LastPersistenceOutcome) ? "—" : report.LastPersistenceOutcome);
			return "[Health] " + text + " v" + text2 + " | shared " + text3 + " | integrations: " + text4 + " | mode: " + text5 + " | character: " + text6 + " | data: " + text7 + " | save: " + text8;
		}

		public static void LogStartupHealth(ManualLogSource log, ModHealthReport report)
		{
			ReportStartup(report);
			if (log != null)
			{
				log.LogInfo((object)FormatHealthLogLine(report));
			}
		}

		public static void LogModStartup(ManualLogSource log, string pluginGuid, string displayName, string pluginVersion, string integrationSummary, string mode = "startup", bool? dataLoaded = false, string lastPersistenceOutcome = "—")
		{
			LogStartupHealth(log, new ModHealthReport
			{
				PluginGuid = pluginGuid,
				DisplayName = displayName,
				PluginVersion = pluginVersion,
				SharedCodeRevision = "2026.07.28",
				IntegrationSummary = integrationSummary,
				Mode = mode,
				DataLoaded = dataLoaded,
				LastPersistenceOutcome = lastPersistenceOutcome
			});
		}
	}
	public static class SuitePluginGuids
	{
		public const string DevTools = "com.azraelgodking.havendevtools";

		public const string SenpaisChest = "com.azraelgodking.senpaischest";

		public const string BirthdayReminder = "com.azraelgodking.squirrelsbirthdayreminder";

		public const string HavensBirthright = "com.azraelgodking.havensbirthright";

		public const string Smut = "com.azraelgodking.sunhavenmuseumutilitytracker";

		public const string SunhavenTodo = "com.azraelgodking.sunhaventodo";

		public const string TheVault = "com.azraelgodking.thevault";

		public const string HavensAlmanac = "com.azraelgodking.havensalmanac";

		public const string FasterRaces = "com.azraelgodking.fasterraces";

		public const string TrinketFortune = "com.azraelgodking.trinketfortune";

		public const string CropOptimizer = "com.azraelgodking.cropoptimizer";

		public const string HavensRespec = "com.azraelgodking.havensrespec";

		public const string GiftingAssistant = "com.azraelgodking.giftingassistant";
	}
	public static class ModHealthIntegrationSummary
	{
		public static string Build(params (string label, string pluginGuid)[] integrations)
		{
			if (integrations == null || integrations.Length == 0)
			{
				return "standalone";
			}
			Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos;
			if (pluginInfos == null)
			{
				return "standalone";
			}
			List<string> list = new List<string>(integrations.Length);
			for (int i = 0; i < integrations.Length; i++)
			{
				var (text, text2) = integrations[i];
				if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(text2) && pluginInfos.ContainsKey(text2))
				{
					list.Add(text);
				}
			}
			if (list.Count != 0)
			{
				return string.Join(", ", list);
			}
			return "standalone";
		}
	}
	public static class ModHealthAggregator
	{
		public sealed class MergedModHealthRow
		{
			public string PluginGuid { get; set; }

			public string DisplayName { get; set; }

			public string InstalledVersion { get; set; }

			public string SharedCodeRevision { get; set; }

			public string IntegrationSummary { get; set; }

			public string Mode { get; set; }

			public string CharacterName { get; set; }

			public bool? DataLoaded { get; set; }

			public string LastPersistenceOutcome { get; set; }

			public DateTime LastCheckUtc { get; set; }

			public int ExceptionCount { get; set; }

			public string LastError { get; set; }

			public DateTime ReportedUtc { get; set; }

			public bool HasDiagnosticsReport { get; set; }

			public bool HasIssue
			{
				get
				{
					if (ExceptionCount <= 0)
					{
						return !string.IsNullOrEmpty(LastError);
					}
					return true;
				}
			}

			public void AppendDiagnosticDump(StringBuilder sb)
			{
				sb.AppendLine("=== " + (DisplayName ?? PluginGuid) + " ===");
				sb.AppendLine("installed: " + (InstalledVersion ?? "—"));
				sb.AppendLine("shared code: " + (SharedCodeRevision ?? "—"));
				sb.AppendLine(string.Format("version check: {0}, exceptions {1}", (LastCheckUtc == default(DateTime)) ? "never" : LastCheckUtc.ToLocalTime().ToString("u"), ExceptionCount));
				if (!string.IsNullOrEmpty(LastError))
				{
					sb.AppendLine("last error: " + LastError);
				}
				sb.AppendLine("integrations: " + (IntegrationSummary ?? "—"));
				sb.AppendLine("mode: " + (Mode ?? "—"));
				sb.AppendLine("character: " + (string.IsNullOrEmpty(CharacterName) ? "—" : CharacterName));
				sb.AppendLine("data loaded: " + (DataLoaded.HasValue ? DataLoaded.Value.ToString() : "—"));
				sb.AppendLine("last save: " + (LastPersistenceOutcome ?? "—"));
				sb.AppendLine("diagnostics reported: " + ((ReportedUtc == default(DateTime)) ? "—" : ReportedUtc.ToLocalTime().ToString("u")));
				sb.AppendLine();
			}
		}

		public sealed class SharedCodeSkewAnalysis
		{
			public bool HasSkew { get; set; }

			public int VersionCheckerCopyCount { get; set; }

			public int ModDiagnosticsCopyCount { get; set; }

			public IReadOnlyDictionary<string, IReadOnlyList<string>> ModsByRevision { get; set; } = new Dictionary<string, IReadOnlyList<string>>();
		}

		private struct VersionTelemetryEntry
		{
			public string PluginGuid;

			public DateTime LastCheckUtc;

			public int ExceptionCount;

			public string LastError;
		}

		private struct SnapshotShape
		{
			public PropertyInfo LastCheckUtc;

			public PropertyInfo ExceptionCount;

			public PropertyInfo LastError;
		}

		private struct DiagnosticsShape
		{
			public PropertyInfo DisplayName;

			public PropertyInfo PluginVersion;

			public PropertyInfo SharedCodeRevision;

			public PropertyInfo IntegrationSummary;

			public PropertyInfo Mode;

			public PropertyInfo CharacterName;

			public PropertyInfo DataLoaded;

			public PropertyInfo LastPersistenceOutcome;

			public PropertyInfo LastError;

			public PropertyInfo ReportedUtc;
		}

		private static readonly object CacheLock = new object();

		private static List<FieldInfo> _cachedVersionCheckerFields;

		private static List<FieldInfo> _cachedDiagnosticsFields;

		private static int _cachedAssemblyCount;

		private static DateTime _cacheBuiltAt = DateTime.MinValue;

		private static readonly TimeSpan CacheMaxAge = TimeSpan.FromMinutes(5.0);

		private static readonly Dictionary<Type, SnapshotShape> VersionSnapshotShapeCache = new Dictionary<Type, SnapshotShape>();

		private static readonly Dictionary<Type, DiagnosticsShape> DiagnosticsShapeCache = new Dictionary<Type, DiagnosticsShape>();

		public static IReadOnlyList<MergedModHealthRow> CollectMergedRows(Func<string, string> resolveDisplayName = null, Func<string, string> resolveInstalledVersion = null)
		{
			if (resolveDisplayName == null)
			{
				resolveDisplayName = (string _) => (string)null;
			}
			if (resolveInstalledVersion == null)
			{
				resolveInstalledVersion = (string _) => (string)null;
			}
			List<VersionTelemetryEntry> list = CollectVersionCheckerTelemetry();
			List<ModHealthReport> list2 = CollectDiagnosticsReports();
			Dictionary<string, MergedModHealthRow> dictionary = new Dictionary<string, MergedModHealthRow>(StringComparer.OrdinalIgnoreCase);
			foreach (VersionTelemetryEntry item in list)
			{
				dictionary[item.PluginGuid] = new MergedModHealthRow
				{
					PluginGuid = item.PluginGuid,
					DisplayName = (resolveDisplayName(item.PluginGuid) ?? item.PluginGuid),
					InstalledVersion = resolveInstalledVersion(item.PluginGuid),
					LastCheckUtc = item.LastCheckUtc,
					ExceptionCount = item.ExceptionCount,
					LastError = item.LastError
				};
			}
			foreach (ModHealthReport item2 in list2)
			{
				if (!string.IsNullOrEmpty(item2.PluginGuid))
				{
					if (!dictionary.TryGetValue(item2.PluginGuid, out var value))
					{
						value = new MergedModHealthRow
						{
							PluginGuid = item2.PluginGuid
						};
						dictionary[item2.PluginGuid] = value;
					}
					value.HasDiagnosticsReport = true;
					value.DisplayName = item2.DisplayName ?? value.DisplayName ?? resolveDisplayName(item2.PluginGuid) ?? item2.PluginGuid;
					value.InstalledVersion = item2.PluginVersion ?? value.InstalledVersion ?? resolveInstalledVersion(item2.PluginGuid);
					value.SharedCodeRevision = item2.SharedCodeRevision ?? value.SharedCodeRevision;
					value.IntegrationSummary = item2.IntegrationSummary ?? value.IntegrationSummary;
					value.Mode = item2.Mode ?? value.Mode;
					value.CharacterName = item2.CharacterName ?? value.CharacterName;
					value.DataLoaded = item2.DataLoaded ?? value.DataLoaded;
					value.LastPersistenceOutcome = item2.LastPersistenceOutcome ?? value.LastPersistenceOutcome;
					value.ReportedUtc = ((item2.ReportedUtc > value.ReportedUtc) ? item2.ReportedUtc : value.ReportedUtc);
					if (!string.IsNullOrEmpty(item2.LastError))
					{
						value.LastError = item2.LastError;
					}
				}
			}
			foreach (MergedModHealthRow value2 in dictionary.Values)
			{
				if (string.IsNullOrEmpty(value2.DisplayName))
				{
					value2.DisplayName = resolveDisplayName(value2.PluginGuid) ?? value2.PluginGuid;
				}
				if (string.IsNullOrEmpty(value2.InstalledVersion))
				{
					value2.InstalledVersion = resolveInstalledVersion(value2.PluginGuid);
				}
			}
			return dictionary.Values.OrderBy<MergedModHealthRow, string>((MergedModHealthRow r) => r.DisplayName, StringComparer.OrdinalIgnoreCase).ToList();
		}

		public static SharedCodeSkewAnalysis AnalyzeSharedCodeSkew(IEnumerable<MergedModHealthRow> rows)
		{
			List<FieldInfo> cachedDiagnosticsFields = GetCachedDiagnosticsFields();
			Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
			if (rows != null)
			{
				foreach (MergedModHealthRow row in rows)
				{
					if (!string.IsNullOrEmpty(row.SharedCodeRevision))
					{
						if (!dictionary.TryGetValue(row.SharedCodeRevision, out var value))
						{
							value = new List<string>();
							dictionary[row.SharedCodeRevision] = value;
						}
						value.Add(row.DisplayName ?? row.PluginGuid);
					}
				}
			}
			return new SharedCodeSkewAnalysis
			{
				HasSkew = (dictionary.Count > 1),
				VersionCheckerCopyCount = GetCachedVersionCheckerFields().Count,
				ModDiagnosticsCopyCount = cachedDiagnosticsFields.Count,
				ModsByRevision = ((IEnumerable<KeyValuePair<string, List<string>>>)dictionary).ToDictionary((Func<KeyValuePair<string, List<string>>, string>)((KeyValuePair<string, List<string>> kvp) => kvp.Key), (Func<KeyValuePair<string, List<string>>, IReadOnlyList<string>>)((KeyValuePair<string, List<string>> kvp) => kvp.Value.OrderBy<string, string>((string n) => n, StringComparer.OrdinalIgnoreCase).ToList()))
			};
		}

		public static string BuildCombinedDiagnosticDump(IEnumerable<MergedModHealthRow> rows)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (rows == null)
			{
				return stringBuilder.ToString();
			}
			foreach (MergedModHealthRow row in rows)
			{
				row.AppendDiagnosticDump(stringBuilder);
			}
			return stringBuilder.ToString();
		}

		private static List<VersionTelemetryEntry> CollectVersionCheckerTelemetry()
		{
			List<FieldInfo> cachedVersionCheckerFields = GetCachedVersionCheckerFields();
			Dictionary<string, VersionTelemetryEntry> dictionary = new Dictionary<string, VersionTelemetryEntry>(StringComparer.OrdinalIgnoreCase);
			foreach (FieldInfo item in cachedVersionCheckerFields)
			{
				IDictionary dictionary2;
				try
				{
					dictionary2 = item.GetValue(null) as IDictionary;
				}
				catch
				{
					continue;
				}
				if (dictionary2 == null)
				{
					continue;
				}
				foreach (DictionaryEntry item2 in dictionary2)
				{
					string text = item2.Key as string;
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					object value = item2.Value;
					if (value != null)
					{
						VersionTelemetryEntry value2 = ReadVersionSnapshot(text, value);
						if (!dictionary.TryGetValue(text, out var value3))
						{
							dictionary[text] = value2;
							continue;
						}
						dictionary[text] = new VersionTelemetryEntry
						{
							PluginGuid = text,
							LastCheckUtc = ((value2.LastCheckUtc > value3.LastCheckUtc) ? value2.LastCheckUtc : value3.LastCheckUtc),
							ExceptionCount = Math.Max(value3.ExceptionCount, value2.ExceptionCount),
							LastError = (string.IsNullOrEmpty(value2.LastError) ? value3.LastError : value2.LastError)
						};
					}
				}
			}
			return dictionary.Values.ToList();
		}

		private static List<ModHealthReport> CollectDiagnosticsReports()
		{
			List<FieldInfo> cachedDiagnosticsFields = GetCachedDiagnosticsFields();
			Dictionary<string, ModHealthReport> dictionary = new Dictionary<string, ModHealthReport>(StringComparer.OrdinalIgnoreCase);
			foreach (FieldInfo item in cachedDiagnosticsFields)
			{
				IDictionary dictionary2;
				try
				{
					dictionary2 = item.GetValue(null) as IDictionary;
				}
				catch
				{
					continue;
				}
				if (dictionary2 == null)
				{
					continue;
				}
				foreach (DictionaryEntry item2 in dictionary2)
				{
					string text = item2.Key as string;
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					object value = item2.Value;
					if (value != null)
					{
						ModHealthReport modHealthReport = ReadDiagnosticsReport(text, value);
						if (!dictionary.TryGetValue(text, out var value2))
						{
							dictionary[text] = modHealthReport;
						}
						else
						{
							dictionary[text] = MergeDiagnosticsReports(value2, modHealthReport);
						}
					}
				}
			}
			return dictionary.Values.ToList();
		}

		private static ModHealthReport MergeDiagnosticsReports(ModHealthReport a, ModHealthReport b)
		{
			ModHealthReport modHealthReport = ((a.ReportedUtc >= b.ReportedUtc) ? a : b);
			ModHealthReport modHealthReport2 = ((modHealthReport == a) ? b : a);
			ModHealthReport modHealthReport3 = modHealthReport.Clone();
			modHealthReport3.IntegrationSummary = modHealthReport.IntegrationSummary ?? modHealthReport2.IntegrationSummary;
			modHealthReport3.Mode = modHealthReport.Mode ?? modHealthReport2.Mode;
			modHealthReport3.CharacterName = modHealthReport.CharacterName ?? modHealthReport2.CharacterName;
			modHealthReport3.DataLoaded = modHealthReport.DataLoaded ?? modHealthReport2.DataLoaded;
			modHealthReport3.LastPersistenceOutcome = modHealthReport.LastPersistenceOutcome ?? modHealthReport2.LastPersistenceOutcome;
			modHealthReport3.SharedCodeRevision = modHealthReport.SharedCodeRevision ?? modHealthReport2.SharedCodeRevision;
			modHealthReport3.LastError = modHealthReport.LastError ?? modHealthReport2.LastError;
			modHealthReport3.DisplayName = modHealthReport.DisplayName ?? modHealthReport2.DisplayName;
			modHealthReport3.PluginVersion = modHealthReport.PluginVersion ?? modHealthReport2.PluginVersion;
			return modHealthReport3;
		}

		private static ModHealthReport ReadDiagnosticsReport(string guid, object reportObj)
		{
			DiagnosticsShape diagnosticsShape = GetDiagnosticsShape(reportObj.GetType());
			ModHealthReport modHealthReport = new ModHealthReport
			{
				PluginGuid = guid
			};
			modHealthReport.DisplayName = diagnosticsShape.DisplayName?.GetValue(reportObj) as string;
			modHealthReport.PluginVersion = diagnosticsShape.PluginVersion?.GetValue(reportObj) as string;
			modHealthReport.SharedCodeRevision = diagnosticsShape.SharedCodeRevision?.GetValue(reportObj) as string;
			modHealthReport.IntegrationSummary = diagnosticsShape.IntegrationSummary?.GetValue(reportObj) as string;
			modHealthReport.Mode = diagnosticsShape.Mode?.GetValue(reportObj) as string;
			modHealthReport.CharacterName = diagnosticsShape.CharacterName?.GetValue(reportObj) as string;
			modHealthReport.LastPersistenceOutcome = diagnosticsShape.LastPersistenceOutcome?.GetValue(reportObj) as string;
			modHealthReport.LastError = diagnosticsShape.LastError?.GetValue(reportObj) as string;
			if (diagnosticsShape.DataLoaded?.GetValue(reportObj) is bool value)
			{
				modHealthReport.DataLoaded = value;
			}
			if (diagnosticsShape.ReportedUtc?.GetValue(reportObj) is DateTime reportedUtc)
			{
				modHealthReport.ReportedUtc = reportedUtc;
			}
			return modHealthReport;
		}

		private static VersionTelemetryEntry ReadVersionSnapshot(string guid, object snap)
		{
			Type type = snap.GetType();
			VersionTelemetryEntry result = new VersionTelemetryEntry
			{
				PluginGuid = guid
			};
			SnapshotShape versionSnapshotShape = GetVersionSnapshotShape(type);
			if (versionSnapshotShape.LastCheckUtc?.GetValue(snap) is DateTime lastCheckUtc)
			{
				result.LastCheckUtc = lastCheckUtc;
			}
			if (versionSnapshotShape.ExceptionCount?.GetValue(snap) is int exceptionCount)
			{
				result.ExceptionCount = exceptionCount;
			}
			result.LastError = versionSnapshotShape.LastError?.GetValue(snap) as string;
			return result;
		}

		private static SnapshotShape GetVersionSnapshotShape(Type snapshotType)
		{
			lock (CacheLock)
			{
				if (VersionSnapshotShapeCache.TryGetValue(snapshotType, out var value))
				{
					return value;
				}
				value = new SnapshotShape
				{
					LastCheckUtc = snapshotType.GetProperty("LastCheckUtc"),
					ExceptionCount = snapshotType.GetProperty("ExceptionCount"),
					LastError = snapshotType.GetProperty("LastError")
				};
				VersionSnapshotShapeCache[snapshotType] = value;
				return value;
			}
		}

		private static DiagnosticsShape GetDiagnosticsShape(Type reportType)
		{
			lock (CacheLock)
			{
				if (DiagnosticsShapeCache.TryGetValue(reportType, out var value))
				{
					return value;
				}
				value = new DiagnosticsShape
				{
					DisplayName = reportType.GetProperty("DisplayName"),
					PluginVersion = reportType.GetProperty("PluginVersion"),
					SharedCodeRevision = reportType.GetProperty("SharedCodeRevision"),
					IntegrationSummary = reportType.GetProperty("IntegrationSummary"),
					Mode = reportType.GetProperty("Mode"),
					CharacterName = reportType.GetProperty("CharacterName"),
					DataLoaded = reportType.GetProperty("DataLoaded"),
					LastPersistenceOutcome = reportType.GetProperty("LastPersistenceOutcome"),
					LastError = reportType.GetProperty("LastError"),
					ReportedUtc = reportType.GetProperty("ReportedUtc")
				};
				DiagnosticsShapeCache[reportType] = value;
				return value;
			}
		}

		private static List<FieldInfo> GetCachedVersionCheckerFields()
		{
			return GetCachedStaticDictionaryFields("SunhavenMods.Shared.VersionChecker", "HealthByPluginGuid", ref _cachedVersionCheckerFields);
		}

		private static List<FieldInfo> GetCachedDiagnosticsFields()
		{
			return GetCachedStaticDictionaryFields("SunhavenMods.Shared.ModDiagnostics", "ReportsByPluginGuid", ref _cachedDiagnosticsFields);
		}

		private static List<FieldInfo> GetCachedStaticDictionaryFields(string typeName, string fieldName, ref List<FieldInfo> cache)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			lock (CacheLock)
			{
				if (cache != null && assemblies.Length == _cachedAssemblyCount && !(DateTime.UtcNow - _cacheBuiltAt > CacheMaxAge))
				{
					return cache;
				}
				List<FieldInfo> list = new List<FieldInfo>();
				Assembly[] array = assemblies;
				foreach (Assembly assembly in array)
				{
					Type type = null;
					try
					{
						type = assembly.GetType(typeName, throwOnError: false);
					}
					catch
					{
					}
					if (!(type == null))
					{
						FieldInfo field = type.GetField(fieldName, BindingFlags.Static | BindingFlags.NonPublic);
						if (!(field == null))
						{
							list.Add(field);
						}
					}
				}
				cache = list;
				_cachedAssemblyCount = assemblies.Length;
				_cacheBuiltAt = DateTime.UtcNow;
				return cache;
			}
		}
	}
	public static class VersionChecker
	{
		public class VersionCheckResult
		{
			public bool Success { get; set; }

			public bool UpdateAvailable { get; set; }

			public string CurrentVersion { get; set; }

			public string LatestVersion { get; set; }

			public string ModName { get; set; }

			public string NexusUrl { get; set; }

			public string Changelog { get; set; }

			public string ErrorMessage { get; set; }
		}

		public class ModHealthSnapshot
		{
			public string PluginGuid { get; set; }

			public DateTime LastCheckUtc { get; set; }

			public int ExceptionCount { get; set; }

			public string LastError { get; set; }
		}

		private class VersionCheckRunner : MonoBehaviour
		{
			private ManualLogSource _pluginLog;

			public void StartCheck(string pluginGuid, string currentVersion, ManualLogSource pluginLog, Action<VersionCheckResult> onComplete)
			{
				_pluginLog = pluginLog;
				((MonoBehaviour)this).StartCoroutine(CheckVersionCoroutine(pluginGuid, currentVersion, onComplete));
			}

			private void LogInfo(string message)
			{
				ManualLogSource pluginLog = _pluginLog;
				if (pluginLog != null)
				{
					pluginLog.LogInfo((object)("[VersionChecker] " + message));
				}
			}

			private void LogWarningMsg(string message)
			{
				ManualLogSource pluginLog = _pluginLog;
				if (pluginLog != null)
				{
					pluginLog.LogWarning((object)("[VersionChecker] " + message));
				}
			}

			private void LogErrorMsg(string message)
			{
				ManualLogSource pluginLog = _pluginLog;
				if (pluginLog != null)
				{
					pluginLog.LogError((object)("[VersionChecker] " + message));
				}
			}

			private IEnumerator CheckVersionCoroutine(string pluginGuid, string currentVersion, Action<VersionCheckResult> onComplete)
			{
				VersionCheckResult result = new VersionCheckResult
				{
					CurrentVersion = currentVersion
				};
				UnityWebRequest www = UnityWebRequest.Get("https://azraelgodking.github.io/SunhavenMod/versions.json");
				try
				{
					www.timeout = 10;
					yield return www.SendWebRequest();
					if ((int)www.result == 2 || (int)www.result == 3)
					{
						result.Success = false;
						result.ErrorMessage = "Network error: " + www.error;
						RecordHealthError(pluginGuid, result.ErrorMessage);
						LogWarningMsg(result.ErrorMessage);
						onComplete?.Invoke(result);
						Object.Destroy((Object)(object)((Component)this).gameObject);
						yield break;
					}
					try
					{
						string text = www.downloadHandler.text;
						Match match = GetModPattern(pluginGuid).Match(text);
						if (!match.Success)
						{
							result.Success = false;
							result.ErrorMessage = "Mod '" + pluginGuid + "' not found in versions.json";
							RecordHealthError(pluginGuid, result.ErrorMessage);
							LogWarningMsg(result.ErrorMessage);
							onComplete?.Invoke(result);
							Object.Destroy((Object)(object)((Component)this).gameObject);
							yield break;
						}
						string value = match.Groups[1].Value;
						result.LatestVersion = ExtractJsonString(value, "version");
						result.ModName = ExtractJsonString(value, "name");
						result.NexusUrl = ExtractJsonString(value, "nexus");
						result.Changelog = ExtractJsonString(value, "changelog");
						if (string.IsNullOrEmpty(result.LatestVersion))
						{
							result.Success = false;
							result.ErrorMessage = "Could not parse version from response";
							RecordHealthError(pluginGuid, result.ErrorMessage);
							LogWarningMsg(result.ErrorMessage);
							onComplete?.Invoke(result);
							Object.Destroy((Object)(object)((Component)this).gameObject);
							yield break;
						}
						result.Success = true;
						result.UpdateAvailable = CompareVersions(currentVersion, result.LatestVersion) < 0;
						if (result.UpdateAvailable)
						{
							LogInfo("Update available for " + result.ModName + ": " + currentVersion + " -> " + result.LatestVersion);
						}
						else
						{
							LogInfo(result.ModName + " is up to date (v" + currentVersion + ")");
						}
					}
					catch (Exception ex)
					{
						result.Success = false;
						result.ErrorMessage = "Parse error: " + ex.Message;
						RecordHealthError(pluginGuid, result.ErrorMessage);
						LogErrorMsg(result.ErrorMessage);
					}
				}
				finally
				{
					((IDisposable)www)?.Dispose();
				}
				onComplete?.Invoke(result);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}

			private string ExtractJsonString(string json, string key)
			{
				Match match = ExtractFieldRegex.Match(json);
				while (match.Success)
				{
					if (string.Equals(match.Groups["key"].Value, key, StringComparison.Ordinal))
					{
						return match.Groups["value"].Value;
					}
					match = match.NextMatch();
				}
				return null;
			}
		}

		private const string VersionsUrl = "https://azraelgodking.github.io/SunhavenMod/versions.json";

		private static readonly Dictionary<string, ModHealthSnapshot> HealthByPluginGuid = new Dictionary<string, ModHealthSnapshot>(StringComparer.OrdinalIgnoreCase);

		private static readonly object HealthLock = new object();

		private static readonly Dictionary<string, Regex> ModPatternCache = new Dictionary<string, Regex>(StringComparer.Ordinal);

		private static readonly object ModPatternCacheLock = new object();

		private static readonly Regex ExtractFieldRegex = new Regex("\"(?<key>[^\"]+)\"\\s*:\\s*(?:\"(?<value>[^\"]*)\"|null)", RegexOptions.Compiled);

		public static void CheckForUpdate(string pluginGuid, string currentVersion, ManualLogSource logger = null, Action<VersionCheckResult> onComplete = null)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			TouchHealth(pluginGuid);
			VersionCheckRunner versionCheckRunner = new GameObject("VersionChecker").AddComponent<VersionCheckRunner>();
			Object.DontDestroyOnLoad((Object)(object)((Component)versionCheckRunner).gameObject);
			SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(((Component)versionCheckRunner).gameObject);
			versionCheckRunner.StartCheck(pluginGuid, currentVersion, logger, onComplete);
		}

		public static ModHealthSnapshot GetHealthSnapshot(string pluginGuid)
		{
			if (string.IsNullOrWhiteSpace(pluginGuid))
			{
				return null;
			}
			lock (HealthLock)
			{
				if (!HealthByPluginGuid.TryGetValue(pluginGuid, out ModHealthSnapshot value))
				{
					return null;
				}
				return new ModHealthSnapshot
				{
					PluginGuid = value.PluginGuid,
					LastCheckUtc = value.LastCheckUtc,
					ExceptionCount = value.ExceptionCount,
					LastError = value.LastError
				};
			}
		}

		public static int CompareVersions(string v1, string v2)
		{
			if (string.IsNullOrEmpty(v1) || string.IsNullOrEmpty(v2))
			{
				return 0;
			}
			v1 = v1.TrimStart('v', 'V');
			v2 = v2.TrimStart('v', 'V');
			int num = v1.IndexOfAny(new char[2] { '-', '+' });
			if (num >= 0)
			{
				v1 = v1.Substring(0, num);
			}
			int num2 = v2.IndexOfAny(new char[2] { '-', '+' });
			if (num2 >= 0)
			{
				v2 = v2.Substring(0, num2);
			}
			string[] array = v1.Split(new char[1] { '.' });
			string[] array2 = v2.Split(new char[1] { '.' });
			int num3 = Math.Max(array.Length, array2.Length);
			for (int i = 0; i < num3; i++)
			{
				int result;
				int num4 = ((i < array.Length && int.TryParse(array[i], out result)) ? result : 0);
				int result2;
				int num5 = ((i < array2.Length && int.TryParse(array2[i], out result2)) ? result2 : 0);
				if (num4 < num5)
				{
					return -1;
				}
				if (num4 > num5)
				{
					return 1;
				}
			}
			return 0;
		}

		private static void TouchHealth(string pluginGuid)
		{
			if (string.IsNullOrWhiteSpace(pluginGuid))
			{
				return;
			}
			lock (HealthLock)
			{
				if (!HealthByPluginGuid.TryGetValue(pluginGuid, out ModHealthSnapshot value))
				{
					value = new ModHealthSnapshot
					{
						PluginGuid = pluginGuid
					};
					HealthByPluginGuid[pluginGuid] = value;
				}
				value.LastCheckUtc = DateTime.UtcNow;
			}
		}

		private static void RecordHealthError(string pluginGuid, string errorMessage)
		{
			if (string.IsNullOrWhiteSpace(pluginGuid))
			{
				return;
			}
			lock (HealthLock)
			{
				if (!HealthByPluginGuid.TryGetValue(pluginGuid, out ModHealthSnapshot value))
				{
					value = new ModHealthSnapshot
					{
						PluginGuid = pluginGuid
					};
					HealthByPluginGuid[pluginGuid] = value;
				}
				value.LastCheckUtc = DateTime.UtcNow;
				value.ExceptionCount++;
				value.LastError = errorMessage;
			}
		}

		private static Regex GetModPattern(string pluginGuid)
		{
			lock (ModPatternCacheLock)
			{
				if (!ModPatternCache.TryGetValue(pluginGuid, out Regex value))
				{
					value = new Regex("\"" + Regex.Escape(pluginGuid) + "\"\\s*:\\s*\\{([^}]+)\\}", RegexOptions.Compiled | RegexOptions.Singleline);
					ModPatternCache[pluginGuid] = value;
				}
				return value;
			}
		}
	}
	public static class VersionCheckerExtensions
	{
		public static void NotifyUpdateAvailable(this VersionChecker.VersionCheckResult result, ManualLogSource logger = null)
		{
			if (!result.UpdateAvailable)
			{
				return;
			}
			string text = result.ModName + " update available: v" + result.LatestVersion;
			try
			{
				Type type = ReflectionHelper.FindWishType("NotificationStack");
				if (type != null)
				{
					Type type2 = ReflectionHelper.FindType("SingletonBehaviour`1", "Wish");
					if (type2 != null)
					{
						object obj = type2.MakeGenericType(type).GetProperty("Instance")?.GetValue(null);
						if (obj != null)
						{
							MethodInfo method = type.GetMethod("SendNotification", new Type[5]
							{
								typeof(string),
								typeof(int),
								typeof(int),
								typeof(bool),
								typeof(bool)
							});
							if (method != null)
							{
								method.Invoke(obj, new object[5] { text, 0, 1, false, true });
								return;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				if (logger != null)
				{
					logger.LogWarning((object)("Failed to send native notification: " + ex.Message));
				}
			}
			if (logger != null)
			{
				logger.LogWarning((object)("[UPDATE AVAILABLE] " + text));
			}
			if (!string.IsNullOrEmpty(result.NexusUrl) && logger != null)
			{
				logger.LogWarning((object)("Download at: " + result.NexusUrl));
			}
		}
	}
	public static class SceneRootSurvivor
	{
		private static readonly object Lock = new object();

		private static readonly List<string> NoKillSubstrings = new List<string>();

		private static Harmony _harmony;

		public static void TryRegisterPersistentRunnerGameObject(GameObject go)
		{
			if (!((Object)(object)go == (Object)null))
			{
				TryAddNoKillListSubstring(((Object)go).name);
			}
		}

		public static void TryAddNoKillListSubstring(string nameSubstring)
		{
			if (string.IsNullOrEmpty(nameSubstring))
			{
				return;
			}
			lock (Lock)
			{
				bool flag = false;
				for (int i = 0; i < NoKillSubstrings.Count; i++)
				{
					if (string.Equals(NoKillSubstrings[i], nameSubstring, StringComparison.OrdinalIgnoreCase))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					NoKillSubstrings.Add(nameSubstring);
				}
			}
			EnsurePatched();
		}

		private static void EnsurePatched()
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_00a3: Expected O, but got Unknown
			if (_harmony != null)
			{
				return;
			}
			lock (Lock)
			{
				if (_harmony == null)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(Scene), "GetRootGameObjects", Type.EmptyTypes, (Type[])null);
					if (!(methodInfo == null))
					{
						string text = typeof(SceneRootSurvivor).Assembly.GetName().Name ?? "Unknown";
						Harmony val = new Harmony("SunhavenMods.SceneRootSurvivor." + text);
						val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SceneRootSurvivor), "OnGetRootGameObjectsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						_harmony = val;
					}
				}
			}
		}

		private static void OnGetRootGameObjectsPostfix(ref GameObject[] __result)
		{
			if (__result == null || __result.Length == 0)
			{
				return;
			}
			List<string> list;
			lock (Lock)
			{
				if (NoKillSubstrings.Count == 0)
				{
					return;
				}
				list = new List<string>(NoKillSubstrings);
			}
			List<GameObject> list2 = new List<GameObject>(__result);
			for (int i = 0; i < list.Count; i++)
			{
				string noKill = list[i];
				list2.RemoveAll((GameObject a) => (Object)(object)a != (Object)null && ((Object)a).name.IndexOf(noKill, StringComparison.OrdinalIgnoreCase) >= 0);
			}
			__result = list2.ToArray();
		}
	}
	public static class ReflectionHelper
	{
		public static readonly BindingFlags AllBindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;

		public static Type FindType(string typeName, params string[] namespaces)
		{
			Assembly[] assemblies;
			if (namespaces != null && namespaces.Length != 0)
			{
				string[] array = namespaces;
				for (int i = 0; i < array.Length; i++)
				{
					Type type = AccessTools.TypeByName(array[i] + "." + typeName);
					if (type != null)
					{
						return type;
					}
				}
				assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					array = namespaces;
					foreach (string text in array)
					{
						try
						{
							Type type2 = assembly.GetType(text + "." + typeName, throwOnError: false);
							if (type2 != null)
							{
								return type2;
							}
						}
						catch
						{
						}
					}
				}
				assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly2 in assemblies)
				{
					try
					{
						Type type3 = assembly2.GetTypes().FirstOrDefault((Type t) => namespaces.Any((string ns) => string.Equals(t.FullName, ns + "." + typeName, StringComparison.Ordinal) || (t.Name == typeName && string.Equals(t.Namespace, ns, StringComparison.Ordinal))));
						if (type3 != null)
						{
							return type3;
						}
					}
					catch (ReflectionTypeLoadException ex)
					{
						Type type4 = ex.Types?.FirstOrDefault((Type t) => t != null && namespaces.Any((string ns) => string.Equals(t.FullName, ns + "." + typeName, StringComparison.Ordinal) || (t.Name == typeName && string.Equals(t.Namespace, ns, StringComparison.Ordinal))));
						if (type4 != null)
						{
							return type4;
						}
					}
				}
				return null;
			}
			Type type5 = AccessTools.TypeByName(typeName);
			if (type5 != null)
			{
				return type5;
			}
			assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly3 in assemblies)
			{
				try
				{
					type5 = assembly3.GetTypes().FirstOrDefault((Type t) => t.Name == typeName || t.FullName == typeName);
					if (type5 != null)
					{
						return type5;
					}
				}
				catch (ReflectionTypeLoadException)
				{
				}
			}
			return null;
		}

		public static Type FindModPlugin(string assemblyName)
		{
			if (string.IsNullOrWhiteSpace(assemblyName))
			{
				return null;
			}
			Type type = FindType("Plugin", assemblyName);
			if (type != null && string.Equals(type.Assembly.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase))
			{
				return type;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!string.Equals(assembly.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				Type type2 = assembly.GetType(assemblyName + ".Plugin", throwOnError: false);
				if (type2 != null)
				{
					return type2;
				}
				try
				{
					Type type3 = assembly.GetTypes().FirstOrDefault((Type t) => t.IsClass && !t.IsAbstract && t.Name == "Plugin");
					if (type3 != null)
					{
						return type3;
					}
				}
				catch (ReflectionTypeLoadException ex)
				{
					Type type4 = ex.Types?.FirstOrDefault((Type t) => t != null && t.IsClass && !t.IsAbstract && t.Name == "Plugin");
					if (type4 != null)
					{
						return type4;
					}
				}
			}
			return null;
		}

		public static MethodInfo GetStaticMethod(Type type, string methodName)
		{
			return type?.GetMethod(methodName, AllBindingFlags);
		}

		public static Type FindWishType(string typeName)
		{
			return FindType(typeName, "Wish");
		}

		public static object GetStaticValue(Type type, string memberName)
		{
			if (type == null)
			{
				return null;
			}
			try
			{
				PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
				if (property != null && property.GetMethod != null && property.GetIndexParameters().Length == 0)
				{
					return property.GetValue(null);
				}
			}
			catch (AmbiguousMatchException)
			{
				return null;
			}
			FieldInfo field = type.GetField(memberName, AllBindingFlags);
			if (field != null)
			{
				return field.GetValue(null);
			}
			return null;
		}

		public static object GetSingletonInstance(Type type)
		{
			if (type == null)
			{
				return null;
			}
			string[] array = new string[5] { "Instance", "instance", "_instance", "Singleton", "singleton" };
			foreach (string memberName in array)
			{
				object staticValue = GetStaticValue(type, memberName);
				if (staticValue != null)
				{
					return staticValue;
				}
			}
			return null;
		}

		public static object GetInstanceValue(object instance, string memberName)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
				if (property != null && property.GetMethod != null)
				{
					return property.GetValue(instance);
				}
				FieldInfo field = type.GetField(memberName, AllBindingFlags);
				if (field != null)
				{
					return field.GetValue(instance);
				}
				type = type.BaseType;
			}
			return null;
		}

		public static bool SetInstanceValue(object instance, string memberName, object value)
		{
			if (instance == null)
			{
				return false;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
				if (property != null && property.SetMethod != null)
				{
					property.SetValue(instance, value);
					return true;
				}
				FieldInfo field = type.GetField(memberName, AllBindingFlags);
				if (field != null)
				{
					field.SetValue(instance, value);
					return true;
				}
				type = type.BaseType;
			}
			return false;
		}

		public static object InvokeMethod(object instance, string methodName, params object[] args)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			Type[] array = args?.Select((object a) => a?.GetType() ?? typeof(object)).ToArray() ?? Type.EmptyTypes;
			MethodInfo methodInfo = AccessTools.Method(type, methodName, array, (Type[])null);
			if (methodInfo == null)
			{
				methodInfo = type.GetMethod(methodName, AllBindingFlags);
			}
			if (methodInfo == null)
			{
				return null;
			}
			return methodInfo.Invoke(instance, args);
		}

		public static object InvokeStaticMethod(Type type, string methodName, params object[] args)
		{
			if (type == null)
			{
				return null;
			}
			Type[] array = args?.Select((object a) => a?.GetType() ?? typeof(object)).ToArray() ?? Type.EmptyTypes;
			MethodInfo methodInfo = AccessTools.Method(type, methodName, array, (Type[])null);
			if (methodInfo == null)
			{
				methodInfo = type.GetMethod(methodName, AllBindingFlags);
			}
			if (methodInfo == null)
			{
				return null;
			}
			return methodInfo.Invoke(null, args);
		}

		public static FieldInfo[] GetAllFields(Type type)
		{
			if (type == null)
			{
				return Array.Empty<FieldInfo>();
			}
			FieldInfo[] fields = type.GetFields(AllBindingFlags);
			IEnumerable<FieldInfo> second;
			if (!(type.BaseType != null) || !(type.BaseType != typeof(object)))
			{
				second = Enumerable.Empty<FieldInfo>();
			}
			else
			{
				IEnumerable<FieldInfo> allFields = GetAllFields(type.BaseType);
				second = allFields;
			}
			return fields.Concat(second).Distinct().ToArray();
		}

		public static PropertyInfo[] GetAllProperties(Type type)
		{
			if (type == null)
			{
				return Array.Empty<PropertyInfo>();
			}
			PropertyInfo[] properties = type.GetProperties(AllBindingFlags);
			IEnumerable<PropertyInfo> second;
			if (!(type.BaseType != null) || !(type.BaseType != typeof(object)))
			{
				second = Enumerable.Empty<PropertyInfo>();
			}
			else
			{
				IEnumerable<PropertyInfo> allProperties = GetAllProperties(type.BaseType);
				second = allProperties;
			}
			return (from p in properties.Concat(second)
				group p by p.Name into g
				select g.First()).ToArray();
		}

		public static T TryGetValue<T>(object instance, string memberName, T defaultValue = default(T))
		{
			try
			{
				object instanceValue = GetInstanceValue(instance, memberName);
				if (instanceValue is T result)
				{
					return result;
				}
				if (instanceValue != null && typeof(T).IsAssignableFrom(instanceValue.GetType()))
				{
					return (T)instanceValue;
				}
				return defaultValue;
			}
			catch
			{
				return defaultValue;
			}
		}
	}
	public static class ItemSearch
	{
		private static readonly ManualLogSource _log = Logger.CreateLogSource("ItemSearch");

		private static object _dbInstance;

		private static FieldInfo _dictField;

		public static string FormatDisplay(string name, int itemId)
		{
			if (string.IsNullOrEmpty(name))
			{
				return $"#{itemId}";
			}
			return $"{name} (#{itemId})";
		}

		public static List<KeyValuePair<int, string>> SearchItems(string query, int maxResults = 50)
		{
			List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
			if (string.IsNullOrEmpty(query) || query.Trim().Length < 2)
			{
				return list;
			}
			try
			{
				Dictionary<int, ItemSellInfo> itemDictionary = GetItemDictionary();
				if (itemDictionary == null)
				{
					return list;
				}
				string text = query.Trim().ToLowerInvariant();
				int result;
				bool flag = int.TryParse(query.Trim(), out result);
				List<KeyValuePair<int, string>> list2 = new List<KeyValuePair<int, string>>();
				List<KeyValuePair<int, string>> list3 = new List<KeyValuePair<int, string>>();
				List<KeyValuePair<int, string>> list4 = new List<KeyValuePair<int, string>>();
				foreach (KeyValuePair<int, ItemSellInfo> item2 in itemDictionary)
				{
					int key = item2.Key;
					string text2 = item2.Value?.name;
					if (!string.IsNullOrEmpty(text2))
					{
						KeyValuePair<int, string> item = new KeyValuePair<int, string>(key, text2);
						string text3 = text2.ToLowerInvariant();
						if (flag && key == result)
						{
							list2.Add(item);
						}
						else if (text3 == text)
						{
							list2.Add(item);
						}
						else if (text3.StartsWith(text))
						{
							list3.Add(item);
						}
						else if (text3.Contains(text))
						{
							list4.Add(item);
						}
						else if (flag && key.ToString().Contains(query.Trim()))
						{
							list4.Add(item);
						}
					}
				}
				list3.Sort((KeyValuePair<int, string> a, KeyValuePair<int, string> b) => string.Compare(a.Value, b.Value, StringComparison.OrdinalIgnoreCase));
				list4.Sort((KeyValuePair<int, string> a, KeyValuePair<int, string> b) => string.Compare(a.Value, b.Value, StringComparison.OrdinalIgnoreCase));
				list.AddRange(list2);
				list.AddRange(list3);
				list.AddRange(list4);
				if (list.Count > maxResults)
				{
					list.RemoveRange(maxResults, list.Count - maxResults);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[ItemSearch] SearchItems error: " + ex.Message));
				}
			}
			return list;
		}

		public static string GetItemName(int itemId)
		{
			try
			{
				Dictionary<int, ItemSellInfo> itemDictionary = GetItemDictionary();
				if (itemDictionary == null || !itemDictionary.ContainsKey(itemId))
				{
					return null;
				}
				return itemDictionary[itemId]?.name;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)$"[ItemSearch] GetItemName({itemId}): {ex.Message}");
				}
				return null;
			}
		}

		public static ItemSellInfo GetItemSellInfo(int itemId)
		{
			try
			{
				Dictionary<int, ItemSellInfo> itemDictionary = GetItemDictionary();
				if (itemDictionary != null && itemDictionary.TryGetValue(itemId, out var value))
				{
					return value;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)$"[ItemSearch] GetItemSellInfo({itemId}): {ex.Message}");
				}
			}
			return null;
		}

		public static List<KeyValuePair<int, string>> GetAllItems()
		{
			List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
			try
			{
				Dictionary<int, ItemSellInfo> itemDictionary = GetItemDictionary();
				if (itemDictionary == null)
				{
					return list;
				}
				foreach (KeyValuePair<int, ItemSellInfo> item in itemDictionary)
				{
					string value = item.Value?.name;
					if (!string.IsNullOrEmpty(value))
					{
						list.Add(new KeyValuePair<int, string>(item.Key, value));
					}
				}
				list.Sort((KeyValuePair<int, string> a, KeyValuePair<int, string> b) => string.Compare(a.Value, b.Value, StringComparison.OrdinalIgnoreCase));
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[ItemSearch] GetAllItems: " + ex.Message));
				}
			}
			return list;
		}

		private static Dictionary<int, ItemSellInfo> GetItemDictionary()
		{
			try
			{
				if (_dbInstance != null)
				{
					object dbInstance = _dbInstance;
					Object val = (Object)((dbInstance is Object) ? dbInstance : null);
					if (val == null || !(val == (Object)null))
					{
						goto IL_005b;
					}
				}
				_dbInstance = null;
				_dictField = null;
				_dbInstance = GetSingletonInstance("Wish.ItemInfoDatabase");
				if (_dbInstance != null)
				{
					_dictField = _dbInstance.GetType().GetField("allItemSellInfos", BindingFlags.Instance | BindingFlags.Public);
				}
				goto IL_005b;
				IL_005b:
				if (_dbInstance == null || _dictField == null)
				{
					return null;
				}
				return _dictField.GetValue(_dbInstance) as Dictionary<int, ItemSellInfo>;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[ItemSearch] GetItemDictionary: " + ex.Message));
				}
				return null;
			}
		}

		private static object GetSingletonInstance(string typeName)
		{
			try
			{
				Type type = AccessTools.TypeByName("Wish.SingletonBehaviour`1");
				if (type == null)
				{
					return null;
				}
				Type type2 = AccessTools.TypeByName(typeName);
				if (type2 == null)
				{
					return null;
				}
				return type.MakeGenericType(type2).GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)?.GetValue(null);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[ItemSearch] GetSingletonInstance(" + typeName + "): " + ex.Message));
				}
				return null;
			}
		}
	}
	public static class TextInputFocusGuard
	{
		private const float DefaultPollIntervalSeconds = 0.25f;

		private static float _nextPollTime = -1f;

		private static bool _cachedDefer;

		private static bool _tmpTypeLookupDone;

		private static Type _tmpInputFieldType;

		private static bool _qcLookupDone;

		private static Type _qcType;

		private static PropertyInfo _qcInstanceProp;

		private static PropertyInfo _qcIsActiveProp;

		private static FieldInfo _qcIsActiveField;

		public static bool ShouldDeferModHotkeys(ManualLogSource debugLog = null, float pollIntervalSeconds = 0.25f)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < _nextPollTime)
			{
				return _cachedDefer;
			}
			_nextPollTime = realtimeSinceStartup + Mathf.Max(0.05f, pollIntervalSeconds);
			bool flag = false;
			try
			{
				if (GUIUtility.keyboardControl != 0)
				{
					flag = true;
				}
				if (!flag)
				{
					EventSystem current = EventSystem.current;
					GameObject val = ((current != null) ? current.currentSelectedGameObject : null);
					if ((Object)(object)val != (Object)null)
					{
						if ((Object)(object)val.GetComponent<InputField>() != (Object)null)
						{
							flag = true;
						}
						else if (TryGetTmpInputField(val))
						{
							flag = true;
						}
					}
				}
				if (!flag && IsQuantumConsoleActiveInternal(debugLog))
				{
					flag = true;
				}
			}
			catch (Exception ex)
			{
				if (debugLog != null)
				{
					debugLog.LogDebug((object)("[TextInputFocusGuard] " + ex.Message));
				}
			}
			_cachedDefer = flag;
			return flag;
		}

		private static bool TryGetTmpInputField(GameObject go)
		{
			if (!_tmpTypeLookupDone)
			{
				_tmpTypeLookupDone = true;
				_tmpInputFieldType = AccessTools.TypeByName("TMPro.TMP_InputField");
			}
			if (_tmpInputFieldType == null)
			{
				return false;
			}
			return (Object)(object)go.GetComponent(_tmpInputFieldType) != (Object)null;
		}

		public static bool IsQuantumConsoleActive(ManualLogSource debugLog = null)
		{
			return IsQuantumConsoleActiveInternal(debugLog);
		}

		public static bool IsUnityUiTextInputFocused()
		{
			try
			{
				EventSystem current = EventSystem.current;
				GameObject val = ((current != null) ? current.currentSelectedGameObject : null);
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				if ((Object)(object)val.GetComponent<InputField>() != (Object)null)
				{
					return true;
				}
				return TryGetTmpInputField(val);
			}
			catch
			{
				return false;
			}
		}

		private static bool IsQuantumConsoleActiveInternal(ManualLogSource debugLog)
		{
			try
			{
				if (!_qcLookupDone)
				{
					_qcLookupDone = true;
					_qcType = AccessTools.TypeByName("QFSW.QC.QuantumConsole");
					if (_qcType != null)
					{
						_qcInstanceProp = AccessTools.Property(_qcType, "Instance");
						_qcIsActiveProp = AccessTools.Property(_qcType, "IsActive");
						_qcIsActiveField = AccessTools.Field(_qcType, "isActive") ?? AccessTools.Field(_qcType, "_isActive");
					}
				}
				if (_qcType == null)
				{
					return false;
				}
				object obj = _qcInstanceProp?.GetValue(null);
				if (obj == null)
				{
					return false;
				}
				if (_qcIsActiveProp != null && _qcIsActiveProp.PropertyType == typeof(bool))
				{
					return (bool)_qcIsActiveProp.GetValue(obj);
				}
				if (_qcIsActiveField != null && _qcIsActiveField.FieldType == typeof(bool))
				{
					return (bool)_qcIsActiveField.GetValue(obj);
				}
			}
			catch (Exception ex)
			{
				if (debugLog != null)
				{
					debugLog.LogDebug((object)("[TextInputFocusGuard] Quantum Console focus check failed: " + ex.Message));
				}
			}
			return false;
		}
	}
	internal static class MinimalJsonParser
	{
		internal static void WriteJsonString(StringBuilder sb, string value)
		{
			sb.Append('"');
			if (value != null)
			{
				foreach (char c in value)
				{
					switch (c)
					{
					case '"':
						sb.Append("\\\"");
						break;
					case '\\':
						sb.Append("\\\\");
						break;
					case '\n':
						sb.Append("\\n");
						break;
					case '\r':
						sb.Append("\\r");
						break;
					case '\t':
						sb.Append("\\t");
						break;
					case '\b':
						sb.Append("\\b");
						break;
					case '\f':
						sb.Append("\\f");
						break;
					default:
						sb.Append(c);
						break;
					}
				}
			}
			sb.Append('"');
		}

		internal static void SkipWhitespace(string json, ref int pos)
		{
			while (pos < json.Length && char.IsWhiteSpace(json[pos]))
			{
				pos++;
			}
		}

		internal static object ParseValue(string json, ref int pos)
		{
			SkipWhitespace(json, ref pos);
			if (pos >= json.Length)
			{
				return null;
			}
			char c = json[pos];
			switch (c)
			{
			case '"':
				return ParseString(json, ref pos);
			case '{':
				return ParseObject(json, ref pos);
			case '[':
				return ParseArray(json, ref pos);
			case 't':
				return ParseLiteral(json, ref pos, "true", true);
			case 'f':
				return ParseLiteral(json, ref pos, "false", false);
			case 'n':
				return ParseLiteral(json, ref pos, "null", null);
			default:
				if (!char.IsDigit(c))
				{
					return null;
				}
				goto case '-';
			case '-':
				return ParseNumber(json, ref pos);
			}
		}

		internal static Dictionary<string, object> ParseObject(string json, ref int pos)
		{
			SkipWhitespace(json, ref pos);
			if (pos >= json.Length || json[pos] != '{')
			{
				return null;
			}
			pos++;
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			SkipWhitespace(json, ref pos);
			if (pos < json.Length && json[pos] == '}')
			{
				pos++;
				return dictionary;
			}
			while (pos < json.Length)
			{
				SkipWhitespace(json, ref pos);
				string text = ParseString(json, ref pos);
				if (text == null)
				{
					break;
				}
				SkipWhitespace(json, ref pos);
				if (pos >= json.Length || json[pos] != ':')
				{
					break;
				}
				pos++;
				SkipWhitespace(json, ref pos);
				dictionary[text] = ParseValue(json, ref pos);
				SkipWhitespace(json, ref pos);
				if (pos >= json.Length || json[pos] != ',')
				{
					break;
				}
				pos++;
			}
			SkipWhitespace(json, ref pos);
			if (pos < json.Length && json[pos] == '}')
			{
				pos++;
			}
			return dictionary;
		}

		internal static List<object> ParseArray(string json, ref int pos)
		{
			SkipWhitespace(json, ref pos);
			if (pos >= json.Length || json[pos] != '[')
			{
				return null;
			}
			pos++;
			List<object> list = new List<object>();
			SkipWhitespace(json, ref pos);
			if (pos < json.Length && json[pos] == ']')
			{
				pos++;
				return list;
			}
			while (pos < json.Length)
			{
				SkipWhitespace(json, ref pos);
				list.Add(ParseValue(json, ref pos));
				SkipWhitespace(json, ref pos);
				if (pos >= json.Length || json[pos] != ',')
				{
					break;
				}
				pos++;
			}
			SkipWhitespace(json, ref pos);
			if (pos < json.Length && json[pos] == ']')
			{
				pos++;
			}
			return list;
		}

		internal static string ParseString(string json, ref int pos)
		{
			SkipWhitespace(json, ref pos);
			if (pos >= json.Length || json[pos] != '"')
			{
				return null;
			}
			pos++;
			StringBuilder stringBuilder = new StringBuilder();
			while (pos < json.Length)
			{
				char c = json[pos];
				if (c == '\\' && pos + 1 < json.Length)
				{
					pos++;
					switch (json[pos])
					{
					case '"':
						stringBuilder.Append('"');
						break;
					case '\\':
						stringBuilder.Append('\\');
						break;
					case '/':
						stringBuilder.Append('/');
						break;
					case 'n':
						stringBuilder.Append('\n');
						break;
					case 'r':
						stringBuilder.Append('\r');
						break;
					case 't':
						stringBuilder.Append('\t');
						break;
					case 'b':
						stringBuilder.Append('\b');
						break;
					case 'f':
						stringBuilder.Append('\f');
						break;
					case 'u':
					{
						if (pos + 4 < json.Length && ushort.TryParse(json.Substring(pos + 1, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result))
						{
							pos += 4;
							if (result >= 55296 && result <= 56319 && pos + 5 < json.Length && json[pos] == '\\' && json[pos + 1] == 'u' && ushort.TryParse(json.Substring(pos + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result2) && result2 >= 56320 && result2 <= 57343)
							{
								stringBuilder.Append(char.ConvertFromUtf32(char.ConvertToUtf32((char)result, (char)result2)));
								pos += 6;
							}
							else
							{
								stringBuilder.Append((char)result);
							}
						}
						else
						{
							stringBuilder.Append('u');
						}
						break;
					}
					default:
						stringBuilder.Append(json[pos]);
						break;
					}
					pos++;
				}
				else
				{
					if (c == '"')
					{
						pos++;
						return stringBuilder.ToString();
					}
					stringBuilder.Append(c);
					pos++;
				}
			}
			return stringBuilder.ToString();
		}

		internal static object ParseNumber(string json, ref int pos)
		{
			int num = pos;
			bool flag = false;
			if (pos < json.Length && json[pos] == '-')
			{
				pos++;
			}
			while (pos < json.Length && char.IsDigit(json[pos]))
			{
				pos++;
			}
			if (pos < json.Length && json[pos] == '.')
			{
				flag = true;
				pos++;
				while (pos < json.Length && char.IsDigit(json[pos]))
				{
					pos++;
				}
			}
			if (pos < json.Length && (json[pos] == 'e' || json[pos] == 'E'))
			{
				flag = true;
				pos++;
				if (pos < json.Length && (json[pos] == '+' || json[pos] == '-'))
				{
					pos++;
				}
				while (pos < json.Length && char.IsDigit(json[pos]))
				{
					pos++;
				}
			}
			string s = json.Substring(num, pos - num);
			if (flag && double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			if (!flag && long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2))
			{
				return result2;
			}
			return 0L;
		}

		internal static object ParseLiteral(string json, ref int pos, string literal, object result)
		{
			if (pos + literal.Length <= json.Length && json.Substring(pos, literal.Length) == literal)
			{
				pos += literal.Length;
				return result;
			}
			pos++;
			return null;
		}

		internal static int ToInt(object val)
		{
			if (val is long num)
			{
				return (int)num;
			}
			if (val is double num2)
			{
				return (int)num2;
			}
			if (val is int)
			{
				return (int)val;
			}
			return 0;
		}
	}
	public static class ModLocalization
	{
		private static readonly string[] SupportedLanguageCodes = new string[16]
		{
			"en", "da", "de", "es", "fr", "it", "ja", "ko", "nl", "pt",
			"pt-BR", "ru", "sv", "zh-CN", "zh-TW", "uk"
		};

		private static readonly Dictionary<string, string> LanguageAlias = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			{ "pt-br", "pt-BR" },
			{ "pt_br", "pt-BR" },
			{ "zh-cn", "zh-CN" },
			{ "zh_cn", "zh-CN" },
			{ "zh-tw", "zh-TW" },
			{ "zh_tw", "zh-TW" }
		};

		private static string _modId;

		private static Dictionary<string, Dictionary<string, string>> _tables;

		private static ManualLogSource _log;

		private static bool _initialized;

		private static bool _forceEnglish;

		public static string CurrentLanguage { get; private set; } = "en";

		public static bool ForceEnglish => _forceEnglish;

		public static bool IsReady
		{
			get
			{
				if (_initialized && _tables != null)
				{
					return _tables.Count > 0;
				}
				return false;
			}
		}

		public static event Action<string> LanguageChanged
		{
			add
			{
				LanguageChangeWatcher.LanguageChanged += value;
			}
			remove
			{
				LanguageChangeWatcher.LanguageChanged -= value;
			}
		}

		public static void Init(string modId, Dictionary<string, Dictionary<string, string>> tables, Harmony harmony, ManualLogSource log)
		{
			_modId = modId ?? string.Empty;
			_tables = tables ?? new Dictionary<string, Dictionary<string, string>>();
			_log = log;
			_initialized = true;
			RefreshCurrentLanguage();
			LanguageChangeWatcher.EnsurePatched(harmony);
		}

		public static void SetForceEnglish(bool forceEnglish)
		{
			_forceEnglish = forceEnglish;
			ApplyEffectiveLanguage();
		}

		internal static void OnGameLanguageChanged(string languageCode)
		{
			if (_tables == null || _forceEnglish)
			{
				return;
			}
			string text = NormalizeLanguageCode(languageCode);
			if (!string.Equals(CurrentLanguage, text, StringComparison.OrdinalIgnoreCase))
			{
				CurrentLanguage = text;
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[" + _modId + "] Language changed to " + CurrentLanguage));
				}
			}
		}

		public static void RefreshCurrentLanguage()
		{
			ApplyEffectiveLanguage();
		}

		private static void ApplyEffectiveLanguage()
		{
			if (_forceEnglish)
			{
				CurrentLanguage = "en";
			}
			else
			{
				RefreshCurrentLanguageFromGame();
			}
		}

		private static void RefreshCurrentLanguageFromGame()
		{
			try
			{
				string currentLanguageCode = LocalizationManager.CurrentLanguageCode;
				if (!string.IsNullOrWhiteSpace(currentLanguageCode))
				{
					CurrentLanguage = NormalizeLanguageCode(currentLanguageCode);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("[" + _modId + "] Failed to read LocalizationManager.CurrentLanguageCode: " + ex.Message));
				}
				CurrentLanguage = "en";
			}
		}

		public static string T(string key)
		{
			if (!TryT(key, out string value))
			{
				return key;
			}
			return value;
		}

		public static string T(string key, params object[] args)
		{
			string text = T(key);
			if (args == null || args.Length == 0)
			{
				return text;
			}
			try
			{
				return string.Format(CultureInfo.InvariantCulture, text, args);
			}
			catch (FormatException ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("[" + _modId + "] Format failed for key '" + key + "': " + ex.Message));
				}
				return text;
			}
		}

		public static bool TryT(string key, out string value)
		{
			value = null;
			if (string.IsNullOrEmpty(key))
			{
				return false;
			}
			if (_tables == null || !_tables.TryGetValue(key, out Dictionary<string, string> value2) || value2 == null)
			{
				return false;
			}
			if (TryGetForLanguage(value2, CurrentLanguage, out value))
			{
				return true;
			}
			if (!string.Equals(CurrentLanguage, "en", StringComparison.OrdinalIgnoreCase) && TryGetForLanguage(value2, "en", out value))
			{
				return true;
			}
			return false;
		}

		private static bool TryGetForLanguage(Dictionary<string, string> translations, string languageCode, out string value)
		{
			value = null;
			if (translations == null)
			{
				return false;
			}
			string text = NormalizeLanguageCode(languageCode);
			if (translations.TryGetValue(text, out value) && !string.IsNullOrEmpty(value))
			{
				return true;
			}
			foreach (KeyValuePair<string, string> translation in translations)
			{
				if (string.Equals(translation.Key, text, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(translation.Value))
				{
					value = translation.Value;
					return true;
				}
			}
			return false;
		}

		public static string NormalizeLanguageCode(string code)
		{
			if (string.IsNullOrWhiteSpace(code))
			{
				return "en";
			}
			string text = code.Trim();
			if (LanguageAlias.TryGetValue(text, out string value))
			{
				return value;
			}
			string[] supportedLanguageCodes = SupportedLanguageCodes;
			foreach (string text2 in supportedLanguageCodes)
			{
				if (string.Equals(text2, text, StringComparison.OrdinalIgnoreCase))
				{
					return text2;
				}
			}
			return "en";
		}

		public static Dictionary<string, Dictionary<string, string>> ParseStringsJson(string json)
		{
			Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
			if (string.IsNullOrWhiteSpace(json))
			{
				return dictionary;
			}
			int pos = 0;
			Dictionary<string, object> dictionary2 = MinimalJsonParser.ParseObject(json, ref pos);
			if (dictionary2 == null)
			{
				return dictionary;
			}
			foreach (KeyValuePair<string, object> item in dictionary2)
			{
				if (!(item.Value is Dictionary<string, object> dictionary3))
				{
					continue;
				}
				Dictionary<string, string> dictionary4 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
				foreach (KeyValuePair<string, object> item2 in dictionary3)
				{
					if (item2.Value is string value)
					{
						dictionary4[NormalizeLanguageCode(item2.Key)] = value;
					}
				}
				if (dictionary4.Count > 0)
				{
					dictionary[item.Key] = dictionary4;
				}
			}
			return dictionary;
		}

		public static Dictionary<string, Dictionary<string, string>> LoadEmbeddedStrings(Assembly assembly, string resourceName, ManualLogSource log = null)
		{
			try
			{
				using Stream stream = assembly.GetManifestResourceStream(resourceName);
				if (stream == null)
				{
					if (log != null)
					{
						log.LogError((object)("Localization resource not found: " + resourceName));
					}
					return new Dictionary<string, Dictionary<string, string>>();
				}
				using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
				return ParseStringsJson(streamReader.ReadToEnd());
			}
			catch (Exception ex)
			{
				if (log != null)
				{
					log.LogError((object)("Failed to load localization resource '" + resourceName + "': " + ex.Message));
				}
				return new Dictionary<string, Dictionary<string, string>>();
			}
		}

		public static void Shutdown()
		{
			_log = null;
		}
	}
	public static class LanguageChangeWatcher
	{
		private static bool _patched;

		public static event Action<string> LanguageChanged;

		public static void EnsurePatched(Harmony harmony)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if (_patched || harmony == null)
			{
				return;
			}
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(LanguageChangeWatcher), "OnSetLanguageAndCode", (Type[])null, (Type[])null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(LocalizationManager), "SetLanguageAndCode", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_patched = true;
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException("Failed to patch LocalizationManager.SetLanguageAndCode", innerException);
			}
		}

		private static void OnSetLanguageAndCode(string LanguageName, string LanguageCode)
		{
			string text = ModLocalization.NormalizeLanguageCode(string.IsNullOrWhiteSpace(LanguageCode) ? LocalizationManager.CurrentLanguageCode : LanguageCode);
			ModLocalization.OnGameLanguageChanged(text);
			LanguageChangeWatcher.LanguageChanged?.Invoke(text);
		}

		internal static void RaiseLanguageChanged(string languageCode)
		{
			string obj = ModLocalization.NormalizeLanguageCode(languageCode);
			LanguageChangeWatcher.LanguageChanged?.Invoke(obj);
		}
	}
	public static class LocalizationBootstrap
	{
		public static ConfigEntry<bool> BindForceEnglish(ConfigFile config)
		{
			ConfigEntry<bool> entry = config.Bind<bool>("Localization", "ForceEnglish", false, "Keep this mod's UI in English and ignore Sun Haven's in-game language setting.");
			ApplyForceEnglish(entry.Value);
			entry.SettingChanged += delegate
			{
				ApplyForceEnglish(entry.Value);
			};
			return entry;
		}

		private static void ApplyForceEnglish(bool forceEnglish)
		{
			ModLocalization.SetForceEnglish(forceEnglish);
			LanguageChangeWatcher.RaiseLanguageChanged(ModLocalization.CurrentLanguage);
		}

		public static void Init(string pluginGuid, Harmony harmony, ManualLogSource log, Assembly assembly = null)
		{
			if ((object)assembly == null)
			{
				assembly = Assembly.GetCallingAssembly();
			}
			Dictionary<string, Dictionary<string, string>> tables = ModLocalization.LoadEmbeddedStrings(assembly, pluginGuid + ".Localization.strings.json", log);
			ModLocalization.Init(pluginGuid, tables, harmony, log);
		}

		public static void EnsureInitialized(string pluginGuid, Harmony harmony, ManualLogSource log, Assembly assembly = null)
		{
			if (!ModLocalization.IsReady)
			{
				Init(pluginGuid, harmony, log, assembly);
			}
		}
	}
}
namespace HavenDevTools
{
	[BepInPlugin("com.azraelgodking.havendevtools", "Haven Dev Tools", "2.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private static ItemInspector _staticItemInspector;

		private static CurrencyTracker _staticCurrencyTracker;

		private static BundleInspector _staticBundleInspector;

		private static RaceModifierTracker _staticRaceModifierTracker;

		private static DebugWindow _staticDebugWindow;

		private static DebugOverlay _staticDebugOverlay;

		private static FpsCounterOverlay _staticFpsCounterOverlay;

		private static CommandConsole _staticCommandConsole;

		private static LogViewerPanel _staticLogViewer;

		private static GameObject _persistentRunner;

		private static PersistentRunner _persistentRunnerComponent;

		internal static KeyCode StaticToggleKey = (KeyCode)292;

		internal static KeyCode StaticOverlayToggleKey = (KeyCode)287;

		private static string _currentPlayerName;

		private Harmony _harmony;

		private bool _applicationQuitting;

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		public static ConfigFile ConfigFile { get; private set; }

		public static bool HasTheVault { get; private set; }

		public static bool HasSMUT { get; private set; }

		public static bool HasHavensBirthright { get; private set; }

		public static bool HasSenpaisChest { get; private set; }

		public static bool HasBirthdayReminder { get; private set; }

		public static bool HasSunhavenTodo { get; private set; }

		public static bool HasHavensAlmanac { get; private set; }

		public static bool HasTrinketFortune { get; private set; }

		public static bool HasCropOptimizer { get; private set; }

		public static bool HasFasterRaces { get; private set; }

		public static bool HasHavensRespec { get; private set; }

		public static bool HasGiftingAssistant { get; private set; }

		public static bool HasUltraPolygamy => UltraPolygamyHelper.IsAvailable;

		public static bool IsAuthorized => true;

		public static string CurrentPlayerName => _currentPlayerName;

		private void Awake()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			ConfigFile = CreateNamedConfig();
			ConfigFileHelper.ReplacePluginConfig((BaseUnityPlugin)(object)this, ConfigFile, (Action<string>)Log.LogWarning);
			Log.LogInfo((object)"Loading Haven Dev Tools v2.1.1");
			try
			{
				ModConfig.Initialize(ConfigFile);
				StaticToggleKey = ModConfig.ToggleKey.Value;
				StaticOverlayToggleKey = ModConfig.OverlayToggleKey.Value;
				CreatePersistentRunner();
				DetectInstalledMods();
				ModConfig.SyncTheVaultFullVaultInspectorToPlugin();
				_staticItemInspector = new ItemInspector();
				_staticCurrencyTracker = new CurrencyTracker();
				_staticBundleInspector = new BundleInspector();
				_staticRaceModifierTracker = new RaceModifierTracker();
				_staticCommandConsole = new CommandConsole();
				_staticLogViewer = new LogViewerPanel();
				CreateUIComponents();
				_harmony = new Harmony("com.azraelgodking.havendevtools");
				LocalizationBootstrap.BindForceEnglish(ConfigFile);
				LocalizationBootstrap.Init("com.azraelgodking.havendevtools", _harmony, Log);
				PatchPlayerInit();
				SceneManager.sceneLoaded += OnSceneLoaded;
				if (ModConfig.CheckForUpdates.Value)
				{
					VersionChecker.CheckForUpdate("com.azraelgodking.havendevtools", "2.1.1", Log, delegate(VersionChecker.VersionCheckResult result)
					{
						result.NotifyUpdateAvailable(Log);
					});
				}
				Log.LogInfo((object)"Haven Dev Tools loaded successfully!");
				ReportStartupHealth();
				Log.LogInfo((object)$"Press {ModConfig.ToggleKey.Value} to open the debug window (requires authorization)");
				Log.LogInfo((object)$"Press {ModConfig.OverlayToggleKey.Value} to toggle the overlay");
				Log.LogInfo((object)$"Detected mods - TheVault: {HasTheVault}, SMUT: {HasSMUT}, Birthright: {HasHavensBirthright}, SenpaisChest: {HasSenpaisChest}, Birthday: {HasBirthdayReminder}, Todo: {HasSunhavenTodo}, Almanac: {HasHavensAlmanac}, TrinketFortune: {HasTrinketFortune}");
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("Failed to load {0}: {1}", "Haven Dev Tools", arg));
			}
		}

		private static ConfigFile CreateNamedConfig()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			string text = Path.Combine(Paths.ConfigPath, "HavenDevTools.cfg");
			string text2 = Path.Combine(Paths.ConfigPath, "com.azraelgodking.havendevtools.cfg");
			try
			{
				if (!File.Exists(text) && File.Exists(text2))
				{
					File.Copy(text2, text);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)("[Config] Migration to HavenDevTools.cfg failed: " + ex.Message));
				}
			}
			return new ConfigFile(text, true);
		}

		private void CreatePersistentRunner()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (!((Object)(object)_persistentRunner != (Object)null) || !((Object)(object)_persistentRunnerComponent != (Object)null))
			{
				_persistentRunner = new GameObject("HavenDevTools_PersistentRunner");
				Object.DontDestroyOnLoad((Object)(object)_persistentRunner);
				((Object)_persistentRunner).hideFlags = (HideFlags)61;
				SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(_persistentRunner);
				_persistentRunnerComponent = _persistentRunner.AddComponent<PersistentRunner>();
				Log.LogInfo((object)"[PersistentRunner] Created hidden persistent runner");
			}
		}

		private void CreateUIComponents()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("HavenDevTools_UI");
			Object.DontDestroyOnLoad((Object)val);
			_staticDebugWindow = val.AddComponent<DebugWindow>();
			_staticDebugOverlay = val.AddComponent<DebugOverlay>();
			_staticFpsCounterOverlay = val.AddComponent<FpsCounterOverlay>();
			Log.LogInfo((object)"UI components created");
		}

		public static void EnsureUIComponentsExist()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)_persistentRunner == (Object)null || (Object)(object)_persistentRunnerComponent == (Object)null)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogInfo((object)"[EnsureUI] Recreating PersistentRunner...");
					}
					_persistentRunner = new GameObject("HavenDevTools_PersistentRunner");
					Object.DontDestroyOnLoad((Object)(object)_persistentRunner);
					((Object)_persistentRunner).hideFlags = (HideFlags)61;
					SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(_persistentRunner);
					_persistentRunnerComponent = _persistentRunner.AddComponent<PersistentRunner>();
					ManualLogSource log2 = Log;
					if (log2 != null)
					{
						log2.LogInfo((object)"[EnsureUI] PersistentRunner recreated");
					}
				}
				if ((Object)(object)_staticDebugWindow == (Object)null || (Object)(object)_staticDebugOverlay == (Object)null || (Object)(object)_staticFpsCounterOverlay == (Object)null)
				{
					ManualLogSource log3 = Log;
					if (log3 != null)
					{
						log3.LogInfo((object)"[EnsureUI] Recreating UI components...");
					}
					GameObject val = new GameObject("HavenDevTools_UI");
					Object.DontDestroyOnLoad((Object)val);
					_staticDebugWindow = val.AddComponent<DebugWindow>();
					_staticDebugOverlay = val.AddComponent<DebugOverlay>();
					_staticFpsCounterOverlay = val.AddComponent<FpsCounterOverlay>();
					ManualLogSource log4 = Log;
					if (log4 != null)
					{
						log4.LogInfo((object)"[EnsureUI] UI components recreated");
					}
				}
				if (_staticItemInspector == null)
				{
					_staticItemInspector = new ItemInspector();
				}
				if (_staticCurrencyTracker == null)
				{
					_staticCurrencyTracker = new CurrencyTracker();
				}
				if (_staticBundleInspector == null)
				{
					_staticBundleInspector = new BundleInspector();
				}
				if (_staticRaceModifierTracker == null)
				{
					_staticRaceModifierTracker = new RaceModifierTracker();
				}
				if (_staticCommandConsole == null)
				{
					_staticCommandConsole = new CommandConsole();
				}
				if (_staticLogViewer == null)
				{
					_staticLogViewer = new LogViewerPanel();
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log5 = Log;
				if (log5 != null)
				{
					log5.LogError((object)("[EnsureUI] Error recreating components: " + ex.Message));
				}
			}
		}

		public static void RefreshInstalledMods()
		{
			HasTheVault = IsSuitePluginLoaded("com.azraelgodking.thevault", "TheVault");
			HasSMUT = IsSuitePluginLoaded("com.azraelgodking.sunhavenmuseumutilitytracker", "SunHavenMuseumUtilityTracker");
			HasHavensBirthright = IsSuitePluginLoaded("com.azraelgodking.havensbirthright", "HavensBirthright");
			HasSenpaisChest = IsSuitePluginLoaded("com.azraelgodking.senpaischest", "SenpaisChest");
			HasBirthdayReminder = IsSuitePluginLoaded("com.azraelgodking.squirrelsbirthdayreminder", "BirthdayReminder");
			HasSunhavenTodo = IsSuitePluginLoaded("com.azraelgodking.sunhaventodo", "SunhavenTodo");
			HasHavensAlmanac = IsSuitePluginLoaded("com.azraelgodking.havensalmanac", "HavensAlmanac");
			HasTrinketFortune = IsSuitePluginLoaded("com.azraelgodking.trinketfortune", "TrinketFortune");
			HasCropOptimizer = IsSuitePluginLoaded("com.azraelgodking.cropoptimizer", "CropOptimizer");
			HasFasterRaces = IsSuitePluginLoaded("com.azraelgodking.fasterraces", "FasterRaces");
			HasHavensRespec = IsSuitePluginLoaded("com.azraelgodking.havensrespec", "HavensRespec");
			HasGiftingAssistant = IsSuitePluginLoaded("com.azraelgodking.giftingassistant", "GiftingAssistant");
		}

		private static bool IsSuitePluginLoaded(string pluginGuid, string assemblyName)
		{
			if (Chainloader.PluginInfos != null && !string.IsNullOrEmpty(pluginGuid) && Chainloader.PluginInfos.ContainsKey(pluginGuid))
			{
				return true;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				if (string.Equals(assemblies[i].GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private void DetectInstalledMods()
		{
			RefreshInstalledMods();
			Log.LogInfo((object)$"Mod detection complete - TheVault: {HasTheVault}, SMUT: {HasSMUT}, Birthright: {HasHavensBirthright}, SenpaisChest: {HasSenpaisChest}, Birthday: {HasBirthdayReminder}, Todo: {HasSunhavenTodo}, Almanac: {HasHavensAlmanac}, TrinketFortune: {HasTrinketFortune}, CropOptimizer: {HasCropOptimizer}, FasterRaces: {HasFasterRaces}, Respec: {HasHavensRespec}, GiftingAssistant: {HasGiftingAssistant}, UltraPolygamy: {HasUltraPolygamy}");
		}

		private void ReportStartupHealth()
		{
			ModDiagnostics.LogModStartup(Log, "com.azraelgodking.havendevtools", "Haven Dev Tools", "2.1.1", "Suite tabs: " + ModHealthIntegrationSummary.Build(("Vault", "com.azraelgodking.thevault"), ("SMUT", "com.azraelgodking.sunhavenmuseumutilitytracker"), ("Birthright", "com.azraelgodking.havensbirthright"), ("SenpaisChest", "com.azraelgodking.senpaischest"), ("Birthday", "com.azraelgodking.squirrelsbirthdayreminder"), ("Todo", "com.azraelgodking.sunhaventodo"), ("Almanac", "com.azraelgodking.havensalmanac"), ("TrinketFortune", "com.azraelgodking.trinketfortune"), ("CropOptimizer", "com.azraelgodking.cropoptimizer"), ("FasterRaces", "com.azraelgodking.fasterraces"), ("Respec", "com.azraelgodking.havensrespec"), ("GiftingAssistant", "com.azraelgodking.giftingassistant")), "startup", false);
		}

		private void PatchPlayerInit()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "InitializeAsOwner", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "OnPlayerInitialized", (Type[])null, (Type[])null);
					_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Log.LogInfo((object)"Patched Player.InitializeAsOwner");
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Failed to patch player init: " + ex.Message));
			}
		}

		private static void OnPlayerInitialized()
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)"[HavenDevTools] Player initialized, ensuring UI exists...");
			}
			EnsureUIComponentsExist();
			UpdatePlayerContext();
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			Log.LogDebug((object)("[SceneChange] Scene loaded: '" + ((Scene)(ref scene)).name + "'"));
			string text = ((Scene)(ref scene)).name.ToLowerInvariant();
			if (text.Contains("menu") || text.Contains("title"))
			{
				Log.LogDebug((object)("Menu scene detected: " + ((Scene)(ref scene)).name));
				_currentPlayerName = null;
			}
		}

		private void OnApplicationQuit()
		{
			_applicationQuitting = true;
		}

		private void OnDestroy()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			SceneManager.sceneLoaded -= OnSceneLoaded;
			Scene activeScene = SceneManager.GetActiveScene();
			string text = ((Scene)(ref activeScene)).name ?? string.Empty;
			string text2 = text.ToLowerInvariant();
			if (_applicationQuitting || !Application.isPlaying || text2.Contains("menu") || text2.Contains("title"))
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)("[Lifecycle] Plugin OnDestroy during expected teardown (scene: " + text + ")"));
				}
			}
			else
			{
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("[Lifecycle] Plugin OnDestroy outside expected teardown (scene: " + text + ")"));
				}
			}
		}

		private static void UpdatePlayerContext()
		{
			try
			{
				if ((Object)(object)Player.Instance != (Object)null)
				{
					PropertyInfo property = ((object)Player.Instance).GetType().GetProperty("PlayerName", BindingFlags.Instance | BindingFlags.Public);
					if (property != null)
					{
						_currentPlayerName = property.GetValue(Player.Instance) as string;
					}
					if (string.IsNullOrEmpty(_currentPlayerName))
					{
						_currentPlayerName = ((Object)Player.Instance).name;
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogDebug((object)("[HavenDevTools] Player name fallback: " + ex.Message));
				}
				_currentPlayerName = "Unknown";
			}
		}

		public static ItemInspector GetItemInspector()
		{
			return _staticItemInspector;
		}

		public static CurrencyTracker GetCurrencyTracker()
		{
			return _staticCurrencyTracker;
		}

		public static BundleInspector GetBundleInspector()
		{
			return _staticBundleInspector;
		}

		public static RaceModifierTracker GetRaceModifierTracker()
		{
			return _staticRaceModifierTracker;
		}

		public static DebugWindow GetDebugWindow()
		{
			return _staticDebugWindow;
		}

		public static DebugOverlay GetDebugOverlay()
		{
			return _staticDebugOverlay;
		}

		public static CommandConsole GetCommandConsole()
		{
			return _staticCommandConsole;
		}

		public static LogViewerPanel GetLogViewer()
		{
			return _staticLogViewer;
		}

		public static void ToggleDebugWindow()
		{
			_staticDebugWindow?.Toggle();
		}

		public static void ToggleDebugOverlay()
		{
			_staticDebugOverlay?.Toggle();
		}
	}
	public class PersistentRunner : MonoBehaviour
	{
		private float _heartbeatTimer;

		private int _heartbeatCount;

		private const float HEARTBEAT_INTERVAL = 30f;

		private bool _syncedTheVaultInspectorOnce;

		private void Awake()
		{
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[PersistentRunner] Awake - hidden persistent runner active");
			}
		}

		private void Update()
		{
			if (!_syncedTheVaultInspectorOnce)
			{
				_syncedTheVaultInspectorOnce = true;
				Plugin.RefreshInstalledMods();
				ModConfig.SyncTheVaultFullVaultInspectorToPlugin();
			}
			CheckHotkeys();
			_heartbeatTimer += Time.deltaTime;
			if (_heartbeatTimer >= 30f)
			{
				_heartbeatTimer = 0f;
				_heartbeatCount++;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)string.Format("[PersistentRunner Heartbeat #{0}] Player: {1}", _heartbeatCount, Plugin.CurrentPlayerName ?? "none"));
				}
			}
		}

		private void CheckHotkeys()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!TextInputFocusGuard.ShouldDeferModHotkeys(Plugin.Log))
				{
					if (Input.GetKeyDown(Plugin.StaticToggleKey))
					{
						Plugin.ToggleDebugWindow();
					}
					if (Input.GetKeyDown(Plugin.StaticOverlayToggleKey))
					{
						Plugin.ToggleDebugOverlay();
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[PersistentRunner] Hotkey error: " + ex.Message));
				}
			}
		}

		private void OnDestroy()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			string text = (((Scene)(ref activeScene)).name ?? string.Empty).ToLowerInvariant();
			if (!Application.isPlaying || text.Contains("menu") || text.Contains("title"))
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[PersistentRunner] OnDestroy during app quit/menu unload (expected).");
				}
			}
			else
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"[PersistentRunner] OnDestroy outside quit/menu (unexpected).");
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "com.azraelgodking.havendevtools";

		public const string PLUGIN_NAME = "Haven Dev Tools";

		public const string PLUGIN_VERSION = "2.1.1";
	}
}
namespace HavenDevTools.UI
{
	public class DebugOverlay : MonoBehaviour
	{
		private bool _isVisible;

		private GUIStyle _overlayStyle;

		private GUIStyle _labelStyle;

		private GUIStyle _valueStyle;

		private bool _stylesInitialized;

		private float _updateTimer;

		private const float UPDATE_INTERVAL = 0.5f;

		private string _playerName = "";

		private string _currentRace = "";

		private int _gold;

		private string _heldItemInfo = "";

		private string _position = "";

		private void Awake()
		{
			_isVisible = ModConfig.ShowOverlayOnStart?.Value ?? false;
		}

		public void Toggle()
		{
			_isVisible = !_isVisible;
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("[DebugOverlay] " + (_isVisible ? "Shown" : "Hidden")));
			}
		}

		public void Show()
		{
			_isVisible = true;
		}

		public void Hide()
		{
			_isVisible = false;
		}

		private void Update()
		{
			if (_isVisible)
			{
				_updateTimer += Time.deltaTime;
				if (_updateTimer >= 0.5f)
				{
					_updateTimer = 0f;
					UpdateCachedData();
				}
			}
		}

		private void UpdateCachedData()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				_playerName = Plugin.CurrentPlayerName ?? "Unknown";
				_currentRace = Plugin.GetRaceModifierTracker()?.GetCurrentRace() ?? "Unknown";
				_gold = Plugin.GetCurrencyTracker()?.GetGold() ?? 0;
				(int, string)? tuple = Plugin.GetItemInspector()?.GetHeldItem();
				_heldItemInfo = (tuple.HasValue ? $"{tuple.Value.Item2} ({tuple.Value.Item1})" : "None");
				if ((Object)(object)Player.Instance != (Object)null)
				{
					Vector3 position = ((Component)Player.Instance).transform.position;
					_position = $"({position.x:F1}, {position.y:F1})";
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[DebugOverlay] Update error: " + ex.Message));
				}
			}
		}

		private void OnGUI()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (_isVisible)
			{
				InitializeStyles();
				OverlayPositionType overlayPosition = ModConfig.GetOverlayPosition();
				Rect overlayRect = GetOverlayRect(overlayPosition);
				GUI.Box(overlayRect, "", _overlayStyle);
				GUILayout.BeginArea(new Rect(((Rect)(ref overlayRect)).x + 8f, ((Rect)(ref overlayRect)).y + 8f, ((Rect)(ref overlayRect)).width - 16f, ((Rect)(ref overlayRect)).height - 16f));
				DrawOverlayContent();
				GUILayout.EndArea();
			}
		}

		private void InitializeStyles()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			if (!_stylesInitialized)
			{
				Texture2D val = new Texture2D(1, 1);
				val.SetPixel(0, 0, new Color(0.05f, 0.05f, 0.1f, 0.85f));
				val.Apply();
				GUIStyle val2 = new GUIStyle(GUI.skin.box);
				val2.normal.background = val;
				_overlayStyle = val2;
				GUIStyle val3 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 11
				};
				val3.normal.textColor = new Color(0.7f, 0.7f, 0.8f);
				_labelStyle = val3;
				GUIStyle val4 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 11,
					fontStyle = (FontStyle)1
				};
				val4.normal.textColor = new Color(0.9f, 0