Editor/GolfCourseProjectMeta.cs
using Sandbox;
using Editor;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;

/// <summary>
/// Keeps a course project's package metadata right so a mapper never edits the .sbproj by hand,
/// and publishes the course the way the backend expects a map.
///
/// While editing the project is an "addon" with no ParentPackage and PrimaryAsset the scene with
/// the course in it. A project with a parent package makes the editor fetch and reference that
/// game at compile time, and a map-typed project does not compile its local libraries at all;
/// either way a mapper whose editor cannot load the game loses every kit component. This state
/// is restored when the editor comes up, after a code reload and after every scene save, which
/// also repairs a project an older kit left as a map.
///
/// Publishing goes through the course scene's own publish settings (Golf Kit &gt; Publish
/// course.., <see cref="PublishCourse"/>): the scene asset is published as a "map" package of the
/// game, through a temporary project the way the Inspector's Publish button publishes a scene.
/// That is the only form of map the backend indexes: a whole project uploaded with Type "map"
/// gets a package record, but it never appears under "type:map" or "target:" (checked
/// 2026-10-28: all 100 newest indexed maps carry the asset publish's AssetType metadata, and a
/// project-published map with the same ParentPackage was missing from every listing), so the
/// game's course screen never sees it.
///
/// Only the editor's active project is touched, only when it holds golf objects (a Golf Course
/// Info or a Hole) and is neither the game nor the kit. Everything goes through the live
/// <see cref="Project.Config"/> and the editor's own project save: the editor writes the .sbproj
/// from that config on close, so a file edited behind its back would be overwritten.
/// </summary>
public static class GolfCourseProjectMeta
{
	public const string GameIdent = "mrtn.golfwithyourguns";
	public const string KitIdent = "mrtn.golfkit";
	public const string MapType = "map";
	public const string EditType = "addon";

	/// <summary>Marker in a scene's publish settings: the kit filled them in once, the mapper's later edits stand.</summary>
	const string CourseMetaKey = "GolfCourse";

	static readonly System.Collections.Generic.HashSet<string> _skipped = new( StringComparer.OrdinalIgnoreCase );

	// The editor's own handlers take these arguments (EditorMainWindow, Scene); the event system
	// refuses a handler whose parameter count differs.
	[Event( "editor.created" )]
	static void OnEditorCreated( EditorMainWindow window ) => Apply( "editor start", null );

	[EditorEvent.Hotload]
	static void OnHotload() => Apply( "code reload", null );

	[Event( "scene.saved" )]
	static void OnSceneSaved( Scene scene ) => Apply( "scene save", scene?.Source?.ResourcePath );

	/// <summary>How often the editor events above have fired, and the last reason: a check that the hooks are wired.</summary>
	public static int Fired { get; private set; }
	public static string LastReason { get; private set; }

	static void Apply( string reason, string savedScene )
	{
		Fired++;
		LastReason = reason;
		try
		{
			Apply( Project.Current, savedScene ?? SceneEditorSession.Active?.Scene?.Source?.ResourcePath, reason );
		}
		catch ( Exception e )
		{
			Log.Warning( e, $"Golf Kit: course metadata ({reason}) failed" );
		}
	}

	/// <summary>
	/// Puts the project in the editing state (Type addon, no ParentPackage, PrimaryAsset the course
	/// scene) when it is not there already, saves the project through the editor and reads the
	/// config back. Returns true when something changed. A project with no golf objects is left
	/// alone; so are the game and the kit, and game or library projects.
	/// </summary>
	public static bool Apply( Project project, string openScene, string reason )
	{
		if ( !IsCourseProject( project, out var config, out var ident ) ) return false;

		var scenes = CourseScenes( project );
		if ( scenes.Count == 0 ) return false;

		var scene = Choose( scenes, openScene, ident );

		var currentType = config.Type ?? "";
		var currentParent = config.GetMetaOrDefault<string>( "ParentPackage", null ) ?? "";
		var currentPrimary = config.GetMetaOrDefault<string>( "PrimaryAsset", null ) ?? "";
		var typeOk = string.Equals( currentType, EditType, StringComparison.OrdinalIgnoreCase );
		if ( typeOk && currentParent.Length == 0 && string.Equals( currentPrimary, scene, StringComparison.OrdinalIgnoreCase ) )
			return false;

		config.Type = EditType;
		config.Metadata?.Remove( "ParentPackage" );
		config.SetMeta( "PrimaryAsset", scene );
		var wasMap = string.Equals( currentType, MapType, StringComparison.OrdinalIgnoreCase ) || string.Equals( currentType, "content", StringComparison.OrdinalIgnoreCase );
		Log.Info( $"Golf Kit: {ident} ({reason}): Type {Show( currentType )} -> {EditType}, ParentPackage {Show( currentParent )} -> (none), PrimaryAsset {Show( currentPrimary )} -> {scene}"
			+ ( wasMap ? "; the course is published as a map package of the game through Golf Kit > Publish course.." : "" ) );

		Save( project );
		Verify( project, scene );
		return true;
	}

	/// <summary>
	/// Golf Kit &gt; Publish course..: fills in the course scene's publish settings (a "map" package
	/// of the game: ParentPackage and GameSupport the game, PrimaryAsset the scene; on the first
	/// run the project's org, ident and title, so a course keeps the ident it had), saves them to
	/// the scene's .meta, and opens the editor's Publisher on the temporary project the editor
	/// builds for a published asset. The mapper's own project is left in the editing state.
	/// </summary>
	[Menu( "Editor", "Golf Kit/Publish course..", "upload_file" )]
	public static void PublishCourse()
	{
		try
		{
			var project = Project.Current;
			if ( !IsCourseProject( project, out var projectConfig, out var ident ) )
			{
				Log.Warning( $"Golf Kit: {Show( project?.Config?.FullIdent )} is not a course project (the game, the kit, a game or library project, or no project); nothing to publish" );
				return;
			}

			var scenes = CourseScenes( project );
			if ( scenes.Count == 0 )
			{
				Log.Warning( $"Golf Kit: {ident} has no scene with a Golf Course Info or a Hole; nothing to publish" );
				return;
			}

			var scene = Choose( scenes, SceneEditorSession.Active?.Scene?.Source?.ResourcePath, ident );
			Apply( project, scene, "publish" );

			var asset = AssetSystem.FindByPath( Path.Combine( project.GetAssetsPath(), scene ) ) ?? AssetSystem.FindByPath( scene );
			if ( asset is null )
			{
				Log.Warning( $"Golf Kit: the course scene {scene} of {ident} is not in the asset system (is it saved?); nothing to publish" );
				return;
			}

			var publishing = asset.Publishing;
			var config = publishing.ProjectConfig;
			var fresh = !config.TryGetMeta<bool>( CourseMetaKey, out var marked ) || !marked;
			publishing.Enabled = true;
			config.Type = MapType;
			if ( fresh || string.IsNullOrEmpty( config.Org ) || string.Equals( config.Org, "local", StringComparison.OrdinalIgnoreCase ) )
				config.Org = projectConfig.Org;
			if ( fresh || string.IsNullOrEmpty( config.Ident ) )
				config.Ident = projectConfig.Ident;
			if ( fresh || string.IsNullOrEmpty( config.Title ) )
				config.Title = string.IsNullOrEmpty( projectConfig.Title ) ? config.Ident : projectConfig.Title;
			config.SetMeta( "ParentPackage", GameIdent );
			config.SetMeta( "GameSupport", new System.Collections.Generic.List<string> { GameIdent } );
			config.SetMeta( "PrimaryAsset", scene );
			config.SetMeta( CourseMetaKey, true );
			publishing.Save();
			Log.Info( $"Golf Kit: {ident} (publish): the scene {scene} is published as {config.FullIdent}, a {MapType} package of {GameIdent}{( fresh ? " (publish settings filled in from the project; change them on the Publisher's first page)" : "" )}" );

			var context = publishing.BuildPublishContext();
			if ( !context.PublishingEnabled )
			{
				Log.Warning( $"Golf Kit: the scene {scene} cannot be published: {context.ReasonForDisabling}" );
				return;
			}

			var thumbnail = CaptureThumbnail( project, scene );

			var temporary = publishing.CreateTemporaryProject( context.IncludeCode ? project.RootDirectory : null );
			if ( temporary is null )
			{
				Log.Warning( $"Golf Kit: the editor would not build a publish project for {scene}; publish the scene from its Inspector's Publish button instead" );
				return;
			}

			var wizard = OpenPublisher( temporary, context );
			if ( wizard is null )
				Log.Warning( $"Golf Kit: the editor's Publisher could not be opened from here; select {scene} in the Asset Browser and press the Inspector's Publish button, the settings are filled in" );
			else
				_ownWizards.Add( wizard );

			if ( wizard is not null && thumbnail is not null )
				_pendingThumbnail = (wizard, thumbnail, RealTime.Now);
			else
				_ = RemindAboutThumbnailAsync( config.FullIdent );
		}
		catch ( Exception e )
		{
			Log.Warning( e, "Golf Kit: Publish course failed" );
		}
	}

	/// <summary>
	/// sbox.game lists a map (and a game) only when it has a thumbnail; the backend's generated
	/// placeholder logo does not count (checked 2026-10-28: none of the 30 newest listed maps had
	/// one, and a course with one was missing from every map listing and from "target:"). The
	/// Publisher uploads a thumbnail only when one is picked on its first page, and when the
	/// package already exists it shows the placeholder there as if it were one. So the mapper is
	/// told, in the console and in a dialog, to pick an image; with the package's current state
	/// when the backend answers.
	/// </summary>
	static async System.Threading.Tasks.Task RemindAboutThumbnailAsync( string fullIdent )
	{
		var state = "";
		try
		{
			var package = await Package.FetchAsync( fullIdent, false, false );
			if ( package is null ) state = $"{fullIdent} is not on sbox.game yet, so it has no thumbnail. ";
			else if ( string.IsNullOrEmpty( package.Thumb ) || package.Thumb.Contains( "generated", StringComparison.OrdinalIgnoreCase ) ) state = $"{fullIdent} has only the placeholder logo on sbox.game, which is why the game's course list does not show it. ";
			else return;
		}
		catch ( Exception e )
		{
			Log.Info( $"Golf Kit: could not look up {fullIdent} on sbox.game ({e.Message}); the thumbnail reminder stands" );
		}

		var message = state + "sbox.game lists a map only when it has a thumbnail, and the Publisher uploads one only if you pick it: click the square image on its first page and choose a PNG or JPG before you publish.";
		Log.Warning( $"Golf Kit: {message}" );
		try { Dialog.AskConfirm( () => { }, message, "Golf Kit: pick a thumbnail", "OK", "Later" ); }
		catch ( Exception e ) { Log.Info( $"Golf Kit: the thumbnail dialog could not be shown ({e.Message})" ); }
	}

	/// <summary>
	/// The editor's publish wizard (Editor.Wizards.PublishWizard in the editor's tools addon, not
	/// public), opened the way the Inspector's Publish button opens it for an asset: with the
	/// asset's temporary project and its publish context. False when this editor build has no
	/// such wizard.
	/// </summary>
	static object OpenPublisher( Project project, ResourcePublishContext context )
	{
		var wizardType = AppDomain.CurrentDomain.GetAssemblies()
			.Select( a => { try { return a.GetType( "Editor.Wizards.PublishWizard", false ); } catch { return null; } } )
			.FirstOrDefault( t => t is not null );
		var open = wizardType?.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static )
			.FirstOrDefault( m => m.Name == "Open" && m.GetParameters().Length >= 1 && m.GetParameters()[0].ParameterType == typeof( Project ) );
		if ( open is null ) return null;

		var parameters = open.GetParameters();
		var args = new object[parameters.Length];
		args[0] = project;
		for ( var i = 1; i < parameters.Length; i++ )
		{
			var type = parameters[i].ParameterType;
			args[i] = type.IsInstanceOfType( context ) ? context : type.IsValueType ? Activator.CreateInstance( type ) : null;
		}

		return open.Invoke( null, args );
	}

	// ---------------------------------------------------------------- the thumbnail

	/// <summary>Where the captured thumbnail is written: the project's .sbox folder, which is never published or committed.</summary>
	const string ThumbnailFile = "golfkit_thumbnail.png";
	const int ThumbnailSize = 512;

	/// <summary>
	/// Renders the course from the Golf Menu Camera (or the first camera in the scene) to a square
	/// PNG for the Publisher's thumbnail. Needs the course scene to be the open scene. Null when
	/// nothing could be rendered; the reminder dialog then stands in.
	/// </summary>
	static string CaptureThumbnail( Project project, string scenePath )
	{
		try
		{
			var scene = SceneEditorSession.Active?.Scene;
			var openPath = (scene?.Source?.ResourcePath ?? "").Replace( '\\', '/' ).TrimStart( '/' );
			if ( scene is null || !string.Equals( openPath, scenePath, StringComparison.OrdinalIgnoreCase ) )
			{
				Log.Info( $"Golf Kit: no thumbnail captured, the open scene is {Show( openPath )} and the course scene is {scenePath}" );
				return null;
			}
			using var sceneScope = scene.Push();

			Transform view;
			var fov = 70f;
			var menu = scene.GetAllComponents<GolfMenuCamera>().FirstOrDefault( m => m.IsValid() );
			if ( menu is not null && menu.HasValidView )
			{
				view = menu.ViewAt( 0f );
				fov = menu.FieldOfView;
			}
			else
			{
				var camera = scene.GetAllComponents<CameraComponent>().FirstOrDefault( c => c.IsValid() );
				if ( camera is null ) { Log.Info( "Golf Kit: no thumbnail captured, the scene has no Golf Menu Camera and no camera" ); return null; }
				view = camera.WorldTransform;
				fov = camera.FieldOfView;
			}

			var target = Texture.CreateRenderTarget( "golfkit-thumbnail", ImageFormat.RGBA8888, new Vector2( ThumbnailSize, ThumbnailSize ) );
			var sceneCamera = new SceneCamera
			{
				World = scene.SceneWorld,
				Position = view.Position,
				Rotation = view.Rotation,
				FieldOfView = fov,
				ZNear = 5f,
				ZFar = 60000f,
				Size = new Vector2( ThumbnailSize, ThumbnailSize ),
				BackgroundColor = Color.Black,
			};
			Graphics.RenderToTexture( sceneCamera, target );
			var bitmap = target.GetBitmap( 0 );
			if ( bitmap is null ) { Log.Info( "Golf Kit: no thumbnail captured, the render could not be read back" ); return null; }
			var png = bitmap.ToPng();
			if ( png is null || png.Length < 1024 ) { Log.Info( "Golf Kit: no thumbnail captured, the render came back empty" ); return null; }

			var folder = Path.Combine( project.RootDirectory.FullName, ".sbox" );
			Directory.CreateDirectory( folder );
			var path = Path.Combine( folder, ThumbnailFile );
			File.WriteAllBytes( path, png );
			Log.Info( $"Golf Kit: thumbnail captured from {( menu is not null ? "the Golf Menu Camera" : "the first camera" )} ({ThumbnailSize}x{ThumbnailSize}) to {path}" );
			return path;
		}
		catch ( Exception e )
		{
			Log.Info( $"Golf Kit: no thumbnail captured ({e.Message}); pick one on the Publisher's first page" );
			return null;
		}
	}

	// The wizard that still needs the captured thumbnail: it makes its Workshop choices when its
	// first page shows, so the thumbnail is handed over from the frame event once they exist.
	static (object Wizard, string Path, float Since)? _pendingThumbnail;

	/// <summary>Sets the captured file as the wizard's picked thumbnail (what its upload sends to the Workshop). True once done or given up.</summary>
	static bool HandOverThumbnail()
	{
		if ( _pendingThumbnail is not { } pending ) return true;
		try
		{
			var wizard = pending.Wizard;
			if ( wizard is Widget w && !w.IsValid() ) { _pendingThumbnail = null; return true; }
			var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
			var config = wizard.GetType().GetField( "Config", flags )?.GetValue( wizard );
			var workshop = config?.GetType().GetProperty( "Workshop", flags )?.GetValue( config );
			if ( workshop is null )
			{
				if ( RealTime.Now - pending.Since > 20f ) { Log.Info( "Golf Kit: the Publisher made no Workshop choices (not a Workshop upload?); pick the thumbnail by hand if it asks for one" ); _pendingThumbnail = null; return true; }
				return false;
			}
			var picked = workshop.GetType().GetProperty( "PickedThumbnail", flags );
			if ( picked is null || !picked.CanWrite ) { Log.Info( "Golf Kit: this editor's Publisher takes no picked thumbnail from here; pick one on its first page" ); _pendingThumbnail = null; return true; }
			picked.SetValue( workshop, pending.Path );
			var preview = workshop.GetType().GetProperty( "Preview", flags );
			if ( preview is not null && preview.CanWrite )
			{
				try { preview.SetValue( workshop, Pixmap.FromFile( pending.Path ) ); } catch { }
			}
			_pendingThumbnail = null;
			Log.Info( "Golf Kit: the captured thumbnail is set on the Publisher; replace it on the first page if you want another" );
			return true;
		}
		catch ( Exception e )
		{
			Log.Info( $"Golf Kit: the thumbnail could not be handed to the Publisher ({e.Message}); pick one on its first page" );
			_pendingThumbnail = null;
			return true;
		}
	}

	// ---------------------------------------------------------------- the project's own Publish..

	// The wizards this class opened (for the temporary projects), so a Publisher for the mapper's
	// own project can be told apart from them.
	static readonly HashSet<object> _ownWizards = new();
	static readonly HashSet<object> _seenWizards = new();
	static TimeSince _sinceWatch;

	/// <summary>
	/// Every frame: hands a pending thumbnail over, and watches for the editor's Publisher opened on
	/// the course project itself (the project name's Publish..). That upload would be a plain addon
	/// the game cannot find, so the window is closed and Publish course takes over. The window is
	/// found through the editor's focus, the only handle the editor gives.
	/// </summary>
	[EditorEvent.Frame]
	static void OnFrame()
	{
		HandOverThumbnail();

		if ( _sinceWatch < 0.25f ) return;
		_sinceWatch = 0;
		try
		{
			for ( var w = Editor.Application.FocusWidget; w is not null && w.IsValid(); w = w.Parent )
			{
				if ( w.GetType().Name != "PublishWizard" ) continue;
				if ( _ownWizards.Contains( w ) || _seenWizards.Contains( w ) ) return;
				_seenWizards.Add( w );
				var wizardProject = w.GetType().GetField( "Project" )?.GetValue( w ) as Project;
				if ( wizardProject is null || wizardProject != Project.Current ) return;
				if ( !IsCourseProject( wizardProject, out _, out var ident ) || CourseScenes( wizardProject ).Count == 0 ) return;

				w.Destroy();
				Log.Warning( $"Golf Kit: the project's own Publish.. would upload {ident} as a plain addon the game's course list cannot find; Publish course opens instead" );
				PublishCourse();
				return;
			}
		}
		catch ( Exception e )
		{
			Log.Info( $"Golf Kit: the Publisher watch failed ({e.Message})" );
		}
	}

	/// <summary>The active project when it is a mapper's course project: not built in, not the game or the kit, not a game or library project.</summary>
	static bool IsCourseProject( Project project, out Sandbox.DataModel.ProjectConfig config, out string ident )
	{
		config = project?.Config;
		ident = config?.FullIdent ?? "";
		if ( project is null || config is null || project.IsBuiltIn ) return false;

		if ( string.Equals( ident, GameIdent, StringComparison.OrdinalIgnoreCase ) || string.Equals( ident, KitIdent, StringComparison.OrdinalIgnoreCase ) )
			return false;
		if ( string.Equals( config.Type, "game", StringComparison.OrdinalIgnoreCase ) || string.Equals( config.Type, "library", StringComparison.OrdinalIgnoreCase ) )
		{
			if ( _skipped.Add( ident ) ) Log.Info( $"Golf Kit: {ident} is a {config.Type} project, its metadata is left alone" );
			return false;
		}
		return true;
	}

	static string Show( string value ) => string.IsNullOrEmpty( value ) ? "(none)" : value;

	/// <summary>
	/// The editor's own project save (Project.Save, not public), which writes the live config to the
	/// .sbproj; then its package record is brought up to date so the local course list sees the
	/// primary scene without a restart. If the save method is ever gone, the config's own JSON is
	/// written to the project's config path, which is what the editor itself writes.
	/// </summary>
	static void Save( Project project )
	{
		var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
		var save = typeof( Project ).GetMethod( "Save", flags, Type.EmptyTypes );
		if ( save is not null )
		{
			save.Invoke( project, null );
		}
		else
		{
			Log.Warning( "Golf Kit: Project.Save not found in this editor build; writing the config JSON to the project file instead" );
			File.WriteAllText( project.ConfigFilePath, project.Config.ToJson() );
		}

		try
		{
			var sync = typeof( Project ).GetMethod( "SyncWithPackageManager", flags );
			if ( sync is not null ) sync.Invoke( sync.IsStatic ? null : project, sync.GetParameters().Length == 0 ? null : new object[] { project } );
			var mock = typeof( Project ).GetMethod( "UpdateMockPackage", flags );
			if ( mock is not null && mock.GetParameters().Length == 0 ) mock.Invoke( mock.IsStatic ? null : project, null );
		}
		catch ( Exception e )
		{
			Log.Info( $"Golf Kit: the package record of {project.Config?.FullIdent} could not be refreshed ({e.GetBaseException().Message}); it is read again when the editor opens" );
		}
	}

	/// <summary>What the editor holds and what is on disk, after the save, against the editing state; a mismatch is a warning.</summary>
	static void Verify( Project project, string scene )
	{
		var config = project.Config;
		var liveOk = string.Equals( config.Type, EditType, StringComparison.OrdinalIgnoreCase )
			&& string.IsNullOrEmpty( config.GetMetaOrDefault<string>( "ParentPackage", null ) )
			&& string.Equals( config.GetMetaOrDefault<string>( "PrimaryAsset", null ), scene, StringComparison.OrdinalIgnoreCase );

		var fileOk = false;
		var fileType = "(unreadable)";
		try
		{
			var json = File.ReadAllText( project.ConfigFilePath );
			using var doc = System.Text.Json.JsonDocument.Parse( json );
			var root = doc.RootElement;
			fileType = root.TryGetProperty( "Type", out var t ) ? t.GetString() : "(none)";
			string fileParent = null, filePrimary = null;
			if ( root.TryGetProperty( "Metadata", out var meta ) && meta.ValueKind == System.Text.Json.JsonValueKind.Object )
			{
				fileParent = meta.TryGetProperty( "ParentPackage", out var p ) && p.ValueKind == System.Text.Json.JsonValueKind.String ? p.GetString() : null;
				filePrimary = meta.TryGetProperty( "PrimaryAsset", out var a ) && a.ValueKind == System.Text.Json.JsonValueKind.String ? a.GetString() : null;
			}
			fileOk = string.Equals( fileType, EditType, StringComparison.OrdinalIgnoreCase ) && string.IsNullOrEmpty( fileParent ) && string.Equals( filePrimary, scene, StringComparison.OrdinalIgnoreCase );
		}
		catch ( Exception e )
		{
			fileType = $"(unreadable: {e.Message})";
		}

		if ( liveOk && fileOk )
			Log.Info( $"Golf Kit: {config.FullIdent} ready for editing: an {fileType} project, no parent game, primary scene {scene} ({Path.GetFileName( project.ConfigFilePath )} read back OK)" );
		else
			Log.Warning( $"Golf Kit: {config.FullIdent} metadata did not stick (live config {( liveOk ? "OK" : "wrong" )}, {Path.GetFileName( project.ConfigFilePath )} {( fileOk ? "OK" : "wrong" )}, file Type {fileType}). Expected Type {EditType}, no ParentPackage, PrimaryAsset {scene}; set them in the project settings by hand." );
	}

	/// <summary>
	/// Every scene under the project's Assets folder that holds a course: a Golf Course Info or Hole
	/// component, or an object named "Hole N". Paths are relative to Assets with forward slashes.
	/// Dot folders (parked sources) are skipped.
	/// </summary>
	public static System.Collections.Generic.List<string> CourseScenes( Project project )
	{
		var result = new System.Collections.Generic.List<string>();
		if ( !project.HasAssetsPath() ) return result;
		var assets = project.GetAssetsPath();
		if ( string.IsNullOrEmpty( assets ) || !Directory.Exists( assets ) ) return result;

		var golf = new Regex( "\"__type\":\\s*\"(GolfCourseInfo|Hole)\"|\"Name\":\\s*\"Hole\\s+\\d+", RegexOptions.Compiled );
		foreach ( var file in Directory.EnumerateFiles( assets, "*.scene", SearchOption.AllDirectories ) )
		{
			var relative = Path.GetRelativePath( assets, file ).Replace( '\\', '/' );
			if ( relative.Split( '/' ).Any( part => part.StartsWith( '.' ) ) ) continue;
			string text;
			try { text = File.ReadAllText( file ); }
			catch { continue; }
			if ( golf.IsMatch( text ) ) result.Add( relative );
		}
		result.Sort( StringComparer.OrdinalIgnoreCase );
		return result;
	}

	/// <summary>The open scene when it is one of the course scenes, else the first; the choice is logged when there is one to make.</summary>
	static string Choose( System.Collections.Generic.List<string> scenes, string openScene, string ident )
	{
		if ( scenes.Count == 1 ) return scenes[0];
		var open = (openScene ?? "").Replace( '\\', '/' ).TrimStart( '/' );
		var match = scenes.FirstOrDefault( s => string.Equals( s, open, StringComparison.OrdinalIgnoreCase ) );
		var chosen = match ?? scenes[0];
		Log.Info( $"Golf Kit: {ident} has {scenes.Count} course scenes ({string.Join( ", ", scenes )}); {( match is null ? "the first is" : "the open one is" )} the primary scene: {chosen}" );
		return chosen;
	}
}