Sump/Generator/MisfitData.cs

Static data layer for the misfit generator. Reads JSON pools (objects, roles, scars, names, backstories, palettes, voice lines) from data/sump/ via FileSystem.Mounted, filters out empty or malformed entries, and exposes them through MisfitTables and MisfitVoice accessors that fall back to the built-in arrays when a pool is missing or empty. A missing or broken file logs one warning and is ignored.

using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// The misfit pools as data. Everything a misfit is rolled from, and every line it can say, is
/// read once from the JSON files in Assets/data/sump/ (see the README there). A file that is
/// missing, unreadable or empty logs one warning and the built-in tables in MisfitTables.cs and
/// MisfitVoice.cs are used instead, pool by pool, so bad data never breaks the game.
/// </summary>
public static class MisfitData
{
	public const string Folder = "data/sump/";

	// ------------------------------------------------------------------ file shapes

	public sealed class FearEntry
	{
		public string Phrase { get; set; }
		public string Kind { get; set; }
	}

	public sealed class ScarsFile
	{
		public Dictionary<string, FearEntry[]> Fears { get; set; }
		public string[] Twitches { get; set; }
		public Dictionary<string, string[]> PlanTwitches { get; set; }
		public Dictionary<string, string[]> SpeechTics { get; set; }
	}

	public sealed class NameParts
	{
		public string[] Start { get; set; }
		public string[] Mid { get; set; }
		public string[] End { get; set; }
	}

	public sealed class NamesFile
	{
		public Dictionary<string, string[]> Nicknames { get; set; }
		public string[] AnyNicknames { get; set; }
		public string[] SwarmNames { get; set; }
		public Dictionary<string, NameParts> Syllables { get; set; }
		public string[] MachineSuffixes { get; set; }
	}

	public sealed class ColourPair
	{
		public float[] Primary { get; set; }
		public float[] Secondary { get; set; }
	}

	public sealed class PlanLook
	{
		public float SizeMin { get; set; }
		public float SizeMax { get; set; }
		public ColourPair[] Colours { get; set; }
	}

	public sealed class VoiceFile
	{
		public string[] Greetings { get; set; }
		public Dictionary<string, string[]> ContactGreetings { get; set; }
		public string[] ObjectLines { get; set; }
		public Dictionary<string, string[]> FearLines { get; set; }
		public Dictionary<string, string[]> HelpLines { get; set; }
		public Dictionary<string, string[]> ThanksLines { get; set; }
		public string[] ThanksTails { get; set; }
		public string[] OrderLines { get; set; }
		public string[] Jingles { get; set; }
		public string[] PriceTags { get; set; }
		public string[] PriceTails { get; set; }
		public Dictionary<string, string> AbilityNames { get; set; }
		public Dictionary<string, string> AbilityDescriptions { get; set; }
		public Dictionary<string, string> ContactDescriptions { get; set; }
		public Dictionary<string, string> TicDescriptions { get; set; }
	}

	// ------------------------------------------------------------------ loaded pools (never null after Ensure; empty means "use the built-in")

	static bool _loaded;
	static Dictionary<string, MisfitTables.ClungThing[]> _objects;
	static MisfitTables.RoleEntry[] _roles;
	static Dictionary<string, (string Phrase, string Kind)[]> _fears;
	static string[] _twitches;
	static Dictionary<string, string[]> _planTwitches;
	static Dictionary<string, string[]> _tics;
	static NamesFile _names;
	static Dictionary<string, (string[] Start, string[] Mid, string[] End)> _syllables;
	static Dictionary<string, string[]> _stories;
	static Dictionary<string, (float[] Primary, float[] Secondary)[]> _palettes;
	static Dictionary<string, (float Min, float Max)> _sizes;
	static VoiceFile _voice;

	public static Dictionary<string, MisfitTables.ClungThing[]> Objects { get { Ensure(); return _objects; } }
	public static MisfitTables.RoleEntry[] Roles { get { Ensure(); return _roles; } }
	public static Dictionary<string, (string Phrase, string Kind)[]> Fears { get { Ensure(); return _fears; } }
	public static string[] Twitches { get { Ensure(); return _twitches; } }
	public static Dictionary<string, string[]> PlanTwitches { get { Ensure(); return _planTwitches; } }
	public static Dictionary<string, string[]> SpeechTics { get { Ensure(); return _tics; } }
	public static NamesFile Names { get { Ensure(); return _names; } }
	public static Dictionary<string, (string[] Start, string[] Mid, string[] End)> Syllables { get { Ensure(); return _syllables; } }
	public static Dictionary<string, string[]> Stories { get { Ensure(); return _stories; } }
	public static Dictionary<string, (float[] Primary, float[] Secondary)[]> Palettes { get { Ensure(); return _palettes; } }
	public static Dictionary<string, (float Min, float Max)> Sizes { get { Ensure(); return _sizes; } }
	public static VoiceFile Voice { get { Ensure(); return _voice; } }

	/// <summary>Forgets what was loaded, so the files are read again at the next roll or spoken line.</summary>
	public static void Reload() => _loaded = false;

	static void Ensure()
	{
		if ( _loaded ) return;
		_loaded = true;

		// objects.json
		_objects = new();
		var objects = Read<Dictionary<string, MisfitTables.ClungThing[]>>( "objects.json", d => d.Count > 0 );
		if ( objects is not null )
			foreach ( var pair in objects )
			{
				var things = (pair.Value ?? Array.Empty<MisfitTables.ClungThing>())
					.Where( t => t is not null && !string.IsNullOrWhiteSpace( t.Name ) ).ToArray();
				foreach ( var t in things ) t.With ??= t.Name;
				if ( things.Length > 0 ) _objects[pair.Key] = things;
			}

		// roles.json
		_roles = (Read<MisfitTables.RoleEntry[]>( "roles.json", a => a.Length > 0 ) ?? Array.Empty<MisfitTables.RoleEntry>())
			.Where( r => r is not null && !string.IsNullOrWhiteSpace( r.Name ) ).ToArray();
		foreach ( var r in _roles )
		{
			r.A ??= ("aeiouAEIOU".IndexOf( r.Name[0] ) >= 0 ? "an " : "a ") + r.Name;
			r.Mission ??= "sent here for reasons nobody wrote down";
			r.Orders ??= "wait for further instructions";
		}

		// scars.json
		var scars = Read<ScarsFile>( "scars.json", s => s.Fears is not null || s.Twitches is not null || s.PlanTwitches is not null || s.SpeechTics is not null );
		_fears = new();
		if ( scars?.Fears is not null )
			foreach ( var pair in scars.Fears )
			{
				var fears = (pair.Value ?? Array.Empty<FearEntry>())
					.Where( f => f is not null && !string.IsNullOrWhiteSpace( f.Phrase ) )
					.Select( f => (f.Phrase, MisfitTables.FearKinds.Contains( f.Kind ) ? f.Kind : "light") ).ToArray();
				if ( fears.Length > 0 ) _fears[pair.Key] = fears;
			}
		_twitches = Strings( scars?.Twitches );
		_planTwitches = Pools( scars?.PlanTwitches );
		_tics = new();
		foreach ( var pair in Pools( scars?.SpeechTics ) )
		{
			// Only tics the voice knows how to speak.
			var tics = pair.Value.Where( t => MisfitTables.SpeechTics.Contains( t ) ).ToArray();
			if ( tics.Length > 0 ) _tics[pair.Key] = tics;
		}

		// names.json
		_names = Read<NamesFile>( "names.json", n => n.Nicknames is not null || n.AnyNicknames is not null || n.SwarmNames is not null || n.Syllables is not null || n.MachineSuffixes is not null ) ?? new NamesFile();
		_names.Nicknames = Pools( _names.Nicknames );
		_names.AnyNicknames = Strings( _names.AnyNicknames );
		_names.SwarmNames = Strings( _names.SwarmNames );
		_names.MachineSuffixes = Strings( _names.MachineSuffixes );
		_syllables = new();
		if ( _names.Syllables is not null )
			foreach ( var pair in _names.Syllables )
			{
				if ( pair.Value is null ) continue;
				var parts = (Strings( pair.Value.Start ), Strings( pair.Value.Mid ), Strings( pair.Value.End ));
				if ( parts.Item1.Length > 0 && parts.Item2.Length > 0 && parts.Item3.Length > 0 ) _syllables[pair.Key] = parts;
			}

		// backstories.json
		_stories = Pools( Read<Dictionary<string, string[]>>( "backstories.json", d => d.Count > 0 ) );

		// palettes.json
		_palettes = new();
		_sizes = new();
		var looks = Read<Dictionary<string, PlanLook>>( "palettes.json", d => d.Count > 0 );
		if ( looks is not null )
			foreach ( var pair in looks )
			{
				if ( pair.Value is null ) continue;
				var colours = (pair.Value.Colours ?? Array.Empty<ColourPair>())
					.Where( c => c is not null && c.Primary is { Length: >= 3 } && c.Secondary is { Length: >= 3 } )
					.Select( c => (c.Primary, c.Secondary) ).ToArray();
				if ( colours.Length > 0 ) _palettes[pair.Key] = colours;
				if ( pair.Value.SizeMin > 0f && pair.Value.SizeMax >= pair.Value.SizeMin ) _sizes[pair.Key] = (pair.Value.SizeMin, pair.Value.SizeMax);
			}

		// voice.json
		_voice = Read<VoiceFile>( "voice.json", v => v.Greetings is not null || v.HelpLines is not null || v.ThanksLines is not null || v.OrderLines is not null
			|| v.ObjectLines is not null || v.FearLines is not null || v.ContactGreetings is not null || v.Jingles is not null || v.PriceTags is not null
			|| v.ContactDescriptions is not null || v.AbilityDescriptions is not null ) ?? new VoiceFile();
		_voice.Greetings = Strings( _voice.Greetings );
		_voice.ContactGreetings = Pools( _voice.ContactGreetings );
		_voice.ObjectLines = Strings( _voice.ObjectLines );
		_voice.FearLines = Pools( _voice.FearLines );
		_voice.HelpLines = Pools( _voice.HelpLines );
		_voice.ThanksLines = Pools( _voice.ThanksLines );
		_voice.ThanksTails = Strings( _voice.ThanksTails );
		_voice.OrderLines = Strings( _voice.OrderLines );
		_voice.Jingles = Strings( _voice.Jingles );
		_voice.PriceTags = Strings( _voice.PriceTags );
		_voice.PriceTails = Strings( _voice.PriceTails );
	}

	/// <summary>Reads one pool file. Null (and one warning) if it is missing, unreadable or has nothing in it.</summary>
	static T Read<T>( string file, Func<T, bool> hasAnything ) where T : class
	{
		var path = Folder + file;
		try
		{
			if ( !FileSystem.Mounted.FileExists( path ) )
			{
				Log.Warning( $"Sump data: {path} is missing, using the built-in pool." );
				return null;
			}
			var data = FileSystem.Mounted.ReadJson<T>( path );
			if ( data is null || !hasAnything( data ) )
			{
				Log.Warning( $"Sump data: {path} is empty, using the built-in pool." );
				return null;
			}
			return data;
		}
		catch ( Exception e )
		{
			Log.Warning( $"Sump data: {path} could not be read, using the built-in pool: {e.Message}" );
			return null;
		}
	}

	static string[] Strings( string[] list ) => list is null ? Array.Empty<string>() : list.Where( s => s is not null ).ToArray();

	static Dictionary<string, string[]> Pools( Dictionary<string, string[]> pools )
	{
		var clean = new Dictionary<string, string[]>();
		if ( pools is null ) return clean;
		foreach ( var pair in pools )
		{
			var list = Strings( pair.Value );
			if ( list.Length > 0 ) clean[pair.Key] = list;
		}
		return clean;
	}

	// ------------------------------------------------------------------ "loaded, or else built-in"

	public static T[] Pool<T>( T[] loaded, T[] builtIn ) => loaded is not null && loaded.Length > 0 ? loaded : builtIn;

	public static T[] Pool<T>( Dictionary<string, T[]> pools, string key, T[] builtIn ) =>
		pools is not null && key is not null && pools.TryGetValue( key, out var loaded ) && loaded is not null && loaded.Length > 0 ? loaded : builtIn;

	public static string Text( Dictionary<string, string> texts, string key, string builtIn ) =>
		texts is not null && key is not null && texts.TryGetValue( key, out var loaded ) && !string.IsNullOrWhiteSpace( loaded ) ? loaded : builtIn;
}

// The public pool accessors: the data files first, the built-in tables behind them.
public static partial class MisfitTables
{
	static readonly FirstContact[] Contacts =
	{
		FirstContact.ShotOnFarm, FirstContact.Dissected, FirstContact.WorshippedThenSold, FirstContact.BecameMeme, FirstContact.AdoptedThenForgotten,
	};

	public static ClungThing[] ThingsFor( FirstContact c ) => MisfitData.Pool( MisfitData.Objects, c.ToString(), BuiltInThingsFor( c ) );

	/// <summary>Objects anybody might cling to, whatever happened to them ("Any" in objects.json).</summary>
	public static ClungThing[] AnyThings => MisfitData.Pool( MisfitData.Objects, "Any", GeneralThings );

	/// <summary>Every clung object there is (for shrines, markets, lookups).</summary>
	public static IEnumerable<ClungThing> AllThings => Contacts.SelectMany( ThingsFor ).Concat( AnyThings );

	public static RoleEntry[] Roles => MisfitData.Pool( MisfitData.Roles, BuiltInRoles );

	public static (string Phrase, string Kind)[] FearsFor( FirstContact c ) => MisfitData.Pool( MisfitData.Fears, c.ToString(), BuiltInFearsFor( c ) );

	public static string[] Twitches => MisfitData.Pool( MisfitData.Twitches, BuiltInTwitches );
	public static string[] TwitchesFor( BodyPlan plan ) => MisfitData.Pool( MisfitData.PlanTwitches, plan.ToString(), BuiltInTwitchesFor( plan ) );
	public static string[] TicsFor( FirstContact c ) => MisfitData.Pool( MisfitData.SpeechTics, c.ToString(), BuiltInTicsFor( c ) );

	public static string[] NicknamesFor( FirstContact c ) => MisfitData.Pool( MisfitData.Names.Nicknames, c.ToString(), BuiltInNicknamesFor( c ) );
	public static string[] AnyNicknames => MisfitData.Pool( MisfitData.Names.AnyNicknames, BuiltInAnyNicknames );
	public static string[] SwarmNames => MisfitData.Pool( MisfitData.Names.SwarmNames, BuiltInSwarmNames );
	public static string[] MachineSuffixes => MisfitData.Pool( MisfitData.Names.MachineSuffixes, BuiltInMachineSuffixes );

	/// <summary>Start, middle and end sounds for a body plan's alien names.</summary>
	public static (string[] Start, string[] Mid, string[] End) SyllablesFor( BodyPlan plan ) =>
		MisfitData.Syllables.TryGetValue( plan.ToString(), out var parts ) ? parts : BuiltInSyllablesFor( plan );

	public static string[] StoriesFor( FirstContact c ) => MisfitData.Pool( MisfitData.Stories, c.ToString(), BuiltInStoriesFor( c ) );

	/// <summary>Primary and secondary colour pairs per body plan, as r,g,b.</summary>
	public static (float[] Primary, float[] Secondary)[] PaletteFor( BodyPlan plan ) => MisfitData.Pool( MisfitData.Palettes, plan.ToString(), BuiltInPaletteFor( plan ) );

	/// <summary>Smallest and largest Size for a body plan (the generator keeps it inside 0.6 to 1.6).</summary>
	public static (float Min, float Max) SizeFor( BodyPlan plan ) =>
		MisfitData.Sizes.TryGetValue( plan.ToString(), out var size ) ? size : BuiltInSizeFor( plan );
}

// The voice's line pools, the same way.
public static partial class MisfitVoice
{
	static string[] Jingles => MisfitData.Pool( MisfitData.Voice.Jingles, BuiltInJingles );
	static string[] PriceTags => MisfitData.Pool( MisfitData.Voice.PriceTags, BuiltInPriceTags );
	static string[] PriceTails => MisfitData.Pool( MisfitData.Voice.PriceTails, BuiltInPriceTails );
	static string[] Greetings => MisfitData.Pool( MisfitData.Voice.Greetings, BuiltInGreetings );
	static string[] ObjectLines => MisfitData.Pool( MisfitData.Voice.ObjectLines, BuiltInObjectLines );
	static string[] ThanksTails => MisfitData.Pool( MisfitData.Voice.ThanksTails, BuiltInThanksTails );
	static string[] OrderLines => MisfitData.Pool( MisfitData.Voice.OrderLines, BuiltInOrderLines );

	static string[] GreetingsFor( FirstContact c ) => MisfitData.Pool( MisfitData.Voice.ContactGreetings, c.ToString(), BuiltInGreetingsFor( c ) );
	static string[] FearLines( string kind ) => MisfitData.Pool( MisfitData.Voice.FearLines, kind, BuiltInFearLines( kind ) );
	static string[] HelpLines( FirstContact c ) => MisfitData.Pool( MisfitData.Voice.HelpLines, c.ToString(), BuiltInHelpLines( c ) );
	static string[] ThanksLines( FirstContact c ) => MisfitData.Pool( MisfitData.Voice.ThanksLines, c.ToString(), BuiltInThanksLines( c ) );

	public static string AbilityName( TwistedAbility a ) => MisfitData.Text( MisfitData.Voice.AbilityNames, a.ToString(), BuiltInAbilityName( a ) );
	public static string AbilityDescription( TwistedAbility a ) => MisfitData.Text( MisfitData.Voice.AbilityDescriptions, a.ToString(), BuiltInAbilityDescription( a ) );
	public static string ContactDescription( FirstContact c ) => MisfitData.Text( MisfitData.Voice.ContactDescriptions, c.ToString(), BuiltInContactDescription( c ) );
	public static string TicDescription( string tic ) => MisfitData.Text( MisfitData.Voice.TicDescriptions, tic, BuiltInTicDescription( tic ) );
}