Decompiled source of BetterPortuguese v0.2.7

plugins/BetterPortuguese/BetterPortuguese.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BetterPortuguese.Core;
using BetterPortuguese.Runtime;
using Burst2Flame;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("BetterPortuguese")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.7.0")]
[assembly: AssemblyInformationalVersion("0.2.7")]
[assembly: AssemblyProduct("BetterPortuguese")]
[assembly: AssemblyTitle("BetterPortuguese")]
[assembly: AssemblyVersion("0.2.7.0")]
namespace BetterPortuguese
{
	[BepInPlugin("com.gumatos.betterportuguese", "BetterPortuguese", "0.2.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.gumatos.betterportuguese";

		public const string Versao = "0.2.7";

		private static readonly StateQueue States = new StateQueue();

		private static Overlay<LocalizationEntry> overlay;

		private static ISet<string> changedKeys = new HashSet<string>(StringComparer.Ordinal);

		private static OnceLog limited;

		private static ManualLogSource log;

		private static Action poll;

		private static bool firstLookup;

		private static bool refreshPending;

		private static float nextPoll;

		private ConfigEntry<bool> active;

		private ConfigEntry<bool> integrate;

		private ConfigEntry<bool> diagnostic;

		private ConfigEntry<Conjunto> variant;

		private string lastFile;

		private Harmony harmony;

		private void Awake()
		{
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			log = ((BaseUnityPlugin)this).Logger;
			limited = new OnceLog(delegate(string s)
			{
				log.LogWarning((object)s);
			});
			try
			{
				bool num = !File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath);
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
				active = ((BaseUnityPlugin)this).Config.Bind<bool>("Geral", "Ativo", true, "Ativa somente as camadas do BetterPortuguese.");
				variant = ((BaseUnityPlugin)this).Config.Bind<Conjunto>("Geral", "Conjunto", Conjunto.Corrigido, "Corrigido (padrao) ou Original. Original deixa a localizacao vigente do jogo intacta.");
				integrate = ((BaseUnityPlugin)this).Config.Bind<bool>("Geral", "IntegracaoMods", true, "Traduz os blocos do BetterTooltips homologado depois da ordem do BT; nao altera a camada base.");
				diagnostic = ((BaseUnityPlugin)this).Config.Bind<bool>("Geral", "Diagnostico", false, "Log de estado e patches, sem log por frame/chave.");
				if (num)
				{
					((BaseUnityPlugin)this).Config.Save();
				}
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
				((BaseUnityPlugin)this).Config.SettingChanged += delegate
				{
					QueueEntries();
				};
				poll = PollFile;
				QueueEntries();
				PollFile();
			}
			catch (Exception ex)
			{
				poll = null;
				States.Enqueue(new Settings(active: false, Conjunto.Corrigido, integrateMods: true, diagnostic: false, valid: false));
				log.LogError((object)("BetterPortuguese: config indisponivel, overrides desativados: " + ex.Message));
			}
			try
			{
				Catalog catalog = Resources.Load(typeof(Plugin).Assembly);
				changedKeys = new HashSet<string>(catalog.Changed.Keys, StringComparer.Ordinal);
				overlay = new Overlay<LocalizationEntry>(catalog, Bindings.Equal, Bindings.Clone, limited);
				log.LogInfo((object)("BetterPortuguese 0.2.7: snapshots completos; " + catalog.Original.Records.Count + " registros; " + catalog.Changed.Count + " chaves corrigidas aprovadas."));
			}
			catch (Exception ex2)
			{
				overlay = null;
				log.LogError((object)("BetterPortuguese: camada base desativada: " + ex2.Message));
			}
			ModCatalog modCatalog = null;
			try
			{
				modCatalog = Resources.LoadMods(typeof(Plugin).Assembly);
				log.LogInfo((object)("BetterPortuguese: registry de mods = " + modCatalog.Count + " regras aprovadas (BetterTooltips 0.1.6)."));
			}
			catch (Exception ex3)
			{
				log.LogWarning((object)("BetterPortuguese: camada de mods desativada, base independente: " + ex3.Message));
			}
			harmony = new Harmony("com.gumatos.betterportuguese");
			Install("consulta da lista", () => Bindings.ListTarget(), "ListPostfix");
			Install("fila/config/refresh", () => Bindings.Exact(typeof(GUIManager), "Update", typeof(void), isStatic: false, Type.EmptyTypes), "MainThreadPostfix");
			CompositionPatches.Install(harmony, () => States.Current, limited, delegate(string message)
			{
				log.LogInfo((object)message);
			});
			StatusPatches.Install(harmony, () => States.Current, limited, delegate(string message)
			{
				log.LogInfo((object)message);
			});
			EventEffectText.Install(harmony, () => States.Current != null && States.Current.Diagnostic, log);
			if (modCatalog != null)
			{
				BetterTooltipsAdapter.Install(modCatalog, () => States.Current, limited, delegate(string message)
				{
					log.LogInfo((object)message);
				});
			}
			log.LogInfo((object)"BetterPortuguese 0.2.7 carregado.");
		}

		private void Install(string label, Func<MethodInfo> target, string patch)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = target();
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin).GetMethod(patch, BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				int num = 0;
				foreach (Patch postfix in patchInfo.Postfixes)
				{
					if (postfix.owner == "com.gumatos.betterportuguese")
					{
						num++;
					}
				}
				if (num != 1)
				{
					throw new InvalidOperationException("Expected one owned postfix, got " + num);
				}
				log.LogInfo((object)("BetterPortuguese: patch " + label + " registrado (owner=com.gumatos.betterportuguese, postfixes proprios=" + num + ")."));
				foreach (Patch postfix2 in patchInfo.Postfixes)
				{
					if (postfix2.owner != "com.gumatos.betterportuguese")
					{
						limited.Write("Outro postfix no alvo " + methodInfo.Name + ": " + postfix2.owner + "; nao ha garantia contra mudancas posteriores.");
					}
				}
			}
			catch (Exception ex)
			{
				log.LogError((object)("BetterPortuguese: alvo " + label + " indisponivel: " + ex.Message));
				if (patch == "MainThreadPostfix")
				{
					States.Enqueue(new Settings(active: false, Conjunto.Corrigido, integrateMods: true, diagnostic: false, valid: false));
				}
			}
		}

		private void QueueEntries()
		{
			States.Enqueue(new Settings(active.Value, variant.Value, integrate.Value, diagnostic.Value));
		}

		private void PollFile()
		{
			try
			{
				string text = File.ReadAllText(((BaseUnityPlugin)this).Config.ConfigFilePath);
				if (!(text == lastFile))
				{
					lastFile = text;
					Settings settings = ConfigReader.Parse(text, new Settings());
					bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
					try
					{
						((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
						((BaseUnityPlugin)this).Config.Reload();
					}
					finally
					{
						((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
					}
					States.Enqueue(settings);
				}
			}
			catch (Exception ex)
			{
				States.Enqueue(new Settings(active: false, Conjunto.Corrigido, integrateMods: true, diagnostic: false, valid: false));
				limited.Write("Config invalida/ilegivel; overrides desativados: " + ex.GetType().Name + ": " + ex.Message);
				lastFile = null;
			}
		}

		private static void ListPostfix(string original, LanguageChoice languageChoice, bool fallbackToTranslatorKey, ref List<LocalizationEntry> __result)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			List<LocalizationEntry> list = __result;
			try
			{
				if (!firstLookup)
				{
					firstLookup = true;
					ManualLogSource obj = log;
					if (obj != null)
					{
						obj.LogInfo((object)"BetterPortuguese: gancho da lista vivo; selecao de genero/fallback permanece no jogo.");
					}
				}
				__result = overlay?.Resolve(original, (int)languageChoice == 10, (int)OptionsManager.CurrentLanguage == 10, States.Current, list) ?? list;
			}
			catch (Exception ex)
			{
				__result = list;
				limited?.Write("Postfix preservou retorno: " + ex.GetType().Name);
			}
		}

		private static void MainThreadPostfix()
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (Time.realtimeSinceStartup >= nextPoll)
				{
					nextPoll = Time.realtimeSinceStartup + 1f;
					poll?.Invoke();
				}
				Settings current = States.Current;
				if (States.ApplyPending())
				{
					refreshPending |= RefreshPlan.Needed(current, States.Current);
					Settings current2 = States.Current;
					ManualLogSource obj = log;
					if (obj != null)
					{
						obj.LogInfo((object)("BetterPortuguese: estado aplicado na thread principal: " + ((current2.Valid && current2.Active) ? current2.Variant.ToString() : "desativado") + ", IntegracaoMods=" + current2.IntegrateMods + " (" + BetterTooltipsAdapter.Count + " adaptador(es) registrado(s))."));
					}
				}
				if (!refreshPending)
				{
					return;
				}
				Scene activeScene = SceneManager.GetActiveScene();
				if (!((Scene)(ref activeScene)).IsValid() || (Object)(object)OptionsManager.instance == (Object)null)
				{
					return;
				}
				refreshPending = false;
				int num = UiRefresh.Apply(changedKeys, limited);
				if (States.Current.Diagnostic)
				{
					ManualLogSource obj2 = log;
					if (obj2 != null)
					{
						obj2.LogInfo((object)("BetterPortuguese: refresh dirigido de " + num + " texto(s) aprovado(s); sem LocalizeUI global; tooltips no proximo hover."));
					}
				}
			}
			catch (Exception ex)
			{
				limited?.Write("Refresh/config falhou; retorno do jogo preservado: " + ex.GetType().Name);
			}
		}
	}
}
namespace BetterPortuguese.Runtime
{
	internal static class BetterTooltipsAdapter
	{
		private sealed class Frame
		{
			public string Original;

			public string Localized;
		}

		public const string Owner = "com.gumatos.betterportuguese.mods.bettertooltips";

		private static ModCatalog map;

		private static Func<Settings> settings;

		private static OnceLog warnings;

		private static Action<string> info;

		private static ISet<string> notes;

		private static OnceLog diagLog;

		private static bool ready;

		private static bool sourceAlive;

		private static bool displayAlive;

		[ThreadStatic]
		private static int localizing;

		public static int Count
		{
			get
			{
				if (!ready)
				{
					return 0;
				}
				return 1;
			}
		}

		public static void Install(ModCatalog catalog, Func<Settings> current, OnceLog limited, Action<string> log)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			warnings = limited;
			info = log;
			settings = current;
			map = catalog;
			Harmony val = new Harmony("com.gumatos.betterportuguese.mods.bettertooltips");
			try
			{
				if (!Chainloader.PluginInfos.TryGetValue("com.gumatos.bettertooltips", out var value))
				{
					throw new InvalidOperationException("BetterTooltips ausente; sem adaptador");
				}
				if (value.Metadata.Version.ToString() != "0.1.6")
				{
					throw new InvalidOperationException("versao BT nao homologada: " + value.Metadata.Version);
				}
				string text = Resources.Sha256(File.ReadAllBytes(typeof(Tooltip).Assembly.Location));
				if (text != "f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182")
				{
					throw new InvalidOperationException("Assembly-CSharp divergente; adaptador recusado (medido " + text + ", esperado f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182)");
				}
				Type type = ((object)value.Instance).GetType().Assembly.GetType("BetterTooltips.Patches.LocalizePatch", throwOnError: true);
				MethodInfo methodInfo = Bindings.Exact(type, "AplicarNotasDoFunil", typeof(void), true, typeof(string), typeof(string).MakeByRefType());
				if (methodInfo.GetParameters()[0].Name != "original" || methodInfo.GetParameters()[1].Name != "__result")
				{
					throw new MissingMethodException("BT source arguments changed");
				}
				notes = (type.GetField("_conteudosDeNota", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) as ISet<string>) ?? throw new MissingFieldException("BT note registry changed");
				MethodInfo methodInfo2 = Bindings.Exact(typeof(Tooltip), "ShowTooltip", typeof(void), false, typeof(string), typeof(string), typeof(Sprite), typeof(string), typeof(TooltipOffsetInfo), typeof(Color), typeof(Vector3?), typeof(bool), typeof(bool), typeof(float), typeof(ControlGlyphInfo?), typeof(string), typeof(bool));
				if (methodInfo2.GetParameters()[3].Name != "description")
				{
					throw new MissingMethodException("Tooltip description argument changed");
				}
				Hook(val, methodInfo, "SourcePrefix", "SourcePostfix", "SourceFinalizer");
				Hook(val, methodInfo2, "DisplayPrefix", "DisplayPostfix", null);
				diagLog = new OnceLog(log, 200);
				ready = true;
				info?.Invoke("BP-MODS: 1 adaptador registrado, BetterTooltips 0.1.6; " + map.Count + " regras; origem BP -> montagem/ordem BT -> traducao final; nenhum patch novo em Update.");
			}
			catch (Exception ex)
			{
				ready = false;
				val.UnpatchSelf();
				warnings?.Write("BP-MODS desativado, base independente: " + ex.GetType().Name + ": " + ex.Message);
			}
		}

		private static void Hook(Harmony harmony, MethodInfo target, string pre, string post, string fin)
		{
			harmony.Patch((MethodBase)target, M(pre), M(post), (HarmonyMethod)null, M(fin), (HarmonyMethod)null);
			Patches patchInfo = Harmony.GetPatchInfo((MethodBase)target);
			if ((pre != null && patchInfo.Prefixes.Count((Patch x) => x.owner == "com.gumatos.betterportuguese.mods.bettertooltips") != 1) || (post != null && patchInfo.Postfixes.Count((Patch x) => x.owner == "com.gumatos.betterportuguese.mods.bettertooltips") != 1) || (fin != null && patchInfo.Finalizers.Count((Patch x) => x.owner == "com.gumatos.betterportuguese.mods.bettertooltips") != 1))
			{
				throw new InvalidOperationException("Adapter ownership mismatch: " + target.Name);
			}
			static HarmonyMethod M(string name)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Expected O, but got Unknown
				if (name != null)
				{
					HarmonyMethod val = new HarmonyMethod(typeof(BetterTooltipsAdapter).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic));
					val.priority = 0;
					val.after = new string[1] { "com.gumatos.bettertooltips" };
					return val;
				}
				return null;
			}
		}

		private static void Diag(string tag, string input, string output)
		{
			if (input != null && (input.IndexOf("shrine", StringComparison.OrdinalIgnoreCase) >= 0 || input.IndexOf("aura", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				Func<Settings> func = settings;
				if (func != null && func()?.Diagnostic == true)
				{
					diagLog?.Write("BP-DIAG " + tag + " changed=" + (input != output) + " in<" + Cut(input) + "> out<" + Cut(output) + ">");
				}
			}
		}

		private static string Cut(string text)
		{
			string text2 = text.Replace("\n", "\\n");
			if (text2.Length > 400)
			{
				return text2.Substring(0, 400) + "…";
			}
			return text2;
		}

		private static bool Enabled()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			if (ready && localizing == 0 && ModCatalog.Enabled(settings?.Invoke(), (int)OptionsManager.CurrentLanguage == 10))
			{
				return true;
			}
			if (localizing == 0)
			{
				warnings?.Write("BP-MODS preservou BT/vanilla: adaptador/config/idioma fora do escopo ativo Corrigido+IntegracaoMods+pt-BR.");
			}
			return false;
		}

		private static string LocalizeName(string text)
		{
			try
			{
				localizing++;
				string text2 = OptionsManager.Localize(text, (LanguageGender)0, (Gender)2);
				return (text2 != null && text2.IndexOf('\n') < 0 && text2.IndexOf('<') < 0) ? text2 : text;
			}
			finally
			{
				localizing--;
			}
		}

		private static void SourcePrefix(string original, ref string __1, out Frame __state)
		{
			__state = null;
			try
			{
				if (Enabled() && original != null && __1 != null)
				{
					__state = new Frame
					{
						Original = original,
						Localized = __1
					};
					__1 = original;
				}
			}
			catch (Exception ex)
			{
				warnings?.Write("BP-MODS origem preservada: " + ex.GetType().Name);
			}
		}

		private static void SourcePostfix(ref string __1, Frame __state)
		{
			if (__state == null)
			{
				return;
			}
			try
			{
				__1 = ModText.Rebase(map, __state.Original, __state.Localized, __1, LocalizeName);
				if (!sourceAlive)
				{
					sourceAlive = true;
					info?.Invoke("BP-MODS: origem localizada preservada; montagem BT viva.");
				}
			}
			catch (Exception ex)
			{
				__1 = __state.Localized;
				warnings?.Write("BP-MODS composicao recusada, origem preservada: " + ex.GetType().Name);
			}
		}

		private static Exception SourceFinalizer(Exception __exception, ref string __1, Frame __state)
		{
			if (__exception != null && __state != null)
			{
				__1 = __state.Localized;
			}
			return __exception;
		}

		private static void DisplayPostfix(Tooltip __instance)
		{
			string text = null;
			try
			{
				if (Enabled() && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.Description == (Object)null))
				{
					text = ((TMP_Text)__instance.Description).text;
					string text2 = ModText.Translate(map, text, notes, LocalizeName, delegate(string s)
					{
						warnings?.Write("BP-MODS: " + s);
					});
					Diag("postfix", text, text2);
					if (text2 != text)
					{
						((TMP_Text)__instance.Description).text = text2;
					}
				}
			}
			catch (Exception ex)
			{
				warnings?.Write("BP-MODS texto renderizado preservado: " + ex.GetType().Name);
			}
		}

		private static void DisplayPrefix(ref string description)
		{
			string text = description;
			try
			{
				if (Enabled())
				{
					description = ModText.Translate(map, text, notes, LocalizeName, delegate(string s)
					{
						warnings?.Write("BP-MODS: " + s);
					});
					Diag("prefix", text, description);
					if (!displayAlive && description != text)
					{
						displayAlive = true;
						info?.Invoke("BP-MODS: traducao final viva depois da ordem BT.");
					}
				}
			}
			catch (Exception ex)
			{
				description = text;
				warnings?.Write("BP-MODS saida preservada: " + ex.GetType().Name);
			}
		}
	}
	internal static class Bindings
	{
		public static MethodInfo Exact(Type type, string name, Type result, bool isStatic, params Type[] parameters)
		{
			BindingFlags bindingAttr = (BindingFlags)(0x30 | (isStatic ? 8 : 4) | 2);
			MethodInfo method = type.GetMethod(name, bindingAttr, null, parameters, null);
			if (method == null || method.IsStatic != isStatic || method.ReturnType != result || method.ContainsGenericParameters)
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return method;
		}

		public static MethodInfo ListTarget()
		{
			MethodInfo methodInfo = Exact(typeof(OptionsManager), "GetLocalizationEntryList", typeof(List<LocalizationEntry>), true, typeof(string), typeof(LanguageChoice), typeof(bool));
			ParameterInfo[] parameters = methodInfo.GetParameters();
			string[] array = new string[3] { "original", "languageChoice", "fallbackToTranslatorKey" };
			for (int i = 0; i < array.Length; i++)
			{
				if (parameters[i].Name != array[i])
				{
					throw new MissingMethodException("Localization parameter names changed");
				}
			}
			return methodInfo;
		}

		public static bool Equal(LocalizationEntry game, Entry baseline)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Invalid comparison between Unknown and I4
			if (game != null && game.Value == baseline.Value && game.Key == baseline.Key && game.TranslatorKey == baseline.TranslatorKey && game.Feminine == baseline.Feminine && game.Masculine == baseline.Masculine && game.Neutral == baseline.Neutral && (int)game.LanguageGender == baseline.LanguageGender && game.CanBeGendered == baseline.CanBeGendered)
			{
				return game.NeedsGenderInfo == baseline.NeedsGenderInfo;
			}
			return false;
		}

		public static LocalizationEntry Clone(Entry entry)
		{
			//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)
			//IL_0011: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			return new LocalizationEntry
			{
				Value = entry.Value,
				Key = entry.Key,
				TranslatorKey = entry.TranslatorKey,
				Feminine = entry.Feminine,
				Masculine = entry.Masculine,
				Neutral = entry.Neutral,
				LanguageGender = (LanguageGender)entry.LanguageGender,
				CanBeGendered = entry.CanBeGendered,
				NeedsGenderInfo = entry.NeedsGenderInfo
			};
		}
	}
	internal static class CompositionPatches
	{
		private sealed class ScopeFrame
		{
			public int Previous;
		}

		private struct FortuneContext
		{
			public Tooltip Target;

			public ItemQuality Quality;
		}

		[ThreadStatic]
		private static int itemDepth;

		[ThreadStatic]
		private static FortuneContext fortuneContext;

		private static bool itemReady;

		private static bool fortuneReady;

		private static bool damageReady;

		private static bool physicalDescriptionReady;

		private static bool itemNameReady;

		private static bool itemAlive;

		private static bool damageAlive;

		private static Func<Settings> settings;

		private static OnceLog warnings;

		private static Action<string> info;

		private static readonly HashSet<string> applied = new HashSet<string>(StringComparer.Ordinal);

		public static void Install(Harmony harmony, Func<Settings> current, OnceLog limited, Action<string> log)
		{
			settings = current;
			warnings = limited;
			info = log;
			try
			{
				string text = Resources.Sha256(File.ReadAllBytes(typeof(Tooltip).Assembly.Location));
				if (text != "f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182")
				{
					throw new InvalidOperationException("Assembly-CSharp SHA-256 divergente: medido " + text + ", esperado f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182 (build homologada; re-inspecionar antes de re-pinar)");
				}
			}
			catch (Exception ex)
			{
				warnings?.Write("BP-COMP recusado: " + ex.Message);
				return;
			}
			bool flag = false;
			try
			{
				MethodInfo methodInfo = Bindings.Exact(typeof(Tooltip), "ShowTooltip", typeof(void), false, typeof(string), typeof(string), typeof(Sprite), typeof(string), typeof(TooltipOffsetInfo), typeof(Color), typeof(Vector3?), typeof(bool), typeof(bool), typeof(float), typeof(ControlGlyphInfo?), typeof(string), typeof(bool));
				RequireArgument(methodInfo, "subtitle", typeof(string));
				RequireArgument(methodInfo, "isItem", typeof(bool));
				Patch(harmony, methodInfo, "SubtitlePrefix", null, null);
				flag = true;
			}
			catch (Exception ex2)
			{
				warnings?.Write("BP-COMP subtitulo recusado: " + ex2.Message);
			}
			if (flag)
			{
				try
				{
					MethodInfo[] array = new MethodInfo[3]
					{
						Bindings.Exact(typeof(Tooltip), "ShowItemTooltip", typeof(void), false, typeof(Item), typeof(Transform), typeof(TooltipOffsetInfo), typeof(Character), typeof(bool), typeof(bool), typeof(ControlGlyphInfo?), typeof(string), typeof(Item)),
						Bindings.Exact(typeof(Tooltip), "ShowItemTooltip", typeof(void), false, typeof(ItemInfo), typeof(TooltipOffsetInfo)),
						Bindings.Exact(typeof(Tooltip), "ShowTransmogTooltip", typeof(void), false, typeof(ItemInfo), typeof(TooltipOffsetInfo), typeof(ControlGlyphInfo?), typeof(string))
					};
					foreach (MethodInfo target in array)
					{
						Patch(harmony, target, "EnterItem", null, "LeaveItem");
					}
					itemReady = true;
					info?.Invoke("BP-COMP: composicao de raridade registrada (3 origens + ShowTooltip; inclui comparacao; sem transpiler).");
				}
				catch (Exception ex3)
				{
					itemReady = false;
					warnings?.Write("BP-COMP raridade recusada: " + ex3.Message);
				}
				try
				{
					MethodInfo methodInfo2 = Bindings.Exact(typeof(Tooltip), "ShowActionStatusTooltip", typeof(void), false, typeof(ActionStatusInfo), typeof(Character), typeof(Character), typeof(Item), typeof(PersistentDurationType), typeof(string), typeof(float), typeof(bool), typeof(string), typeof(ActionStatus), typeof(string));
					RequireArgument(methodInfo2, "actionStatusInfo", typeof(ActionStatusInfo));
					Patch(harmony, methodInfo2, "EnterFortune", null, "LeaveFortune");
					fortuneReady = true;
					info?.Invoke("BP-COMP: subtitulo de Fortuna registrado (origem nativa; sem transpiler).");
				}
				catch (Exception ex4)
				{
					fortuneReady = false;
					warnings?.Write("BP-COMP Fortuna recusada: " + ex4.Message);
				}
			}
			try
			{
				MethodInfo methodInfo3 = Bindings.Exact(typeof(Tooltip), "GetDamageTypeLabel", typeof(string), true, typeof(DamageType));
				RequireArgument(methodInfo3, "damageType", typeof(DamageType));
				Patch(harmony, methodInfo3, null, "DamagePostfix", null);
				damageReady = true;
				info?.Invoke("BP-COMP: rotulo Healing registrado em Tooltip.GetDamageTypeLabel.");
			}
			catch (Exception ex5)
			{
				damageReady = false;
				warnings?.Write("BP-COMP Healing recusado: " + ex5.Message);
			}
			try
			{
				MethodInfo methodInfo4 = Bindings.Exact(typeof(Tooltip), "AppendItemMods", typeof(string), false, typeof(Item), typeof(Item));
				RequireArgument(methodInfo4, "item", typeof(Item));
				Patch(harmony, methodInfo4, null, "PhysicalItemDescriptionPostfix", null);
				physicalDescriptionReady = true;
			}
			catch (Exception ex6)
			{
				physicalDescriptionReady = false;
				warnings?.Write("BP-COMP rotulo de item recusado: " + ex6.Message);
			}
			try
			{
				MethodInfo target2 = Bindings.Exact(typeof(Item), "get_ItemName", typeof(string), false);
				Patch(harmony, target2, null, "ItemNamePostfix", null);
				itemNameReady = true;
			}
			catch (Exception ex7)
			{
				itemNameReady = false;
				warnings?.Write("BP-COMP nome de item recusado: " + ex7.Message);
			}
		}

		private static void RequireArgument(MethodInfo method, string name, Type type)
		{
			if (method == null || method.GetParameters().Count((ParameterInfo p) => p.Name == name && p.ParameterType == type) != 1)
			{
				throw new MissingMethodException("BP-COMP argumento ausente ou alterado: " + name);
			}
		}

		private static void Patch(Harmony harmony, MethodInfo target, string prefix, string postfix, string finalizer)
		{
			harmony.Patch((MethodBase)target, Hook(prefix), Hook(postfix), (HarmonyMethod)null, Hook(finalizer), (HarmonyMethod)null);
			Patches patchInfo = Harmony.GetPatchInfo((MethodBase)target);
			if ((prefix != null && patchInfo.Prefixes.Count((Patch p) => p.owner == "com.gumatos.betterportuguese") != 1) || (postfix != null && patchInfo.Postfixes.Count((Patch p) => p.owner == "com.gumatos.betterportuguese") != 1) || (finalizer != null && patchInfo.Finalizers.Count((Patch p) => p.owner == "com.gumatos.betterportuguese") != 1))
			{
				throw new InvalidOperationException("ownership inesperado: " + target.Name);
			}
			foreach (string item in patchInfo.Owners.Where((string o) => o != "com.gumatos.betterportuguese"))
			{
				warnings?.Write("BP-COMP outro owner em " + target.Name + ": " + item + "; saida exata sera conferida.");
			}
			static HarmonyMethod Hook(string name)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				if (name != null)
				{
					return new HarmonyMethod(typeof(CompositionPatches).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic))
					{
						priority = 0
					};
				}
				return null;
			}
		}

		private static bool Enabled()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			if (Composition.Enabled(settings?.Invoke(), (int)OptionsManager.CurrentLanguage == 10, out var reason))
			{
				return true;
			}
			warnings?.Write("BP-COMP preservou vanilla: " + reason);
			return false;
		}

		private static void EnterItem(out ScopeFrame __state)
		{
			__state = null;
			if (itemReady)
			{
				__state = new ScopeFrame
				{
					Previous = itemDepth
				};
				itemDepth++;
			}
		}

		private static Exception LeaveItem(Exception __exception, ScopeFrame __state)
		{
			if (__state != null)
			{
				itemDepth = __state.Previous;
			}
			return __exception;
		}

		private static void EnterFortune(Tooltip __instance, ActionStatusInfo actionStatusInfo, out FortuneContext? __state)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!fortuneReady)
			{
				return;
			}
			try
			{
				bool flag = (Object)(object)actionStatusInfo != (Object)null && (int)actionStatusInfo.StatusType == 1;
				if (flag || fortuneContext.Target != null)
				{
					__state = fortuneContext;
					fortuneContext = (flag ? new FortuneContext
					{
						Target = __instance,
						Quality = actionStatusInfo.Rarity
					} : default(FortuneContext));
				}
			}
			catch (Exception ex)
			{
				__state = fortuneContext;
				fortuneContext = default(FortuneContext);
				warnings?.Write("BP-COMP Fortuna preservada por excecao de contexto: " + ex.GetType().Name);
			}
		}

		private static Exception LeaveFortune(Exception __exception, FortuneContext? __state)
		{
			if (__state.HasValue)
			{
				fortuneContext = __state.Value;
			}
			return __exception;
		}

		private static void SubtitlePrefix(object __instance, ref string subtitle, bool isItem)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected I4, but got Unknown
			string text = subtitle;
			try
			{
				FortuneContext fortuneContext = CompositionPatches.fortuneContext;
				if (fortuneReady && !isItem && fortuneContext.Target == __instance)
				{
					if (Enabled())
					{
						subtitle = Composition.FortuneSubtitle((int)fortuneContext.Quality, text, out var reason);
						if (reason != null)
						{
							warnings?.Write("BP-COMP Fortuna preservada: " + reason);
						}
						if (text != subtitle)
						{
							infoOnce("subtitulo de Fortuna corrigido");
						}
					}
				}
				else if (itemReady && itemDepth != 0 && Enabled())
				{
					if (!itemAlive)
					{
						itemAlive = true;
						info?.Invoke("BP-COMP: gancho de subtitulo vivo em contexto nativo de item.");
					}
					string reason2;
					string text2 = Composition.ItemSubtitle(text, out reason2);
					if (reason2 != null)
					{
						warnings?.Write("BP-COMP subtitulo preservado: " + reason2);
					}
					subtitle = text2;
					if (text != text2)
					{
						infoOnce("raridade corrigida");
					}
				}
			}
			catch (Exception ex)
			{
				subtitle = text;
				warnings?.Write("BP-COMP subtitulo preservado por excecao: " + ex.GetType().Name);
			}
		}

		private static void DamagePostfix(DamageType damageType, ref string __result)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			string text = __result;
			try
			{
				if (damageReady && Enabled())
				{
					if (!damageAlive)
					{
						damageAlive = true;
						info?.Invoke("BP-COMP: gancho de tipo de dano vivo.");
					}
					string reason;
					string text2 = Composition.DamageLabel((int)damageType == 6, text, out reason);
					if (reason != null)
					{
						warnings?.Write("BP-COMP rotulo preservado: " + reason);
					}
					__result = text2;
					if (text != text2)
					{
						infoOnce("Healing corrigido para Cura por Dano");
					}
				}
			}
			catch (Exception ex)
			{
				__result = text;
				warnings?.Write("BP-COMP rotulo preservado por excecao: " + ex.GetType().Name);
			}
		}

		private static void ItemNamePostfix(Item __instance, bool __runOriginal, ref string __result)
		{
			if (!itemNameReady || !__runOriginal || !string.Equals(__result, "Túnica da Máscara de Sangue Reforçado", StringComparison.Ordinal))
			{
				return;
			}
			try
			{
				if (!Enabled() || __instance == null)
				{
					return;
				}
				ItemInfo itemInfo = __instance.ItemInfo;
				if (!((Object)(object)itemInfo == (Object)null) && !(itemInfo.ItemName != "Blood Mask Tunic"))
				{
					ItemMod prefixMod = __instance.PrefixMod;
					if (!((Object)(object)prefixMod == (Object)null) && (!(((Object)prefixMod).name != "Reinforced") || !(((Object)prefixMod).name != "Bolstered")))
					{
						__result = "Túnica da Máscara de Sangue Reforçada";
					}
				}
			}
			catch (Exception ex)
			{
				warnings?.Write("BP-COMP nome de item preservado por excecao: " + ex.GetType().Name);
			}
		}

		private static void PhysicalItemDescriptionPostfix(Item item, bool __runOriginal, ref string __result)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			string text = __result;
			try
			{
				if (!physicalDescriptionReady || !__runOriginal)
				{
					return;
				}
				Weapon val = (Weapon)(object)((item is Weapon) ? item : null);
				if (val == null || (int)val.DamageType != 1 || text == null || text.Length < 15 + "Dano Físico</color>\n".Length || !text.StartsWith("<color=#", StringComparison.Ordinal) || text[14] != '>' || string.CompareOrdinal(text, 15, "Dano Físico</color>\n", 0, "Dano Físico</color>\n".Length) != 0)
				{
					return;
				}
				for (int i = "<color=#".Length; i < 14; i++)
				{
					char c = text[i];
					if ((c < '0' || c > '9') && (c < 'A' || c > 'F') && (c < 'a' || c > 'f'))
					{
						return;
					}
				}
				if (Enabled())
				{
					__result = text.Substring(0, 15) + "Dano físico" + text.Substring(15 + "Dano Físico".Length);
					infoOnce("rotulo de arma fisica corrigido em Tooltip.AppendItemMods");
				}
			}
			catch (Exception ex)
			{
				__result = text;
				warnings?.Write("BP-COMP rotulo de item preservado por excecao: " + ex.GetType().Name);
			}
		}

		private static void infoOnce(string text)
		{
			if (applied.Add(text))
			{
				info?.Invoke("BP-COMP: " + text + ".");
			}
		}
	}
	internal static class ConfigReader
	{
		public static Settings Parse(string text, Settings defaults)
		{
			Dictionary<string, string> values = new Dictionary<string, string>(StringComparer.Ordinal);
			string text2 = "";
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text3 = array[i].Trim();
				if (text3.Length == 0 || text3.StartsWith("#") || text3.StartsWith(";"))
				{
					continue;
				}
				if (text3.StartsWith("[") && text3.EndsWith("]"))
				{
					text2 = text3.Substring(1, text3.Length - 2);
				}
				else if (!(text2 != "Geral"))
				{
					int num = text3.IndexOf('=');
					if (num < 0)
					{
						throw new FormatException("Malformed BetterPortuguese config line");
					}
					string text4 = text3.Substring(0, num).Trim();
					if (text4 != "Ativo" && text4 != "Conjunto" && text4 != "IntegracaoMods" && text4 != "Diagnostico")
					{
						throw new FormatException("Unknown BetterPortuguese setting");
					}
					if (values.ContainsKey(text4))
					{
						throw new FormatException("Duplicate BetterPortuguese setting");
					}
					values.Add(text4, text3.Substring(num + 1).Trim());
				}
			}
			Conjunto variant = defaults.Variant;
			if (values.TryGetValue("Conjunto", out var value))
			{
				if (value != "Original" && value != "Corrigido")
				{
					throw new FormatException("Conjunto must be Original or Corrigido");
				}
				variant = ((!(value == "Original")) ? Conjunto.Corrigido : Conjunto.Original);
			}
			return new Settings(Boolean("Ativo", defaults.Active), variant, Boolean("IntegracaoMods", defaults.IntegrateMods), Boolean("Diagnostico", defaults.Diagnostic));
			bool Boolean(string key, bool fallback)
			{
				if (!values.TryGetValue(key, out var value2))
				{
					return fallback;
				}
				if (!bool.TryParse(value2, out var result))
				{
					throw new FormatException("Invalid " + key);
				}
				return result;
			}
		}
	}
	internal static class EventEffectText
	{
		private static readonly Dictionary<string, string> Fixes = new Dictionary<string, string>(StringComparer.Ordinal)
		{
			["Reroll a skill"] = "Rerolar uma habilidade",
			["Level up Fortunes"] = "Aumente o nível das suas Fortunas"
		};

		private static readonly Dictionary<string, string> Baloes = new Dictionary<string, string>(StringComparer.Ordinal)
		{
			["Battle"] = "Batalhar",
			["Hard Battle"] = "Batalha Difícil",
			["Rest"] = "Descanso"
		};

		private static ManualLogSource _log;

		private static bool _diag;

		private static readonly HashSet<string> _seen = new HashSet<string>(StringComparer.Ordinal);

		public static void Install(Harmony harmony, Func<bool> diagnostico, ManualLogSource log)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			_log = log;
			try
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(EventOptionSelectionItem), "PopulateResultEffects", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(EventEffectText), "AfterPopulate", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(EventResultEffect), "SetEventAction", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(EventEffectText), "AfterSetAction", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(NavNodeVotingButton), "set_NodeType", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(EventEffectText), "AfterNodeType", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_diag = diagnostico?.Invoke() ?? false;
				if (log != null)
				{
					log.LogInfo((object)("BetterPortuguese: traducao das linhas de efeito de evento registrada (" + Fixes.Count + " regras)."));
				}
			}
			catch (Exception ex)
			{
				if (log != null)
				{
					log.LogWarning((object)("BetterPortuguese: linhas de efeito de evento NAO traduzidas: " + ex.GetType().Name + ": " + ex.Message));
				}
			}
		}

		private static void AfterPopulate(EventOptionSelectionItem __instance)
		{
			try
			{
				Apply(__instance.SingleActionEffectText);
				Apply(__instance.SuccessEffectText);
				Apply(__instance.FailureEffectText);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("BetterPortuguese: efeito de evento preservado: " + ex.GetType().Name));
				}
			}
		}

		private static void AfterSetAction(EventResultEffect __instance)
		{
			try
			{
				Apply(__instance);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("BetterPortuguese: efeito de evento preservado: " + ex.GetType().Name));
				}
			}
		}

		private static void AfterNodeType(NavNodeVotingButton __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.NodeTypeText == (Object)null)
				{
					return;
				}
				string text = ((TMP_Text)__instance.NodeTypeText).text;
				if (string.IsNullOrEmpty(text))
				{
					return;
				}
				if (Baloes.TryGetValue(text, out var value))
				{
					((TMP_Text)__instance.NodeTypeText).text = value;
				}
				else if (_diag && _seen.Add("nav:" + text))
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogInfo((object)("BP-TEXTO: rotulo de no sem traducao: '" + text + "'"));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)("BetterPortuguese: rotulo de no preservado: " + ex.GetType().Name));
				}
			}
		}

		private static void Apply(EventResultEffect effect)
		{
			TMP_Text val = (TMP_Text)(object)(((Object)(object)effect != (Object)null) ? effect.EffectText : null);
			if ((Object)(object)val == (Object)null || string.IsNullOrEmpty(val.text))
			{
				return;
			}
			string text = val.text;
			if (Fixes.TryGetValue(text, out var value))
			{
				val.text = value;
			}
			else if (_diag && _seen.Add(text))
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)("BP-EVENTO: linha sem traducao: '" + text + "'"));
				}
			}
		}
	}
	internal static class StatusPatches
	{
		private static bool ready;

		private static bool failed;

		private static bool aliveReported;

		private static int corrected;

		private static Func<Settings> settings;

		private static OnceLog warnings;

		private static Action<string> info;

		public static void Install(Harmony harmony, Func<Settings> current, OnceLog limited, Action<string> log)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			settings = current;
			warnings = limited;
			info = log;
			try
			{
				string text = Resources.Sha256(File.ReadAllBytes(typeof(Tooltip).Assembly.Location));
				if (text != "f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182")
				{
					throw new InvalidOperationException("Assembly-CSharp SHA-256 divergente: medido " + text + ", esperado f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182 (build homologada; re-inspecionar antes de re-pinar)");
				}
			}
			catch (Exception ex)
			{
				warnings?.Write("BP-COMP-STATUS recusado: " + ex.Message);
				return;
			}
			try
			{
				MethodInfo methodInfo = Bindings.Exact(typeof(GameLogic), "OverheadMessage", typeof(void), false, typeof(PlayerMovement), typeof(string), typeof(float), typeof(string));
				RequireArgument(methodInfo, "message", typeof(string));
				HarmonyMethod val = new HarmonyMethod(typeof(StatusPatches).GetMethod("OverheadPrefix", BindingFlags.Static | BindingFlags.NonPublic))
				{
					priority = 0
				};
				harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				if (patchInfo == null || patchInfo.Prefixes.Count((Patch p) => p.owner == "com.gumatos.betterportuguese") != 1)
				{
					throw new InvalidOperationException("ownership inesperado: GameLogic.OverheadMessage");
				}
				foreach (string item in patchInfo.Owners.Where((string o) => o != "com.gumatos.betterportuguese"))
				{
					warnings?.Write("BP-COMP-STATUS outro owner em OverheadMessage: " + item + "; cosmetica apenas.");
				}
				ready = true;
				failed = false;
				info?.Invoke("BP-COMP-STATUS: concordancia de texto flutuante registrada em GameLogic.OverheadMessage (prefixo no parametro 'message'; " + StatusAgreement.Feminine.Count + " nomes femininos).");
			}
			catch (Exception ex2)
			{
				ready = false;
				warnings?.Write("BP-COMP-STATUS recusado: " + ex2.Message);
			}
		}

		private static void RequireArgument(MethodInfo method, string name, Type type)
		{
			if (method == null || method.GetParameters().Count((ParameterInfo p) => p.Name == name && p.ParameterType == type) != 1)
			{
				throw new MissingMethodException("BP-COMP-STATUS argumento ausente ou alterado: " + name);
			}
		}

		private static void OverheadPrefix(ref string message)
		{
			string text = message;
			try
			{
				if (!ready || failed || text == null || text.IndexOf("Aplicado", StringComparison.Ordinal) < 0 || !Enabled())
				{
					return;
				}
				if (!aliveReported)
				{
					aliveReported = true;
					info?.Invoke("BP-COMP-STATUS: gancho de texto flutuante vivo.");
				}
				string reason;
				string text2 = StatusAgreement.Compose(text, out reason);
				if (reason != null && reason.StartsWith("feminino:", StringComparison.Ordinal))
				{
					corrected++;
					if (corrected <= 3 || corrected % 50 == 0)
					{
						info?.Invoke("BP-COMP-STATUS: " + reason + " -> total " + corrected);
					}
				}
				message = text2;
			}
			catch (Exception ex)
			{
				message = text;
				failed = true;
				warnings?.Write("BP-COMP-STATUS desativado por excecao: " + ex.GetType().Name + ": " + ex.Message);
			}
		}

		private static bool Enabled()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			if (Composition.Enabled(settings?.Invoke(), (int)OptionsManager.CurrentLanguage == 10, out var reason))
			{
				return true;
			}
			warnings?.Write("BP-COMP-STATUS preservou vanilla: " + reason);
			return false;
		}
	}
	internal static class UiRefresh
	{
		private static FieldInfo originals;

		public static int Apply(ISet<string> changed, OnceLog log)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)OptionsManager.CurrentLanguage != 10 || changed.Count == 0)
			{
				return 0;
			}
			if (originals == null)
			{
				originals = typeof(OptionsManager).GetField("OriginalTextValues", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
				if (originals == null || originals.FieldType != typeof(Dictionary<TextOrTMPText, string>))
				{
					originals = null;
					throw new MissingFieldException("OptionsManager.OriginalTextValues dictionary unavailable; reopen UI to refresh.");
				}
			}
			Dictionary<TextOrTMPText, string> dictionary = (Dictionary<TextOrTMPText, string>)originals.GetValue(null);
			if (dictionary == null)
			{
				return 0;
			}
			int num = 0;
			KeyValuePair<TextOrTMPText, string>[] array = RefreshPlan.Select(dictionary, changed);
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<TextOrTMPText, string> keyValuePair = array[i];
				try
				{
					if (keyValuePair.Key != null && !((Object)(object)keyValuePair.Key.GameObject == (Object)null))
					{
						OptionsManager.LocalizeUIText(keyValuePair.Key);
						num++;
					}
				}
				catch (Exception ex)
				{
					log?.Write("Refresh de texto aprovado preservou demais alvos: " + ex.GetType().Name);
				}
			}
			return num;
		}
	}
}
namespace BetterPortuguese.Core
{
	internal sealed class Entry
	{
		internal static readonly string[] Fields = new string[9] { "Value", "Key", "TranslatorKey", "Feminine", "Masculine", "Neutral", "LanguageGender", "CanBeGendered", "NeedsGenderInfo" };

		private readonly IReadOnlyDictionary<string, object> values;

		public string Value => (string)values["Value"];

		public string Key => (string)values["Key"];

		public string TranslatorKey => (string)values["TranslatorKey"];

		public string Feminine => (string)values["Feminine"];

		public string Masculine => (string)values["Masculine"];

		public string Neutral => (string)values["Neutral"];

		public int LanguageGender => JsonShape.Int(values["LanguageGender"]);

		public bool CanBeGendered => (bool)values["CanBeGendered"];

		public bool NeedsGenderInfo => (bool)values["NeedsGenderInfo"];

		public object this[string field] => values[field];

		public Entry(Dictionary<string, object> obj)
		{
			JsonShape.Fields(obj, Fields);
			foreach (string item in Fields.Take(6))
			{
				JsonShape.Text(obj[item], nullable: true);
			}
			int num = JsonShape.Int(obj["LanguageGender"]);
			if (num < 0 || num > 6)
			{
				throw new FormatException("Unknown LanguageGender");
			}
			JsonShape.Bool(obj["CanBeGendered"]);
			JsonShape.Bool(obj["NeedsGenderInfo"]);
			values = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>(obj, StringComparer.Ordinal));
		}

		public bool Same(Entry other)
		{
			if (other != null)
			{
				return Fields.All((string f) => object.Equals(this[f], other[f]));
			}
			return false;
		}

		public static bool SameLists(IReadOnlyList<Entry> a, IReadOnlyList<Entry> b)
		{
			if (a == null || b == null)
			{
				if (a == null)
				{
					return b == null;
				}
				return false;
			}
			if (a.Count != b.Count)
			{
				return false;
			}
			for (int i = 0; i < a.Count; i++)
			{
				if (!a[i].Same(b[i]))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal sealed class Record
	{
		public string Id { get; }

		public string Key { get; }

		public bool PresentInSource { get; }

		public IReadOnlyList<Entry> Entries { get; }

		public Record(Dictionary<string, object> obj)
		{
			JsonShape.Fields(obj, "id", "key", "presentInSource", "entries");
			Id = JsonShape.Text(obj["id"]);
			Key = JsonShape.Text(obj["key"]);
			if (!Regex.IsMatch(Id, "^LANG-[0-9]{5}$"))
			{
				throw new FormatException("Invalid editorial ID");
			}
			PresentInSource = JsonShape.Bool(obj["presentInSource"]);
			Entries = ((obj["entries"] == null) ? null : new ReadOnlyCollection<Entry>((from e in JsonShape.Array(obj["entries"])
				select new Entry(JsonShape.Object(e))).ToList()));
		}
	}
	internal sealed class Snapshot
	{
		private readonly object source;

		private readonly List<object> manual;

		public string Variant { get; }

		public IReadOnlyDictionary<string, Record> Records { get; }

		public int ManualCount => manual.Count;

		private Snapshot(Dictionary<string, object> obj, string expectedVariant)
		{
			JsonShape.Fields(obj, "schemaVersion", "locale", "variant", "source", "records", "manualRecords");
			if (JsonShape.Int(obj["schemaVersion"]) != 1 || JsonShape.Text(obj["locale"]) != "pt-BR" || JsonShape.Text(obj["variant"]) != expectedVariant)
			{
				throw new FormatException("Unsupported snapshot");
			}
			Variant = expectedVariant;
			Dictionary<string, object> dictionary = JsonShape.Object(obj["source"]);
			JsonShape.Fields(dictionary, "taskId", "artifactSha256", "resourcePath", "resourcePathId", "resourceAssetSha256", "assemblySha256", "canonicalMemberSha256");
			string[] array = new string[4] { "artifactSha256", "resourceAssetSha256", "assemblySha256", "canonicalMemberSha256" };
			foreach (string key in array)
			{
				if (!Regex.IsMatch(JsonShape.Text(dictionary[key]), "^[a-f0-9]{64}$"))
				{
					throw new FormatException("Invalid source hash");
				}
			}
			JsonShape.Text(dictionary["taskId"]);
			JsonShape.Text(dictionary["resourcePath"]);
			JsonShape.Int(dictionary["resourcePathId"]);
			source = dictionary;
			Dictionary<string, Record> dictionary2 = new Dictionary<string, Record>(StringComparer.Ordinal);
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			string text = null;
			foreach (object item in JsonShape.Array(obj["records"]))
			{
				Record record = new Record(JsonShape.Object(item));
				if (!hashSet.Add(record.Id) || dictionary2.ContainsKey(record.Key))
				{
					throw new FormatException("Duplicate ID/key");
				}
				if (text != null && string.CompareOrdinal(text, record.Id) >= 0)
				{
					throw new FormatException("Records not ordered by ID");
				}
				text = record.Id;
				if (expectedVariant == "Original" && record.PresentInSource != (record.Entries != null))
				{
					throw new FormatException("Presence/entries mismatch");
				}
				dictionary2.Add(record.Key, record);
			}
			Records = new ReadOnlyDictionary<string, Record>(dictionary2);
			manual = JsonShape.Array(obj["manualRecords"]);
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			foreach (object item2 in manual)
			{
				Dictionary<string, object> dictionary3 = JsonShape.Object(item2);
				JsonShape.Fields(dictionary3, "id", "sourceFile", "sourcePathId", "englishText", "originalEntries", "ptBRText");
				if (!hashSet2.Add(JsonShape.Text(dictionary3["id"])))
				{
					throw new FormatException("Duplicate manual ID");
				}
				JsonShape.Text(dictionary3["sourceFile"]);
				JsonShape.Int(dictionary3["sourcePathId"]);
				JsonShape.Text(dictionary3["englishText"]);
				JsonShape.Text(dictionary3["ptBRText"], nullable: true);
				foreach (object item3 in JsonShape.Array(dictionary3["originalEntries"]))
				{
					Dictionary<string, object> dictionary4 = JsonShape.Object(item3);
					JsonShape.Fields(dictionary4, "Language", "Text");
					JsonShape.Int(dictionary4["Language"]);
					JsonShape.Text(dictionary4["Text"], nullable: true);
				}
			}
		}

		public static Snapshot Parse(string json, string variant)
		{
			return new Snapshot(JsonShape.Object(StrictJson.Parse(json)), variant);
		}

		public void ValidateIdentity(Snapshot corrected)
		{
			if (Records.Count != corrected.Records.Count || !JsonShape.Equal(source, corrected.source) || !JsonShape.Equal(manual, corrected.manual))
			{
				throw new FormatException("Snapshot identity/manual drift (manual adapter unsupported)");
			}
			foreach (KeyValuePair<string, Record> record in Records)
			{
				if (!corrected.Records.TryGetValue(record.Key, out var value) || record.Value.Id != value.Id || record.Value.PresentInSource != value.PresentInSource)
				{
					throw new FormatException("Immutable ID/key/presence changed");
				}
			}
		}
	}
	internal sealed class Catalog
	{
		public Snapshot Original { get; }

		public Snapshot Corrected { get; }

		public IReadOnlyDictionary<string, Record> Changed { get; }

		private Catalog(Snapshot original, Snapshot corrected, List<object> diff)
		{
			Original = original;
			Corrected = corrected;
			original.ValidateIdentity(corrected);
			Dictionary<string, Dictionary<string, object>> dictionary = new Dictionary<string, Dictionary<string, object>>(StringComparer.Ordinal);
			Dictionary<string, EntryAddition> dictionary2 = new Dictionary<string, EntryAddition>(StringComparer.Ordinal);
			foreach (object item in diff)
			{
				Dictionary<string, object> dictionary3 = JsonShape.Object(item);
				if (dictionary3.ContainsKey("operation"))
				{
					EntryAddition value = EntryAddition.Parse(dictionary3, original);
					string key = JsonShape.Text(dictionary3["key"]);
					if (dictionary2.ContainsKey(key))
					{
						throw new FormatException("Duplicate addEntry target");
					}
					dictionary2.Add(key, value);
					continue;
				}
				JsonShape.Fields(dictionary3, "id", "key", "entryIndex", "field", "before", "after", "approvalTaskId");
				string key2 = JsonShape.Text(dictionary3["key"]);
				string text = JsonShape.Text(dictionary3["field"]);
				int num = JsonShape.Int(dictionary3["entryIndex"]);
				if (!Regex.IsMatch(JsonShape.Text(dictionary3["approvalTaskId"]), "^t_[a-f0-9]{8}$"))
				{
					throw new FormatException("Approval task missing/invalid");
				}
				if (!new string[4] { "Value", "Feminine", "Masculine", "Neutral" }.Contains(text))
				{
					throw new FormatException("Unsupported diff field/operation");
				}
				if (!original.Records.TryGetValue(key2, out var value2) || JsonShape.Text(dictionary3["id"]) != value2.Id || value2.Entries == null || num < 0 || num >= value2.Entries.Count)
				{
					throw new FormatException("Invalid diff target");
				}
				string text2 = JsonShape.Text(dictionary3["before"], nullable: true);
				string text3 = JsonShape.Text(dictionary3["after"], nullable: true);
				if (text2 == text3 || !object.Equals(value2.Entries[num][text], text2))
				{
					throw new FormatException("Invalid diff before/after");
				}
				string[] array = TokenGuard.Inventory(text2).ToArray();
				string[] array2 = TokenGuard.Inventory(text3).ToArray();
				if (!array.SequenceEqual<string>(array2, StringComparer.Ordinal))
				{
					TokenGuard.RegisterException(JsonShape.Text(dictionary3["approvalTaskId"]), "0.1.0", array, array2);
				}
				string key3 = value2.Id + ":" + num + ":" + text;
				if (dictionary.ContainsKey(key3))
				{
					throw new FormatException("Duplicate diff target");
				}
				dictionary.Add(key3, dictionary3);
			}
			Dictionary<string, Record> dictionary4 = new Dictionary<string, Record>(StringComparer.Ordinal);
			int num2 = 0;
			foreach (KeyValuePair<string, Record> record2 in original.Records)
			{
				Record value3 = record2.Value;
				Record record = corrected.Records[record2.Key];
				if (dictionary2.TryGetValue(record2.Key, out var value4))
				{
					if (record.Entries == null || record.Entries.Count != 1 || !value4.After.Same(record.Entries[0]))
					{
						throw new FormatException("addEntry not exactly reflected by corrected snapshot: " + value3.Id);
					}
					num2++;
					dictionary4.Add(record2.Key, record);
				}
				else
				{
					if (Entry.SameLists(value3.Entries, record.Entries))
					{
						continue;
					}
					if (value3.Entries == null || record.Entries == null || value3.Entries.Count != record.Entries.Count)
					{
						throw new FormatException("List/absence operations require a newer validated loader");
					}
					for (int i = 0; i < value3.Entries.Count; i++)
					{
						string[] fields = Entry.Fields;
						foreach (string text4 in fields)
						{
							if (!object.Equals(value3.Entries[i][text4], record.Entries[i][text4]))
							{
								if (!dictionary.TryGetValue(value3.Id + ":" + i + ":" + text4, out var value5) || !object.Equals(value5["after"], record.Entries[i][text4]))
								{
									throw new FormatException("Unapproved change");
								}
								num2++;
							}
						}
					}
					dictionary4.Add(record2.Key, record);
				}
			}
			if (num2 != dictionary.Count + dictionary2.Count)
			{
				throw new FormatException("Diff not reflected by corrected snapshot");
			}
			Changed = new ReadOnlyDictionary<string, Record>(dictionary4);
		}

		public static Catalog Parse(string original, string corrected, string diff)
		{
			return new Catalog(Snapshot.Parse(original, "Original"), Snapshot.Parse(corrected, "Corrigido"), JsonShape.Array(StrictJson.Parse(diff)));
		}
	}
	internal static class TokenGuard
	{
		private static readonly Regex Tokens = new Regex("\\[\\[[^\\]]*\\]\\]|\\[[^\\]]*\\]|\\{[^}]*\\}|\\*[0-9]+|<[^>]*>", RegexOptions.CultureInvariant);

		private static volatile List<(string taskId, string version, string[] beforeTokens, string[] afterTokens)> validatedExceptions;

		private static readonly object validatedExceptionsLock = new object();

		private static List<(string taskId, string version, string[] beforeTokens, string[] afterTokens)> ValidatedExceptions
		{
			get
			{
				if (validatedExceptions == null)
				{
					lock (validatedExceptionsLock)
					{
						if (validatedExceptions == null)
						{
							validatedExceptions = new List<(string, string, string[], string[])>();
						}
					}
				}
				return validatedExceptions;
			}
		}

		internal static IEnumerable<string> Inventory(string s)
		{
			return (from Match m in Tokens.Matches(s ?? "")
				select m.Value).OrderBy<string, string>((string x) => x, StringComparer.Ordinal);
		}

		public static void Check(string before, string after)
		{
			string[] array = Inventory(before).ToArray();
			string[] second = Inventory(after).ToArray();
			if (array.SequenceEqual<string>(second, StringComparer.Ordinal))
			{
				return;
			}
			foreach (var validatedException in ValidatedExceptions)
			{
				if (validatedException.beforeTokens.SequenceEqual<string>(array, StringComparer.Ordinal) && validatedException.afterTokens.SequenceEqual<string>(second, StringComparer.Ordinal))
				{
					return;
				}
			}
			throw new FormatException("Functional tokens/tags changed; explicit validated exception unsupported in 0.1.0");
		}

		public static void RegisterException(string taskId, string version, string[] beforeTokens, string[] afterTokens)
		{
			if (!Regex.IsMatch(taskId, "^t_[a-f0-9]{8}$"))
			{
				throw new FormatException("Invalid exception taskId");
			}
			if (string.IsNullOrEmpty(version))
			{
				throw new FormatException("Invalid exception version");
			}
			if (beforeTokens == null || afterTokens == null)
			{
				throw new FormatException("Null inventory in exception");
			}
			if (beforeTokens.SequenceEqual<string>(afterTokens, StringComparer.Ordinal))
			{
				throw new FormatException("Exception before/after identical");
			}
			ValidatedExceptions.Add((taskId, version, beforeTokens, afterTokens));
		}
	}
	internal static class Composition
	{
		internal enum Agreement
		{
			Masculine,
			Feminine,
			MasculinePlural,
			FemininePlural
		}

		public const string AssemblySha256 = "f3f0069b3a21e7939ed85d9d31ec5ec7cb4c24015811e25350ed2239a25ed182";

		internal static readonly IReadOnlyDictionary<string, Agreement> Nouns = new Dictionary<string, Agreement>(StringComparer.Ordinal)
		{
			["Arma"] = Agreement.Feminine,
			["Escudo"] = Agreement.Masculine,
			["Cabeça"] = Agreement.Feminine,
			["Armadura"] = Agreement.Feminine,
			["Anel"] = Agreement.Masculine,
			["Amuleto"] = Agreement.Masculine,
			["Consumível"] = Agreement.Masculine,
			["Material"] = Agreement.Masculine,
			["Ferramenta"] = Agreement.Feminine,
			["Mercadoria"] = Agreement.Feminine,
			["Espada de 1M"] = Agreement.Feminine,
			["Espada 2M"] = Agreement.Feminine,
			["Machado de 1M"] = Agreement.Masculine,
			["Machado de 2 Mãos"] = Agreement.Masculine,
			["Arma de Haste"] = Agreement.Feminine,
			["Arco"] = Agreement.Masculine,
			["Arma de 1 Mão"] = Agreement.Feminine,
			["Arma de 2M"] = Agreement.Feminine,
			["Cajado"] = Agreement.Masculine,
			["Varinha"] = Agreement.Feminine,
			["Maça 1M"] = Agreement.Feminine,
			["Maça 2M"] = Agreement.Feminine,
			["Arma de Punho"] = Agreement.Feminine,
			["Espada"] = Agreement.Feminine,
			["Adaga"] = Agreement.Feminine,
			["Lança"] = Agreement.Feminine,
			["Bota"] = Agreement.Feminine,
			["Botas"] = Agreement.FemininePlural,
			["Luva"] = Agreement.Feminine,
			["Luvas"] = Agreement.FemininePlural,
			["Capa"] = Agreement.Feminine,
			["Maça"] = Agreement.Feminine,
			["Machado"] = Agreement.Masculine
		};

		internal static readonly string[][] Rarities = new string[5][]
		{
			new string[4] { "Comum", "Comum", "Comuns", "Comuns" },
			new string[4] { "Incomum", "Incomum", "Incomuns", "Incomuns" },
			new string[4] { "Raro", "Rara", "Raros", "Raras" },
			new string[4] { "Lendário", "Lendária", "Lendários", "Lendárias" },
			new string[4] { "Mítico", "Mítica", "Míticos", "Míticas" }
		};

		private static readonly (string Original, string Corrected)[] FortuneLabels = Array.ConvertAll(Rarities, (string[] forms) => (forms[0] + " Sorte", "Fortuna " + forms[1].ToLowerInvariant()));

		public static bool Enabled(Settings settings, bool portuguese, out string reason)
		{
			reason = ((settings == null || !settings.Valid) ? "config invalida" : ((!settings.Active) ? "Ativo=false" : ((settings.Variant != Conjunto.Corrigido) ? "Conjunto=Original" : ((!portuguese) ? "idioma diferente de pt-BR" : null))));
			return reason == null;
		}

		public static string ItemSubtitle(string incoming, out string reason)
		{
			reason = null;
			if (incoming == null)
			{
				reason = "subtitulo nulo";
				return incoming;
			}
			string[] array = incoming.Split('\n');
			int num = -1;
			string text = null;
			for (int i = 0; i < array.Length; i++)
			{
				foreach (KeyValuePair<string, Agreement> noun in Nouns)
				{
					if (array[i] == noun.Key)
					{
						if (num >= 0)
						{
							reason = "mais de uma linha de tipo";
							return incoming;
						}
						num = i;
						text = array[i];
					}
					string[][] rarities = Rarities;
					foreach (string[] array2 in rarities)
					{
						string text2 = array2[(int)noun.Value] + " " + noun.Key;
						if (!(array[i] != array2[0] + " " + noun.Key) || !(array[i] != text2))
						{
							if (num >= 0)
							{
								reason = "mais de uma linha de tipo";
								return incoming;
							}
							num = i;
							text = text2;
						}
					}
				}
			}
			if (num < 0)
			{
				reason = "formato/raridade/tipo nao reconhecido";
				return incoming;
			}
			if (array[num] == text)
			{
				return incoming;
			}
			array[num] = text;
			return string.Join("\n", array);
		}

		public static string FortuneSubtitle(int quality, string incoming, out string reason)
		{
			reason = null;
			if ((uint)quality >= (uint)FortuneLabels.Length)
			{
				reason = "raridade de Fortuna desconhecida";
				return incoming;
			}
			var (text, text2) = FortuneLabels[quality];
			if (incoming == text2)
			{
				return incoming;
			}
			if (incoming == text)
			{
				return text2;
			}
			reason = "subtitulo de Fortuna divergente";
			return incoming;
		}

		public static string DamageLabel(bool healing, string incoming, out string reason)
		{
			reason = null;
			if (!healing)
			{
				return incoming;
			}
			if (incoming == "Cura por Dano")
			{
				return incoming;
			}
			if (incoming == "Dano Cura")
			{
				return "Cura por Dano";
			}
			if (incoming != "Cura de Dano")
			{
				reason = "rotulo Healing divergente";
				return incoming;
			}
			return "Cura por Dano";
		}
	}
	internal sealed class EntryAddition
	{
		public Entry After { get; }

		private EntryAddition(Entry after)
		{
			After = after;
		}

		public static EntryAddition Parse(Dictionary<string, object> d, Snapshot original)
		{
			JsonShape.Fields(d, "operation", "id", "key", "entryIndex", "before", "after", "approvalTaskId");
			if (JsonShape.Text(d["operation"]) != "addEntry")
			{
				throw new FormatException("Unsupported diff operation");
			}
			string text = JsonShape.Text(d["id"]);
			string text2 = JsonShape.Text(d["key"]);
			string text3 = "addEntry " + text + ": ";
			if (!Regex.IsMatch(JsonShape.Text(d["approvalTaskId"]), "^t_[a-f0-9]{8}$"))
			{
				throw new FormatException(text3 + "Approval task missing/invalid");
			}
			if (!original.Records.TryGetValue(text2, out var value) || value.Id != text)
			{
				throw new FormatException(text3 + "Unknown ID/key");
			}
			if (JsonShape.Int(d["entryIndex"]) != 0)
			{
				throw new FormatException(text3 + "Only entryIndex 0 supported");
			}
			if (value.Entries != null && value.Entries.Count != 0)
			{
				throw new FormatException(text3 + "Entry already exists; populated baseline");
			}
			bool num;
			if (value.Entries != null)
			{
				if (d["before"] == null)
				{
					goto IL_0189;
				}
				num = JsonShape.Array(d["before"]).Count != 0;
			}
			else
			{
				num = d["before"] != null;
			}
			if (!num)
			{
				Entry entry = new Entry(JsonShape.Object(d["after"]));
				if (string.IsNullOrWhiteSpace(entry.Value))
				{
					throw new FormatException(text3 + "Value must be nonblank");
				}
				if (entry.Key != text2 || entry.TranslatorKey != null || entry.Feminine != null || entry.Masculine != null || entry.Neutral != null || entry.LanguageGender != 0 || entry.CanBeGendered || entry.NeedsGenderInfo)
				{
					throw new FormatException(text3 + "Unsupported metadata; expected neutral Value-only entry");
				}
				if (!TokenGuard.Inventory(text2).SequenceEqual<string>(TokenGuard.Inventory(entry.Value), StringComparer.Ordinal))
				{
					throw new FormatException(text3 + "Functional tokens/tags changed against source key");
				}
				return new EntryAddition(entry);
			}
			goto IL_0189;
			IL_0189:
			throw new FormatException(text3 + "Baseline null/empty mismatch");
		}
	}
	internal sealed class ModCatalog
	{
		public sealed class Rule
		{
			public string Id;

			public string Kind;

			public string Source;

			public string Target;

			public string[] Slots;

			private Regex matcher;

			private Regex wholeMatcher;

			public Rule(Dictionary<string, object> row)
			{
				JsonShape.Fields(row, "id", "kind", "source", "ptBR", "slots", "approvalTaskId");
				Id = JsonShape.Text(row["id"]);
				Kind = JsonShape.Text(row["kind"]);
				Source = JsonShape.Text(row["source"]);
				Target = JsonShape.Text(row["ptBR"]);
				Slots = (from x in JsonShape.Array(row["slots"])
					select JsonShape.Text(x)).ToArray();
				if (!Regex.IsMatch(Id, "^BT-[0-9]{4}$") || JsonShape.Text(row["approvalTaskId"]) != "t_2e0fe616" || !new string[5] { "note", "suffix", "header", "aura", "fragment" }.Contains(Kind) || Source.Length == 0 || Target.Length == 0)
				{
					throw new FormatException("Invalid BT rule");
				}
				if (!TokenGuard.Inventory(Source).SequenceEqual<string>(TokenGuard.Inventory(Target), StringComparer.Ordinal))
				{
					throw new FormatException("Mod functional tokens changed: " + Id);
				}
				int[] array = (from Match m in Regex.Matches(Source, "\\{([0-9]+)\\}")
					select int.Parse(m.Groups[1].Value) into x
					orderby x
					select x).ToArray();
				int[] first = (from Match m in Regex.Matches(Target, "\\{([0-9]+)\\}")
					select int.Parse(m.Groups[1].Value) into x
					orderby x
					select x).ToArray();
				if (!array.SequenceEqual(Enumerable.Range(0, Slots.Length)) || !first.SequenceEqual(array))
				{
					throw new FormatException("Invalid template slots: " + Id);
				}
				string text = Regex.Escape(Source);
				for (int num = 0; num < Slots.Length; num++)
				{
					string text2 = "[+−-]?[0-9]+(?:[.,][0-9]+)?";
					object obj;
					if (!(Slots[num] == "number"))
					{
						if (!(Slots[num] == "richNumber"))
						{
							if (!(Slots[num] == "gameText"))
							{
								if (!(Slots[num] == "opaque"))
								{
									throw new FormatException("Unknown slot type");
								}
								obj = "[^<>\\r\\n]{1,8192}?";
							}
							else
							{
								obj = "[^<>\\r\\n]{1,512}?";
							}
						}
						else
						{
							obj = "(?:<color=#[0-9A-Fa-f]{6}>" + text2 + "</color>|" + text2 + ")";
						}
					}
					else
					{
						obj = text2;
					}
					string text3 = (string)obj;
					text = text.Replace(Regex.Escape("{" + num + "}"), "(?<v" + num + ">" + text3 + ")");
				}
				matcher = new Regex("\\G(?:" + text + ")", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(30.0));
				wholeMatcher = new Regex("\\A(?:" + text + ")\\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(30.0));
			}

			public bool Match(string text, int start, Func<string, string> localize, out int length, out string result, bool whole = false)
			{
				Match m = (whole ? wholeMatcher : matcher).Match(text, start);
				length = (m.Success ? m.Length : 0);
				result = null;
				if (!m.Success)
				{
					return false;
				}
				result = Regex.Replace(Target, "\\{([0-9]+)\\}", delegate(Match token)
				{
					int num = int.Parse(token.Groups[1].Value);
					string value = m.Groups["v" + num].Value;
					return (Slots[num] == "gameText") ? (localize?.Invoke(value) ?? value) : value;
				});
				return true;
			}
		}

		public const string BetterTooltipsGuid = "com.gumatos.bettertooltips";

		public const string BetterTooltipsVersion = "0.1.6";

		public IReadOnlyList<Rule> Rules { get; }

		public int Count => Rules.Count;

		public static bool Enabled(Settings s, bool portuguese)
		{
			return s != null && s.Valid && s.Active && s.Variant == Conjunto.Corrigido && s.IntegrateMods && portuguese;
		}

		private ModCatalog(string json)
		{
			Dictionary<string, object> dictionary = JsonShape.Object(StrictJson.Parse(json));
			JsonShape.Fields(dictionary, "schemaVersion", "locale", "modGuid", "modVersion", "records");
			if (JsonShape.Int(dictionary["schemaVersion"]) != 1 || JsonShape.Text(dictionary["locale"]) != "pt-BR" || JsonShape.Text(dictionary["modGuid"]) != "com.gumatos.bettertooltips" || JsonShape.Text(dictionary["modVersion"]) != "0.1.6")
			{
				throw new FormatException("Invalid mod registry identity/version");
			}
			List<Rule> list = (from x in JsonShape.Array(dictionary["records"])
				select new Rule(JsonShape.Object(x))).ToList();
			if (list.Count == 0 || list.Select((Rule r) => r.Id).Distinct().Count() != list.Count || list.Select((Rule r) => r.Kind + "\0" + r.Source).Distinct().Count() != list.Count)
			{
				throw new FormatException("Empty/duplicate mod registry");
			}
			Rules = list.AsReadOnly();
		}

		public static ModCatalog Parse(string json)
		{
			return new ModCatalog(json);
		}

		public bool TryWhole(string kind, string input, Func<string, string> localize, out string output)
		{
			output = input;
			if (input == null)
			{
				return false;
			}
			foreach (Rule item in from r in Rules
				where r.Kind == kind
				orderby r.Source.Length descending
				select r)
			{
				if (item.Match(input, 0, localize, out var length, out var result, whole: true) && length == input.Length)
				{
					output = result;
					return true;
				}
			}
			return false;
		}

		public bool TryNote(string input, Func<string, string> localize, out string output)
		{
			output = input;
			if (input == null || input.Length > 32768)
			{
				return false;
			}
			StringBuilder stringBuilder = new StringBuilder(input.Length);
			int num = 0;
			Rule[] array = (from r in Rules
				where r.Kind == "note"
				orderby r.Source.Length descending
				select r).ToArray();
			while (num < input.Length)
			{
				if (char.IsWhiteSpace(input[num]))
				{
					stringBuilder.Append(input[num++]);
					continue;
				}
				bool flag = false;
				Rule[] array2 = array;
				for (int num2 = 0; num2 < array2.Length; num2++)
				{
					if (array2[num2].Match(input, num, localize, out var length, out var result) && (num + length >= input.Length || char.IsWhiteSpace(input[num + length])))
					{
						stringBuilder.Append(result);
						num += length;
						flag = true;
						break;
					}
				}
				if (flag)
				{
					continue;
				}
				return false;
			}
			output = stringBuilder.ToString();
			return true;
		}

		public bool TryAura(string input, Func<string, string> localize, out string output)
		{
			output = input;
			string text = "";
			Match match = Regex.Match(input, " \\(total [+−-]?[0-9]+(?:[.,][0-9]+)?%\\)$", RegexOptions.CultureInvariant);
			if (match.Success)
			{
				text = match.Value;
				input = input.Substring(0, match.Index);
			}
			if (!TryWhole("aura", input, localize, out var output2))
			{
				return false;
			}
			output = output2 + text;
			return true;
		}
	}
	internal static class ModText
	{
		public const string AuraHeader = "Your active shrine auras:";

		public const string SynergyHeader = "Your skills on this status:";

		private const string Number = "[+−-]?[0-9]+(?:[.,][0-9]+)?";

		private static readonly Regex Colors = new Regex("<color=#[0-9A-Fa-f]{6}>(?<body>[^<>]*)</color>", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50.0));

		private static readonly Regex AttributeSuffix = new Regex(" \\(<color=#[0-9A-Fa-f]{6}>(?<parts>[^<>\\r\\n]+)</color>\\)$", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(30.0));

		private static readonly Regex AttributePart = new Regex("^(?<number>[+−-]?[0-9]+(?:[.,][0-9]+)?) (?<label>[^<>\\r\\n]+)$", RegexOptions.CultureInvariant);

		private static readonly Regex ValueSuffix = new Regex(" \\((?:<color=#[0-9A-Fa-f]{6}>)?[+−-]?[0-9]+(?:[.,][0-9]+)?(?:</color>)?(?: health for you| health per turn for you|% increased damage right now| damage per turn for you)\\)\\.$", RegexOptions.CultureInvariant);

		public static string Rebase(ModCatalog map, string original, string localized, string generated, Func<string, string> localize)
		{
			if (generated == null || localized == null || original == null || generated == original)
			{
				return localized;
			}
			int num = generated.Length;
			foreach (Match item in Colors.Matches(generated))
			{
				if (item.Value.StartsWith("<color=#C8B090>", StringComparison.Ordinal) || item.Groups["body"].Value.StartsWith("Your active shrine auras:", StringComparison.Ordinal))
				{
					num = item.Index;
					while (num > 0 && generated[num - 1] == '\n')
					{
						num--;
					}
					break;
				}
			}
			string input = generated.Substring(0, num).TrimEnd();
			string text = localized;
			Match match2 = ValueSuffix.Match(input);
			if (match2.Success && !original.EndsWith(match2.Value, StringComparison.Ordinal))
			{
				if (!map.TryWhole("suffix", match2.Value, localize, out var output))
				{
					throw new FormatException("Unknown BT value suffix");
				}
				text = localized.TrimEnd();
				if (text.EndsWith(".", StringComparison.Ordinal))
				{
					text = text.Substring(0, text.Length - 1);
				}
				text += output;
			}
			else
			{
				Match match3 = AttributeSuffix.Match(input);
				if (match3.Success && !original.EndsWith(match3.Value, StringComparison.Ordinal))
				{
					string newValue = TranslateAttributeList(match3.Groups["parts"].Value, localize);
					text = localized.TrimEnd() + match3.Value.Replace(match3.Groups["parts"].Value, newValue);
				}
			}
			return text + generated.Substring(num);
		}

		private static string TranslateAttributeList(string input, Func<string, string> localize)
		{
			return string.Join(", ", input.Split(new string[1] { ", " }, StringSplitOptions.None).Select(delegate(string part)
			{
				Match match = AttributePart.Match(part);
				if (!match.Success)
				{
					throw new FormatException("Unknown BT attribute suffix");
				}
				return match.Groups["number"].Value + " " + localize(match.Groups["label"].Value);
			}));
		}

		public static string Translate(ModCatalog map, string input, ISet<string> ownedNotes, Func<string, string> localize, Action<string> refusal)
		{
			if (input == null || input.Length > 65536)
			{
				return input;
			}
			return Colors.Replace(input, delegate(Match m)
			{
				string value = m.Groups["body"].Value;
				string output;
				if (ownedNotes.Contains(value))
				{
					if (!map.TryNote(value, localize, out output))
					{
						refusal?.Invoke("nota BT fora do mapa; bloco preservado");
						return m.Value;
					}
				}
				else if (value.StartsWith("Your active shrine auras: ", StringComparison.Ordinal))
				{
					output = Blue(map, value, "Your active shrine auras:", localize, synergy: false);
				}
				else
				{
					if (!value.StartsWith("Your skills on this status: ", StringComparison.Ordinal))
					{
						return m.Value;
					}
					output = Blue(map, value, "Your skills on this status:", localize, synergy: true);
				}
				return m.Value.Substring(0, m.Groups["body"].Index - m.Index) + output + "</color>";
			});
		}

		private static string Blue(ModCatalog map, string body, string header, Func<string, string> localize, bool synergy)
		{
			if (!body.EndsWith(".", StringComparison.Ordinal) || !map.TryWhole("header", header, localize, out var output))
			{
				return body;
			}
			string[] array = body.Substring(header.Length + 1, body.Length - header.Length - 2).Split(new string[1] { "; " }, StringSplitOptions.None);
			List<string> list = new List<string>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				string output2;
				if (synergy)
				{
					output2 = Synergy(map, text, localize);
				}
				else if (!map.TryAura(text, localize, out output2))
				{
					return body;
				}
				list.Add(output2);
			}
			return output + " " + string.Join("; ", list) + ".";
		}

		private static string Fragment(ModCatalog map, string text)
		{
			if (!map.TryWhole("fragment", text, null, out var output))
			{
				return text;
			}
			return output;
		}

		private static string Synergy(ModCatalog map, string item, Func<string, string> localize)
		{
			Match match = Regex.Match(item, "^(?<names>.+) (?<number>[+−-]?[0-9]+(?:[.,][0-9]+)?)(?<effect>%? [^<>]+?)(?<stack> per stack)?$", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(30.0));
			if (!match.Success)
			{
				throw new FormatException("Unknown BT synergy layout");
			}
			string text = string.Join(" + ", match.Groups["names"].Value.Split(new string[1] { " + " }, StringSplitOptions.None).Select(localize));
			string value = match.Groups["effect"].Value;
			value = ((!(value == "% damage") && !(value == "% Max Health")) ? (value.StartsWith("% ", StringComparison.Ordinal) ? ("% " + localize(value.Substring(2))) : (" " + localize(value.Substring(1)))) : Fragment(map, value));
			return text + " " + match.Groups["number"].Value + value + Fragment(map, match.Groups["stack"].Value);
		}
	}
	public enum Conjunto
	{
		Original,
		Corrigido
	}
	internal sealed class Settings
	{
		public bool Active { get; }

		public Conjunto Variant { get; }

		public bool IntegrateMods { get; }

		public bool Diagnostic { get; }

		public bool Valid { get; }

		public Settings(bool active = true, Conjunto variant = Conjunto.Corrigido, bool integrateMods = true, bool diagnostic = false, bool valid = true)
		{
			Active = active;
			Variant = variant;
			IntegrateMods = integrateMods;
			Diagnostic = diagnostic;
			Valid = valid && Enum.IsDefined(typeof(Conjunto), variant);
		}
	}
	internal sealed class StateQueue
	{
		private Settings current = new Settings(active: false);

		private Settings pending;

		public Settings Current => Volatile.Read(in current);

		public void Enqueue(Settings settings)
		{
			Interlocked.Exchange(ref pending, settings ?? new Settings(active: false, Conjunto.Corrigido, integrateMods: true, diagnostic: false, valid: false));
		}

		public bool ApplyPending()
		{
			Settings settings = Interlocked.Exchange(ref pending, null);
			if (settings == null)
			{
				return false;
			}
			Settings settings2 = Current;
			if (settings2.Active == settings.Active && settings2.Variant == settings.Variant && settings2.IntegrateMods == settings.IntegrateMods && settings2.Diagnostic == settings.Diagnostic && settings2.Valid == settings.Valid)
			{
				return false;
			}
			Interlocked.Exchange(ref current, settings);
			return true;
		}
	}
	internal sealed class OnceLog
	{
		private readonly HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal);

		private readonly Action<string> log;

		private readonly int maximum;

		public int Count
		{
			get
			{
				lock (seen)
				{
					return seen.Count;
				}
			}
		}

		public OnceLog(Action<string> log, int maximum = 128)
		{
			this.log = log;
			this.maximum = maximum;
		}

		public void Write(string reason)
		{
			bool flag;
			lock (seen)
			{
				flag = seen.Count < maximum && seen.Add(reason);
			}
			if (flag)
			{
				try
				{
					log?.Invoke(reason);
				}
				catch
				{
				}
			}
		}
	}
	internal sealed class Overlay<T>
	{
		private readonly Catalog catalog;

		private readonly Func<T, Entry, bool> equal;

		private readonly Func<Entry, T> clone;

		private readonly OnceLog log;

		public Overlay(Catalog catalog, Func<T, Entry, bool> equal, Func<Entry, T> clone, OnceLog log)
		{
			this.catalog = catalog;
			this.equal = equal;
			this.clone = clone;
			this.log = log;
		}

		public List<T> Resolve(string key, bool requestedPortuguese, bool effectivePortuguese, Settings settings, List<T> incoming)
		{
			try
			{
				if (catalog == null || settings == null || !settings.Valid || !settings.Active || settings.Variant != Conjunto.Corrigido || !requestedPortuguese || !effectivePortuguese || key == null || !catalog.Changed.TryGetValue(key, out var value))
				{
					return incoming;
				}
				IReadOnlyList<Entry> entries = catalog.Original.Records[key].Entries;
				bool flag = ((entries == null) ? (incoming == null) : (incoming != null && entries.Count == incoming.Count));
				if (flag && entries != null)
				{
					for (int i = 0; i < entries.Count; i++)
					{
						if (!equal(incoming[i], entries[i]))
						{
							flag = false;
							break;
						}
					}
				}
				if (!flag)
				{
					log?.Write("Conflito de baseline: " + value.Id);
					return incoming;
				}
				if (value.Entries == null)
				{
					return incoming;
				}
				List<T> list = new List<T>(value.Entries.Count);
				foreach (Entry entry in value.Entries)
				{
					list.Add(clone(entry));
				}
				return list;
			}
			catch (Exception ex)
			{
				log?.Write("Overlay preservou retorno: " + ex.GetType().Name);
				return incoming;
			}
		}
	}
	internal static class RefreshPlan
	{
		private static bool Effective(Settings s)
		{
			if (s != null && s.Valid && s.Active)
			{
				return s.Variant == Conjunto.Corrigido;
			}
			return false;
		}

		public static bool Needed(Settings before, Settings after)
		{
			return Effective(before) != Effective(after);
		}

		public static KeyValuePair<T, string>[] Select<T>(IEnumerable<KeyValuePair<T, string>> registered, ISet<string> changed)
		{
			return registered.Where((KeyValuePair<T, string> p) => p.Value != null && changed.Contains(p.Value)).ToArray();
		}
	}
	public static class ResourceHashes
	{
		public static readonly IReadOnlyDictionary<string, string> Expected = new Dictionary<string, string>
		{
			{ "correcoes.diff.json", "68f2b7f7571bfad444ecc9b27f9cb7d23dff3c60543f4da809b01177ced72679" },
			{ "manifest.json", "fb2f92a83aa06d52f4a4e467f3965f5448001f78262d0238ffc28853921c1851" },
			{ "pendencias.json", "778e0f9e0d269b15802ab620a18a5ffec1768aeb761428bbd0de75d66fb6dfaf" },
			{ "pt-BR.corrigido.json", "2c50e71cbb52eb35b8011ea0925cc3321c1b3e519d846abd2b6d120e17e957a5" },
			{ "pt-BR.mods.json", "4310f52c22e08bc2e443a5db77984a6b86f346543b14074d1d5daa185cd20c6b" },
			{ "pt-BR.original.json", "80d48629b6f0d6681badee323ee97201d7c445876e9d9d17a6ae0dadab9f2224" },
			{ "upstream.BP3.manifest.json", "2f9e7d57198881d1c2ec31b3332cdbe7e9162d24b34b5a7665299e61888c870e" }
		};
	}
	internal static class Resources
	{
		public static string Sha256(byte[] bytes)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant();
		}

		public static string Decode(byte[] bytes)
		{
			return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(bytes);
		}

		public static string Read(Assembly assembly, string name)
		{
			using Stream stream = assembly.GetManifestResourceStream("BetterPortuguese.Data." + name) ?? throw new InvalidDataException("Missing embedded resource " + name);
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			byte[] bytes = memoryStream.ToArray();
			if (!ResourceHashes.Expected.TryGetValue(name, out var value) || Sha256(bytes) != value)
			{
				throw new InvalidDataException("Resource SHA-256 mismatch " + name);
			}
			return Decode(bytes);
		}

		public static Catalog Load(Assembly assembly)
		{
			foreach (KeyValuePair<string, string> item in ResourceHashes.Expected)
			{
				if (item.Key != "pt-BR.mods.json")
				{
					Read(assembly, item.Key);
				}
			}
			return Catalog.Parse(Read(assembly, "pt-BR.original.json"), Read(assembly, "pt-BR.corrigido.json"), Read(assembly, "correcoes.diff.json"));
		}

		public static ModCatalog LoadMods(Assembly assembly)
		{
			return ModCatalog.Parse(Read(assembly, "pt-BR.mods.json"));
		}
	}
	internal static class StatusAgreement
	{
		internal const string MasculineSuffix = " Aplicado";

		internal const string FeminineSuffix = " Aplicada";

		internal static readonly HashSet<string> Feminine = new HashSet<string>(StringComparer.Ordinal)
		{
			"Resistência ao Controle", "Proteção Elemental", "Terra Ardente", "Terra Sagrada", "Fúria de Batalha", "Maldição", "Fratura", "Nuvem de Fumaça", "Aura do Conquistador", "Aura de Energia",
			"Aura do Xamã"
		};

		internal static string Compose(string incoming, out string reason)
		{
			reason = null;
			if (incoming == null)
			{
				reason = "texto nulo";
				return null;
			}
			if (incoming.Length < " Aplicado".Length)
			{
				reason = "curto demais";
				return incoming;
			}
			int num = TrailingClosingTags(incoming);
			int num2 = incoming.Length - num;
			if (num2 < " Aplicado".Length || string.CompareOrdinal(incoming, num2 - " Aplicado".Length, " Aplicado", 0, " Aplicado".Length) != 0)
			{
				reason = "sem sufixo ' Aplicado' no fim";
				return incoming;
			}
			string text = incoming.Substring(0, num2 - " Aplicado".Length);
			string text2 = ((num == 0) ? string.Empty : incoming.Substring(num2));
			int num3 = LeadingOpeningTags(text);
			string text3 = text.Substring(0, num3);
			string text4 = text.Substring(num3);
			string text5 = string.Empty;
			int num4 = text4.Length;
			while (num4 > 0 && text4[num4 - 1] >= '0' && text4[num4 - 1] <= '9')
			{
				num4--;
			}
			if (num4 < text4.Length && num4 >= 2 && text4[num4 - 2] == ' ' && (text4[num4 - 1] == 'x' || text4[num4 - 1] == 'X'))
			{
				text5 = text4.Substring(num4 - 2);
				text4 = text4.Substring(0, num4 - 2);
			}
			if (text4.IndexOf('<') >= 0 || text4.IndexOf('>') >= 0)
			{
				reason = "markup interna";
				return incoming;
			}
			if (!Feminine.Contains(text4))
			{
				reason = "nome fora da tabela";
				return incoming;
			}
			reason = "feminino:" + text4;
			return text3 + text4 + text5 + " Aplicada" + text2;
		}

		private static int TrailingClosingTags(string text)
		{
			int i;
			string text2;
			for (i = 0; i < text.Length && text[text.Length - 1 - i] == '>'; i += text2.Length)
			{
				int num = text.LastIndexOf('<', text.Length - 1 - i);
				if (num < 0)
				{
					break;
				}
				text2 = text.Substring(num, text.Length - i - num);
				if (!text2.StartsWith("</", StringComparison.Ordinal) || text2.Length < 4)
				{
					break;
				}
			}
			return i;
		}

		private static int LeadingOpeningTags(string text)
		{
			int num = 0;
			while (num < text.Length && text[num] == '<')
			{
				int num2 = text.IndexOf('>', num + 1);
				if (num2 < 0 || num2 + 1 <= num + 1)
				{
					break;
				}
				num = num2 + 1;
			}
			return num;
		}
	}
	internal sealed class StrictJson
	{
		private readonly string text;

		private int pos;

		private StrictJson(string text)
		{
			this.text = text ?? throw new ArgumentNullException("text");
		}

		public static object Parse(string text)
		{
			StrictJson strictJson = new StrictJson(text);
			object result = strictJson.Value(0);
			strictJson.White();
			if (strictJson.pos != text.Length)
			{
				throw strictJson.Error("Trailing content");
			}
			return result;
		}

		private FormatException Error(string reason)
		{
			return new FormatException(reason + " at JSON offset " + pos);
		}

		private void White()
		{
			while (pos < text.Length && " \t\r\n".IndexOf(text[pos]) >= 0)
			{
				pos++;
			}
		}

		private bool Take(char c)
		{
			White();
			if (pos < text.Length && text[pos] == c)
			{
				pos++;
				return true;
			}
			return false;
		}

		private void Need(char c)
		{
			if (!Take(c))
			{
				throw Error("Expected " + c);
			}
		}

		private object Value(int depth)
		{
			if (depth > 64)
			{
				throw Error("Maximum nesting exceeded");
			}
			White();
			if (pos >= this.text.Length)
			{
				throw Error("Unexpected end");
			}
			switch (this.text[pos])
			{
			case '"':
				return String();
			case '{':
			{
				pos++;
				Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal);
				if (Take('}'))
				{
					return dictionary;
				}
				do
				{
					White();
					if (pos >= this.text.Length || this.text[pos] != '"')
					{
						throw Error("Expected member name");
					}
					string text2 = String();
					Need(':');
					object value = Value(depth + 1);
					if (dictionary.ContainsKey(text2))
					{
						throw Error("Duplicate member " + text2);
					}
					dictionary.Add(text2, value);
				}
				while (Take(','));
				Need('}');
				return dictionary;
			}
			case '[':
			{
				pos++;
				List<object> list = new List<object>();
				if (Take(']'))
				{
					return list;
				}
				do
				{
					list.Add(Value(depth + 1));
				}
				while (Take(','));
				Need(']');
				return list;
			}
			default:
			{
				string[] array = new string[3] { "true", "false", "null" };
				foreach (string text in array)
				{
					if (pos + text.Length <= this.text.Length && string.CompareOrdinal(this.text, pos, text, 0, text.Length) == 0)
					{
						pos += text.Length;
						if (!(text == "null"))
						{
							return text == "true";
						}
						return null;
					}
				}
				int num = pos;
				if (this.text[pos] == '-')
				{
					pos++;
				}
				if (pos >= this.text.Length)
				{
					throw Error("Number truncated");
				}
				if (this.text[pos] == '0')
				{
					pos++;
				}
				else
				{
					if (this.text[pos] < '1' || this.text[pos] > '9')
					{
						throw Error("Invalid value");
					}
					Digits();
				}
				if (pos < this.text.Length && this.text[pos] == '.')
				{
					pos++;
					int num2 = pos;
					Digits();
					if (num2 == pos)
					{
						throw Error("Fraction missing");
					}
				}
				if (pos < this.text.Length && (this.text[pos] == 'e' || this.text[pos] == 'E'))
				{
					pos++;
					if (pos < this.text.Length && (this.text[pos] == '+' || this.text[pos] == '-'))
					{
						pos++;
					}
					int num3 = pos;
					Digits();
					if (num3 == pos)
					{
						throw Error("Exponent missing");
					}
				}
				if (!decimal.TryParse(this.text.Substring(num, pos - num), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					throw Error("Number out of range");
				}
				return result;
			}
			}
		}

		private void Digits()
		{
			while (pos < text.Length && text[pos] >= '0' && text[pos] <= '9')
			{
				pos++;
			}
		}

		private char Hex()
		{
			if (pos + 4 > text.Length)
			{
				throw Error("Truncated unicode escape");
			}
			if (!ushort.TryParse(text.Substring(pos, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result))
			{
				throw Error("Invalid unicode escape");
			}
			pos += 4;
			return (char)result;
		}

		private string String()
		{
			Need('"');
			StringBuilder stringBuilder = new StringBuilder();
			while (pos < this.text.Length)
			{
				char c = this.text[pos++];
				if (c == '"')
				{
					string text = stringBuilder.ToString();
					for (int i = 0; i < text.Length; i++)
					{
						if (char.IsHighSurrogate(text[i]))
						{
							if (++i >= text.Length || !char.IsLowSurrogate(text[i]))
							{
								throw Error("Unpaired surrogate");
							}
						}
						else if (char.IsLowSurrogate(text[i]))
						{
							throw Error("Unpaired surrogate");
						}
					}
					return text;
				}
				if (c < ' ')
				{
					throw Error("Control character in string");
				}
				if (c != '\\')
				{
					stringBuilder.Append(c);
					continue;
				}
				if (pos >= this.text.Length)
				{
					throw Error("Truncated escape");
				}
				c = this.text[pos++];
				switch (c)
				{
				case '"':
				case '/':
				case '\\':
					stringBuilder.Append(c);
					break;
				case 'b':
					stringBuilder.Append('\b');
					break;
				case 'f':
					stringBuilder.Append('\f');
					break;
				case 'n':
					stringBuilder.Append('\n');
					break;
				case 'r':
					stringBuilder.Append('\r');
					break;
				case 't':
					stringBuilder.Append('\t');
					break;
				case 'u':
					stringBuilder.Append(Hex());
					break;
				default:
					throw Error("Invalid escape");
				}
			}
			throw Error("Unterminated string");
		}
	}
	internal static class JsonShape
	{
		public static Dictionary<string, object> Object(object value)
		{
			return (value as Dictionary<string, object>) ?? throw new FormatException("Expected object");
		}

		public static List<object> Array(object value)
		{
			return (value as List<object>) ?? throw new FormatException("Expected array");
		}

		public static string Text(object value, bool nullable = false)
		{
			return (value == null && nullable) ? null : ((value as string) ?? throw new FormatException("Expected string"));
		}

		public static bool Bool(object value)
		{
			if (value is bool)
			{
				return (bool)value;
			}
			throw new FormatException("Expected boolean");
		}

		public static int Int(object value)
		{
			if (!(value is decimal num) || !(decimal.Truncate(num) == num) || !(num >= -2147483648m) || !(num <= 2147483647m))
			{
				throw new FormatException("Expected integer");
			}
			return (int)num;
		}

		public static void Fields(Dictionary<string, object> obj, params string[] fields)
		{
			if (obj.Count != fields.Length)
			{
				throw new FormatException("Unexpected/missing fields");
			}
			foreach (string text in fields)
			{
				if (!obj.ContainsKey(text))
				{
					throw new FormatException("Missing field " + text);
				}
			}
		}

		public static bool Equal(object a, object b)
		{
			if (a == b)
			{
				return true;
			}
			if (a is Dictionary<string, object> dictionary && b is Dictionary<string, object> dictionary2)
			{
				if (dictionary.Count != dictionary2.Count)
				{
					return false;
				}
				foreach (KeyValuePair<string, object> item in dictionary)
				{
					if (!dictionary2.TryGetValue(item.Key, out var value) || !Equal(item.Value, value))
					{
						return false;
					}
				}
				return true;
			}
			if (a is List<object> list && b is List<object> list2)
			{
				if (list.Count != list2.Count)
				{
					return false;
				}
				for (int i = 0; i < list.Count; i++)
				{
					if (!Equal(list[i], list2[i]))
					{
						return false;
					}
				}
				return true;
			}
			return object.Equals(a, b);
		}
	}
}