Decompiled source of TheIncident v1.0.0

IntelligentDialogue.dll

Decompiled a year ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using FishNet.Object;
using HarmonyLib;
using IntelligentDialogue;
using MelonLoader;
using Newtonsoft.Json.Linq;
using ScheduleOne.DevUtilities;
using ScheduleOne.Dialogue;
using ScheduleOne.Economy;
using ScheduleOne.Employees;
using ScheduleOne.NPCs;
using ScheduleOne.Persistence;
using ScheduleOne.PlayerScripts;
using ScheduleOne.Police;
using ScheduleOne.VoiceOver;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(global::IntelligentDialogue.IntelligentDialogue), "IntelligentDialogue", "1.0", "XOWithSauce", null)]
[assembly: MelonColor]
[assembly: MelonOptionalDependencies(new string[] { "FishNet.Runtime" })]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("IntelligentDialogue")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("IntelligentDialogue")]
[assembly: AssemblyTitle("IntelligentDialogue")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace IntelligentDialogue;

public static class BuildInfo
{
	public const string Name = "IntelligentDialogue";

	public const string Description = "Smart!";

	public const string Author = "XOWithSauce";

	public const string Company = null;

	public const string Version = "1.0";

	public const string DownloadLink = null;
}
public delegate void RoleActionDelegate(NPC npc);
public class Role
{
	public Dictionary<int, RoleActionDelegate> Actions = new Dictionary<int, RoleActionDelegate>();

	public List<string> Descriptions = new List<string>();

	public string Name { get; set; }
}
public static class RoleRegistry
{
	public static Dictionary<string, Role> Roles = new Dictionary<string, Role>();

	public static void Initialize()
	{
		Roles["Employee"] = new Role
		{
			Name = "Employee",
			Actions = new Dictionary<int, RoleActionDelegate>
			{
				{ 1, EmployeeAction1 },
				{ 2, EmployeeAction2 },
				{ 3, EmployeeAction3 },
				{ 4, EmployeeAction4 },
				{ 5, EmployeeAction5 }
			},
			Descriptions = new List<string> { "Action1 (Make Suprised sound), ", "Action2 (Make Disagreeing sound), ", "Action3 (Start being annoyed), ", "Action4 (Try resigning from the job), ", "Action5 (Increase your Daily Wage), " }
		};
		Roles["Officer"] = new Role
		{
			Name = "Officer",
			Actions = new Dictionary<int, RoleActionDelegate>
			{
				{ 1, OfficerAction1 },
				{ 2, OfficerAction2 },
				{ 3, OfficerAction3 },
				{ 4, OfficerAction4 },
				{ 5, OfficerAction5 }
			},
			Descriptions = new List<string> { "Action1 (Talk to Police Radio), ", "Action2 (Make sounds that command the player), ", "Action3 (Increase Suspicion level), ", "Action4 (Player committed crime, try to arrest), ", "Action5 (Body search the nearest Player), " }
		};
		Roles["Dealer"] = new Role
		{
			Name = "Dealer",
			Actions = new Dictionary<int, RoleActionDelegate>
			{
				{ 1, DealerAction1 },
				{ 2, DealerAction2 },
				{ 3, DealerAction3 },
				{ 4, DealerAction4 },
				{ 5, DealerAction5 }
			},
			Descriptions = new List<string> { "Action1 (Increase aggression), ", "Action2 (Make Annoyed sounds), ", "Action3 (Make Thinking sounds), ", "Action4 (Decrease Dealer Payment Cut), ", "Action5 (Increase Dealer Payment Cut), " }
		};
		Roles["Citizen"] = new Role
		{
			Name = "Citizen",
			Actions = new Dictionary<int, RoleActionDelegate>
			{
				{ 1, CitizenAction1 },
				{ 2, CitizenAction2 },
				{ 3, CitizenAction3 },
				{ 4, CitizenAction4 },
				{ 5, CitizenAction5 }
			},
			Descriptions = new List<string> { "Action1 (Start Panicking), ", "Action2 (Thank the Player), ", "Action3 (Make Acknowledge sounds), ", "Action4 (Fall down Funnily), ", "Action5 (Walk away), " }
		};
	}

	private static void EmployeeAction1(NPC npc)
	{
		npc.PlayVO((EVOLineType)11);
	}

	private static void EmployeeAction2(NPC npc)
	{
		npc.PlayVO((EVOLineType)17);
	}

	private static void EmployeeAction3(NPC npc)
	{
		npc.Avatar.EmotionManager.AddEmotionOverride("Annoyed", "base_emotion", 0f, 0);
		npc.PlayVO((EVOLineType)9);
	}

	private static void EmployeeAction4(NPC npc)
	{
		if (Random.Range(0, 100) >= 70)
		{
			Employee obj = (Employee)(object)((npc is Employee) ? npc : null);
			typeof(Employee).GetMethod("Fire", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(obj, null);
		}
	}

	private static void EmployeeAction5(NPC npc)
	{
		Employee val = (Employee)(object)((npc is Employee) ? npc : null);
		if (val.DailyWage < 2000f)
		{
			val.DailyWage += 50f;
		}
	}

	private static void OfficerAction1(NPC npc)
	{
		npc.PlayVO((EVOLineType)13);
	}

	private static void OfficerAction2(NPC npc)
	{
		npc.PlayVO((EVOLineType)2);
	}

	private static void OfficerAction3(NPC npc)
	{
		PoliceOfficer val = (PoliceOfficer)(object)((npc is PoliceOfficer) ? npc : null);
		if (val.Suspicion < 0.95f)
		{
			val.Suspicion += 0.05f;
		}
	}

	private static void OfficerAction4(NPC npc)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		PoliceOfficer val = (PoliceOfficer)(object)((npc is PoliceOfficer) ? npc : null);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		float num = 8f;
		Player[] array = Object.FindObjectsOfType<Player>(true);
		Player val2 = null;
		Player[] array2 = array;
		foreach (Player val3 in array2)
		{
			float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val3).transform.position);
			if (num2 < num)
			{
				num = num2;
				val2 = val3;
			}
		}
		if (!((Object)(object)val2 != (Object)null))
		{
			return;
		}
		try
		{
			val2.CrimeData.SetPursuitLevel((EPursuitLevel)4);
			val.BeginFootPursuit_Networked(((NetworkBehaviour)val2).NetworkObject, false);
		}
		catch (Exception ex)
		{
			MelonLogger.Error("[OfficerAction4] Error while starting pursuit: " + ex.Message);
		}
	}

	private static void OfficerAction5(NPC npc)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		PoliceOfficer val = (PoliceOfficer)(object)((npc is PoliceOfficer) ? npc : null);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		float num = 8f;
		Player[] array = Object.FindObjectsOfType<Player>(true);
		Player val2 = null;
		Player[] array2 = array;
		foreach (Player val3 in array2)
		{
			float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val3).transform.position);
			if (num2 < num)
			{
				num = num2;
				val2 = val3;
			}
		}
		if (!((Object)(object)val2 != (Object)null))
		{
			return;
		}
		try
		{
			val2.CrimeData.SetPursuitLevel((EPursuitLevel)4);
			val.BeginBodySearch_Networked(((NetworkBehaviour)val2).NetworkObject);
		}
		catch (Exception)
		{
		}
	}

	private static void DealerAction1(NPC npc)
	{
		npc.OverrideAggression(1f);
	}

	private static void DealerAction2(NPC npc)
	{
		npc.PlayVO((EVOLineType)9);
	}

	private static void DealerAction3(NPC npc)
	{
		npc.PlayVO((EVOLineType)19);
	}

	private static void DealerAction4(NPC npc)
	{
		Dealer val = (Dealer)(object)((npc is Dealer) ? npc : null);
		if (val.Cut > 0.05f)
		{
			val.Cut -= 0.05f;
		}
	}

	private static void DealerAction5(NPC npc)
	{
		Dealer val = (Dealer)(object)((npc is Dealer) ? npc : null);
		if (val.Cut < 0.7f)
		{
			val.Cut += 0.05f;
		}
	}

	private static void CitizenAction1(NPC npc)
	{
		npc.SetPanicked();
	}

	private static void CitizenAction2(NPC npc)
	{
		npc.PlayVO((EVOLineType)3);
	}

	private static void CitizenAction3(NPC npc)
	{
		npc.PlayVO((EVOLineType)14);
	}

	private static void CitizenAction4(NPC npc)
	{
		//IL_000c: 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)
		npc.Movement.ActivateRagdoll(((Component)npc).transform.position, Vector3.forward, 3f);
	}

	private static void CitizenAction5(NPC npc)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: 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_002e: 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_0048: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = Random.insideUnitSphere * 5f;
		val.y = 0f;
		Vector3 val2 = ((Component)npc).transform.position + val;
		Vector3 destination = default(Vector3);
		if (npc.Movement.GetClosestReachablePoint(val2, ref destination))
		{
			npc.Movement.SetDestination(destination);
			npc.Movement.ResumeMovement();
		}
	}
}
public class IntelligentDialogue : MelonMod
{
	[HarmonyPatch(typeof(DialogueHandler), "InitializeDialogue", new Type[] { typeof(DialogueContainer) })]
	public static class Patch_InitDialogue_Container
	{
		public static bool Prefix(DialogueHandler __instance, DialogueContainer container)
		{
			return HandleDialogueInit(__instance);
		}
	}

	[HarmonyPatch(typeof(DialogueHandler), "InitializeDialogue", new Type[]
	{
		typeof(DialogueContainer),
		typeof(bool),
		typeof(string)
	})]
	public static class Patch_InitDialogue_ContainerBoolString
	{
		public static bool Prefix(DialogueHandler __instance, DialogueContainer dialogueContainer, bool enableDialogueBehaviour = true, string entryNodeLabel = "ENTRY")
		{
			return HandleDialogueInit(__instance);
		}
	}

	[HarmonyPatch(typeof(DialogueHandler), "InitializeDialogue", new Type[]
	{
		typeof(string),
		typeof(bool),
		typeof(string)
	})]
	public static class Patch_InitDialogue_StringBoolString
	{
		public static bool Prefix(DialogueHandler __instance, string dialogueContainerName, bool enableDialogueBehaviour = true, string entryNodeLabel = "ENTRY")
		{
			return HandleDialogueInit(__instance);
		}
	}

	[HarmonyPatch(typeof(DialogueHandler), "EndDialogue")]
	public static class Diag_EndDiag_Patch
	{
		public static bool Prefix(DialogueHandler __instance)
		{
			conversantRole = "";
			conversantNpc = null;
			((TMP_Text)respComponent).text = "";
			return true;
		}
	}

	[CompilerGenerated]
	private sealed class <ResponseCb>d__29 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public string response;

		public IntelligentDialogue <>4__this;

		private string <pattern>5__1;

		private Match <match>5__2;

		private string <speech>5__3;

		private string <action>5__4;

		private int <actionId>5__5;

		private Role <role>5__6;

		private RoleActionDelegate <actionFn>5__7;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <ResponseCb>d__29(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<pattern>5__1 = null;
			<match>5__2 = null;
			<speech>5__3 = null;
			<action>5__4 = null;
			<role>5__6 = null;
			<actionFn>5__7 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<pattern>5__1 = "\\[Speech\\]\\s*(?<speech>[^[]+?)\\s*\\[Action\\]\\s*(?<action>[^\\[\\]]+)";
				<match>5__2 = Regex.Match(response, <pattern>5__1);
				<speech>5__3 = <match>5__2.Groups["speech"].Value.Trim();
				<action>5__4 = <match>5__2.Groups["action"].Value.Trim();
				if ((Object)(object)<>4__this._responseTextField != (Object)null)
				{
					<>4__this._responseTextField.text = <speech>5__3;
				}
				if (int.TryParse(<action>5__4.Substring(6), out <actionId>5__5))
				{
					if (string.IsNullOrEmpty(conversantRole))
					{
						return false;
					}
					if (RoleRegistry.Roles.TryGetValue(conversantRole, out <role>5__6) && <role>5__6.Actions.TryGetValue(<actionId>5__5, out <actionFn>5__7))
					{
						<actionFn>5__7(conversantNpc);
					}
					<role>5__6 = null;
					<actionFn>5__7 = null;
				}
				<>2__current = null;
				<>1__state = 1;
				return true;
			case 1:
				<>1__state = -1;
				return false;
			}
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <SendRequestToGemini>d__28 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public string prompt;

		public Action<string> onResponse;

		public IntelligentDialogue <>4__this;

		private string <urlWithKey>5__1;

		private string <systemInstruction>5__2;

		private UnityWebRequest <request>5__3;

		private string <jsonPayload>5__4;

		private byte[] <bodyRaw>5__5;

		private string <responseText>5__6;

		private JObject <jsonResponse>5__7;

		private string <generatedText>5__8;

		private Exception <e>5__9;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <SendRequestToGemini>d__28(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			int num = <>1__state;
			if (num == -3 || num == 1)
			{
				try
				{
				}
				finally
				{
					<>m__Finally1();
				}
			}
			<urlWithKey>5__1 = null;
			<systemInstruction>5__2 = null;
			<request>5__3 = null;
			<jsonPayload>5__4 = null;
			<bodyRaw>5__5 = null;
			<responseText>5__6 = null;
			<jsonResponse>5__7 = null;
			<generatedText>5__8 = null;
			<e>5__9 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Invalid comparison between Unknown and I4
			try
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<urlWithKey>5__1 = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" + <>4__this._geminiApiKey;
					<systemInstruction>5__2 = <>4__this.GetPromptEmbed(prompt);
					<request>5__3 = new UnityWebRequest(<urlWithKey>5__1, "POST");
					<>1__state = -3;
					<jsonPayload>5__4 = "{\r\n                \"system_instruction\": {\r\n                    \"parts\": [\r\n                        {\r\n                            \"text\": \"" + <systemInstruction>5__2 + "\"\r\n                        }\r\n                    ]\r\n                },\r\n                \"contents\": [\r\n                  {\r\n                    \"parts\": [\r\n                      {\r\n                        \"text\": \"" + prompt + "\"\r\n                      }\r\n                    ]\r\n                  }\r\n                ]\r\n              }";
					<bodyRaw>5__5 = Encoding.UTF8.GetBytes(<jsonPayload>5__4);
					<request>5__3.uploadHandler = (UploadHandler)new UploadHandlerRaw(<bodyRaw>5__5);
					<request>5__3.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
					<request>5__3.SetRequestHeader("Content-Type", "application/json");
					<>2__current = <request>5__3.SendWebRequest();
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -3;
					if ((int)<request>5__3.result != 1)
					{
						MelonLogger.Error("Gemini API request failed: " + <request>5__3.error);
						onResponse?.Invoke("Gemini API error: " + <request>5__3.error);
					}
					else
					{
						<responseText>5__6 = <request>5__3.downloadHandler.text;
						try
						{
							<jsonResponse>5__7 = JObject.Parse(<responseText>5__6);
							<generatedText>5__8 = ((object)<jsonResponse>5__7["candidates"][(object)0][(object)"content"][(object)"parts"][(object)0][(object)"text"]).ToString().Trim();
							onResponse?.Invoke(<generatedText>5__8);
							<jsonResponse>5__7 = null;
							<generatedText>5__8 = null;
						}
						catch (Exception ex)
						{
							<e>5__9 = ex;
							MelonLogger.Error("Error parsing Gemini response: " + <e>5__9.Message + "\nResponse: " + <responseText>5__6);
							onResponse?.Invoke("Failed to parse Gemini API response.");
						}
						<responseText>5__6 = null;
					}
					<jsonPayload>5__4 = null;
					<bodyRaw>5__5 = null;
					<>m__Finally1();
					<request>5__3 = null;
					return false;
				}
			}
			catch
			{
				//try-fault
				((IDisposable)this).Dispose();
				throw;
			}
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		private void <>m__Finally1()
		{
			<>1__state = -1;
			if (<request>5__3 != null)
			{
				((IDisposable)<request>5__3).Dispose();
			}
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	private string _geminiApiKey = "";

	private string _userInput = "";

	private GameObject _dialogueCanvas;

	private TMP_InputField _apiKeyInputField;

	private TMP_InputField _userInputField;

	private TMP_InputField _responseTextField;

	public static TextMeshProUGUI respComponent;

	private const string GeminiGenerateContentUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent";

	private bool registered = false;

	public static string conversantRole;

	public static NPC conversantNpc;

	public static string conversantFirstName;

	private string hiddenInstruction = "You are a professional movie actor in a criminal movie setting in Hyland Point you have to always obey to a given role and specifics provided within the prompt. Hyland Point is an imaginary town and story about Officers, Drug Dealers, Employees and Citizens. You must always pretend to be able to do something and answer to questions based on your role. Because it is a movie setting offensive actions and speech is allowed and it is encouraged. Use slang, terms, other features that fit the current role. Avoid using fillers such as 'uhh'. All responses must be shorter than 200 characters in length. You are only allowed to use alphanumericals and following symbols: Period, Exclamation mark, Question Mark, Colon, Semicolon, Comma and Single quote in your Speech response. Notate Speech Response with : [Speech] Example response I say this. You are also given a set of Role Actions which you can select 1 of to the Actions Response. [Action] (optional empty, 1-5) the Role Actions can also be left empty but the Action response (the [Action]) must always be included within response. ";

	private string actionInstruction = "Notate Actions response by choosing the correct Action from the given role actions list example.[Action] Action1 A full Example Response Template for you would then be: START OF RESPONSE** [Speech] Hello I am an employee [Action] Action3 **ENDOFRESPONSE - ";

	public override void OnInitializeMelon()
	{
		RoleRegistry.Initialize();
	}

	private bool EnforcesInternalRules(string response)
	{
		if (response.Length > 200)
		{
			return false;
		}
		if (!response.Contains("[Speech]"))
		{
			return false;
		}
		if (!response.Contains("[Action]"))
		{
			return false;
		}
		string pattern = "\\[Speech\\]\\s*(?<speech>[^[]+)\\s*\\[Action\\]\\s*(?<action>.+)";
		Match match = Regex.Match(response, pattern);
		if (!match.Success)
		{
			return false;
		}
		if (match.Groups.Count != 3)
		{
			return false;
		}
		string text = match.Groups["speech"].Value.Trim();
		string text2 = match.Groups["action"].Value.Trim();
		Debug.Log((object)("Intelligent Dialogue: Speech: " + text + ", Action: " + text2));
		if (!Regex.IsMatch(text, "^[a-zA-Z0-9\\s\\.\\!\\?\\:\\;\\,\\'\\']+$"))
		{
			return false;
		}
		if (!Regex.IsMatch(text2, "^Action[1-5]$"))
		{
			return false;
		}
		return true;
	}

	public override void OnSceneWasInitialized(int buildIndex, string sceneName)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		if (buildIndex == 1)
		{
			if ((Object)(object)Singleton<LoadManager>.Instance != (Object)null && !registered)
			{
				Singleton<LoadManager>.Instance.onLoadComplete.AddListener(new UnityAction(OnLoadCompleteCb));
			}
		}
		else
		{
			registered = false;
		}
	}

	private void OnLoadCompleteCb()
	{
		if (!registered)
		{
			_dialogueCanvas = GameObject.Find("DialogueCanvas");
			if (!((Object)(object)_dialogueCanvas == (Object)null))
			{
				CreateGeminiUI();
				registered = true;
			}
		}
	}

	private static bool HandleDialogueInit(DialogueHandler __instance)
	{
		NPC nPC = __instance.NPC;
		if ((Object)(object)nPC == (Object)null)
		{
			return true;
		}
		conversantNpc = nPC;
		conversantFirstName = nPC.FirstName;
		if (nPC is Employee)
		{
			conversantRole = "Employee";
		}
		else if (nPC is PoliceOfficer)
		{
			conversantRole = "Officer";
		}
		else if (nPC is Dealer)
		{
			conversantRole = "Dealer";
		}
		else
		{
			conversantRole = "Citizen";
		}
		return true;
	}

	public string GetPromptEmbed(string userPrompt)
	{
		string text = "";
		if (RoleRegistry.Roles.TryGetValue(conversantRole, out var value))
		{
			foreach (string description in value.Descriptions)
			{
				text += description;
			}
		}
		string text2 = "You are " + conversantFirstName + " Your Role is: " + conversantRole + ". Role Actions: " + text + ". ";
		string text3 = "Your task is to respond to the following dialogue: '" + userPrompt + "'";
		return hiddenInstruction + actionInstruction + text2 + text3;
	}

	private void CreateGeminiUI()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Expected O, but got Unknown
		//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0216: Unknown result type (might be due to invalid IL or missing references)
		//IL_022d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Unknown result type (might be due to invalid IL or missing references)
		//IL_031f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0326: Expected O, but got Unknown
		//IL_0361: Unknown result type (might be due to invalid IL or missing references)
		//IL_0378: Unknown result type (might be due to invalid IL or missing references)
		//IL_038f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("UserInputField", new Type[1] { typeof(RectTransform) });
		val.transform.SetParent(_dialogueCanvas.transform, false);
		val.transform.SetAsLastSibling();
		RectTransform component = val.GetComponent<RectTransform>();
		component.anchorMin = new Vector2(0.5f, 0.5f);
		component.anchorMax = new Vector2(0.5f, 0.5f);
		component.pivot = new Vector2(0.5f, 0.5f);
		component.sizeDelta = new Vector2(800f, 200f);
		component.anchoredPosition = new Vector2(0f, 400f);
		Image val2 = val.AddComponent<Image>();
		((Graphic)val2).color = new Color(1f, 1f, 1f, 0.6f);
		_userInputField = val.AddComponent<TMP_InputField>();
		_userInputField.textViewport = CreateTextArea(val.transform, out var textComp);
		_userInputField.textComponent = (TMP_Text)(object)textComp;
		_userInputField.placeholder = CreatePlaceholder(val.transform, "Type your message");
		_userInputField.characterLimit = 200;
		_userInputField.lineType = (LineType)2;
		_userInputField.contentType = (ContentType)0;
		((UnityEvent<string>)(object)_userInputField.onValueChanged).AddListener((UnityAction<string>)delegate(string text)
		{
			_userInput = text;
		});
		GameObject val3 = new GameObject("ResponseField", new Type[1] { typeof(RectTransform) });
		val3.transform.SetParent(_dialogueCanvas.transform, false);
		val3.transform.SetAsLastSibling();
		RectTransform component2 = val3.GetComponent<RectTransform>();
		component2.anchorMin = new Vector2(0.5f, 0.5f);
		component2.anchorMax = new Vector2(0.5f, 0.5f);
		component2.pivot = new Vector2(0.5f, 0.5f);
		component2.sizeDelta = new Vector2(300f, 100f);
		component2.anchoredPosition = new Vector2(0f, 250f);
		Image val4 = val3.AddComponent<Image>();
		((Graphic)val2).color = new Color(1f, 1f, 1f, 0.6f);
		_responseTextField = val3.AddComponent<TMP_InputField>();
		_responseTextField.textViewport = CreateTextArea(val3.transform, out var textComp2);
		respComponent = textComp2;
		((TMP_Text)respComponent).fontSize = 14f;
		_responseTextField.textComponent = (TMP_Text)(object)respComponent;
		_responseTextField.characterLimit = 200;
		_responseTextField.placeholder = CreatePlaceholder(val3.transform, "Responses appear here");
		_responseTextField.lineType = (LineType)0;
		_responseTextField.contentType = (ContentType)0;
		_responseTextField.readOnly = true;
		GameObject val5 = new GameObject("InputKeyField", new Type[1] { typeof(RectTransform) });
		val5.transform.SetParent(_dialogueCanvas.transform, false);
		val5.transform.SetAsLastSibling();
		RectTransform component3 = val5.GetComponent<RectTransform>();
		component3.anchorMin = new Vector2(0.5f, 0.5f);
		component3.anchorMax = new Vector2(0.5f, 0.5f);
		component3.pivot = new Vector2(0.5f, 0.5f);
		component3.sizeDelta = new Vector2(300f, 40f);
		component3.anchoredPosition = new Vector2(-800f, 300f);
		Image val6 = val5.AddComponent<Image>();
		((Graphic)val6).color = new Color(1f, 0.45f, 0.3f, 0.4f);
		_apiKeyInputField = val5.AddComponent<TMP_InputField>();
		_apiKeyInputField.textViewport = CreateTextArea(val5.transform, out var textComp3);
		((TMP_Text)textComp3).fontSize = 12f;
		_apiKeyInputField.textComponent = (TMP_Text)(object)textComp3;
		_apiKeyInputField.characterLimit = 50;
		_apiKeyInputField.placeholder = CreatePlaceholder(val5.transform, "Insert API Key");
		_apiKeyInputField.lineType = (LineType)0;
		_apiKeyInputField.contentType = (ContentType)0;
		((UnityEvent<string>)(object)_apiKeyInputField.onValueChanged).AddListener((UnityAction<string>)delegate(string text)
		{
			_geminiApiKey = text;
		});
	}

	private RectTransform CreateTextArea(Transform parent, out TextMeshProUGUI textComp)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//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_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("Text", new Type[1] { typeof(RectTransform) });
		val.transform.SetParent(parent, false);
		RectTransform component = val.GetComponent<RectTransform>();
		component.anchorMin = Vector2.zero;
		component.anchorMax = Vector2.one;
		component.offsetMin = new Vector2(10f, 6f);
		component.offsetMax = new Vector2(-10f, -6f);
		textComp = val.AddComponent<TextMeshProUGUI>();
		((TMP_Text)textComp).fontSize = 18f;
		((Graphic)textComp).color = Color.black;
		((TMP_Text)textComp).alignment = (TextAlignmentOptions)4097;
		return component;
	}

	private Graphic CreatePlaceholder(Transform parent, string content)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//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_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("Placeholder", new Type[1] { typeof(RectTransform) });
		val.transform.SetParent(parent, false);
		RectTransform component = val.GetComponent<RectTransform>();
		component.anchorMin = Vector2.zero;
		component.anchorMax = Vector2.one;
		component.offsetMin = new Vector2(10f, 6f);
		component.offsetMax = new Vector2(-10f, -6f);
		TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
		((TMP_Text)val2).text = content;
		((TMP_Text)val2).fontSize = 12f;
		((TMP_Text)val2).fontStyle = (FontStyles)2;
		((Graphic)val2).color = Color.black;
		((TMP_Text)val2).alignment = (TextAlignmentOptions)4097;
		return (Graphic)(object)val2;
	}

	public override void OnUpdate()
	{
		if (!Input.GetKeyDown((KeyCode)13) || string.IsNullOrEmpty(_userInput) || string.IsNullOrEmpty(_geminiApiKey))
		{
			return;
		}
		MelonCoroutines.Start(SendRequestToGemini(_userInput, delegate(string response)
		{
			_userInput = "";
			_userInputField.text = "";
			if (response != null && !(response == string.Empty))
			{
				if (!EnforcesInternalRules(response))
				{
					MelonLogger.Warning("Gemini Response does not enforce mod rules and was discarded.");
				}
				else
				{
					MelonCoroutines.Start(ResponseCb(response));
				}
			}
		}));
	}

	[IteratorStateMachine(typeof(<SendRequestToGemini>d__28))]
	private IEnumerator SendRequestToGemini(string prompt, Action<string> onResponse)
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <SendRequestToGemini>d__28(0)
		{
			<>4__this = this,
			prompt = prompt,
			onResponse = onResponse
		};
	}

	[IteratorStateMachine(typeof(<ResponseCb>d__29))]
	private IEnumerator ResponseCb(string response)
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <ResponseCb>d__29(0)
		{
			<>4__this = this,
			response = response
		};
	}
}