Framework/Scripting/Gamemodes/GamemodeRegistry.cs

Discovers gamemodes under lua/gamemodes by reading each folder's gamemode.json through a BaseFileSystem. Validates manifests, rejects dependency cycles and gamemodes whose dependencies are missing or invalid, exposes the valid and rejected sets, and computes a depth-first load order. Logs a summary of accepted and rejected gamemodes.

File Access
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Diagnostics;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Discovers and validates gamemodes under <c>lua/gamemodes/*/gamemode.json</c>. Invalid gamemodes are
/// listed with their problems but never loaded.
/// </summary>
public sealed class GamemodeRegistry
{
	public const string GamemodesRoot = "lua/gamemodes";

	readonly Dictionary<string, GamemodeManifest> _valid = new();
	readonly Dictionary<string, List<string>> _invalid = new();

	public IReadOnlyDictionary<string, GamemodeManifest> Valid => _valid;
	public IReadOnlyDictionary<string, List<string>> Invalid => _invalid;

	public static GamemodeRegistry Current { get; private set; } = new();

	public static GamemodeRegistry Discover( BaseFileSystem fs, bool makeCurrent = true )
	{
		var reg = new GamemodeRegistry();

		if ( fs.DirectoryExists( GamemodesRoot ) )
		{
			foreach ( var folder in fs.FindDirectory( GamemodesRoot, "*", false ).OrderBy( x => x ) )
			{
				if ( folder.StartsWith( "_" ) ) continue; // templates (e.g. _template) are not gamemodes
				var root = $"{GamemodesRoot}/{folder}";
				var path = $"{root}/gamemode.json";
				if ( !fs.FileExists( path ) ) continue;

				GamemodeManifest m;
				try
				{
					if ( !Json.TryDeserialize( fs.ReadAllText( path ), out m ) || m is null )
					{
						reg._invalid[folder] = new List<string> { "gamemode.json is not valid JSON" };
						continue;
					}
				}
				catch ( System.Exception e )
				{
					reg._invalid[folder] = new List<string> { $"gamemode.json could not be read: {e.Message}" };
					continue;
				}

				m.Root = root;
				var problems = m.Validate( folder );
				if ( problems.Count > 0 ) reg._invalid[folder] = problems;
				else reg._valid[m.Id] = m;
			}
		}

		// Cycles: find every gamemode on a cycle before removing any, so all members are reported.
		var cycles = new Dictionary<string, List<string>>();
		foreach ( var m in reg._valid.Values )
			if ( reg.FindCycle( m.Id ) is { } cycle ) cycles[m.Id] = cycle;
		foreach ( var (id, cycle) in cycles )
		{
			reg._valid.Remove( id );
			reg._invalid[id] = new List<string> { $"dependency cycle: {string.Join( " -> ", cycle )}" };
		}

		// Dependencies must exist and be valid; remove anything that depends on something invalid, repeatedly.
		bool changed = true;
		while ( changed )
		{
			changed = false;
			foreach ( var m in reg._valid.Values.ToList() )
			{
				var missing = m.Dependencies.Where( d => !reg._valid.ContainsKey( d ) ).ToList();
				if ( missing.Count == 0 ) continue;
				reg._valid.Remove( m.Id );
				reg._invalid[m.Id] = missing.Select( d => $"dependency \"{d}\" is missing or invalid" ).ToList();
				changed = true;
			}
		}

		if ( makeCurrent ) Current = reg;
		return reg;
	}

	List<string> FindCycle( string start )
	{
		var path = new List<string>();
		var onPath = new HashSet<string>();

		List<string> Visit( string id )
		{
			if ( onPath.Contains( id ) )
			{
				var from = path.IndexOf( id );
				var cyc = path.Skip( from ).ToList();
				cyc.Add( id );
				return cyc;
			}
			if ( !_valid.TryGetValue( id, out var m ) ) return null;
			onPath.Add( id );
			path.Add( id );
			foreach ( var d in m.Dependencies )
				if ( Visit( d ) is { } c ) return c;
			path.RemoveAt( path.Count - 1 );
			onPath.Remove( id );
			return null;
		}

		return Visit( start );
	}

	/// <summary>Load order for a gamemode: its dependencies first (depth-first), then itself. Null if not loadable.</summary>
	public List<GamemodeManifest> LoadOrder( string id )
	{
		if ( !_valid.ContainsKey( id ) ) return null;
		var order = new List<GamemodeManifest>();
		var seen = new HashSet<string>();

		void Add( string g )
		{
			if ( !seen.Add( g ) ) return;
			var m = _valid[g];
			foreach ( var d in m.Dependencies ) Add( d );
			order.Add( m );
		}

		Add( id );
		return order;
	}

	public void LogSummary()
	{
		foreach ( var m in _valid.Values )
			RpLog.Info( "gamemodes", $"Found {m.Id} {m.Version} \"{m.Title}\"{(m.Dependencies.Count > 0 ? " (depends on " + string.Join( ", ", m.Dependencies ) + ")" : "")}" );
		foreach ( var (id, problems) in _invalid )
			RpLog.Warn( "gamemodes", $"Rejected gamemode '{id}': {string.Join( "; ", problems )}" );
	}
}