using Godot;
using Theriapolis.Core.Persistence;
using Theriapolis.Core.Rules.Character;
using Theriapolis.Core.World.Generation;

namespace Theriapolis.GodotHost;

/// <summary>
/// Autoload singleton. Holds the cross-scene state that outlives any
/// single screen: the world seed and (post-worldgen) WorldGenContext,
/// the pending character from the M6 wizard hand-off, and the pending
/// save snapshot from the SaveLoadScreen load hand-off.
///
/// Per port-plan §M7 §4.3: TitleScreen + Wizard + SaveLoadScreen write
/// pending fields; WorldGenProgressScreen + PlayScreen consume them and
/// clear them.
///
/// Registered in <c>project.godot</c> under <c>[autoload]</c>; reachable
/// from any scene via <see cref="From"/>.
/// </summary>
public partial class GameSession : Node
{
    /// <summary>World seed for the next worldgen run. Set by TitleScreen
    /// (new game) or by SaveLoadScreen (from the loaded header).</summary>
    public ulong Seed { get; set; }

    /// <summary>Set by WorldGenProgressScreen on completion; consumed by
    /// PlayScreen during <c>_Ready</c>.</summary>
    public WorldGenContext? Ctx { get; set; }

    /// <summary>Set by the Wizard hand-off (M6 → M7.1). PlayScreen
    /// attaches this to the spawned player actor and clears the field.</summary>
    public Character? PendingCharacter { get; set; }
    public string PendingName { get; set; } = "Wanderer";

    /// <summary>Set by SaveLoadScreen when the player picks a slot.
    /// PlayScreen consumes via <c>ApplyRestoredBody</c> in <c>_Ready</c>.</summary>
    public SaveBody? PendingRestore { get; set; }
    public SaveHeader? PendingHeader { get; set; }

    /// <summary>Convenience accessor — any node can grab the session via
    /// <c>GameSession.From(this)</c> without hard-coding the autoload path.</summary>
    public static GameSession From(Node anyNode)
        => anyNode.GetNode<GameSession>("/root/GameSession");

    /// <summary>Drop the per-run pending fields. Called on quit-to-title
    /// so a fresh "New Character" run doesn't see stale handoff data.</summary>
    public void ClearPending()
    {
        PendingCharacter = null;
        PendingName = "Wanderer";
        PendingRestore = null;
        PendingHeader = null;
    }
}
