Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

44.9 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Statecraft.Sim;

namespace Statecraft.Game.UI
{
    /// <summary>The UI's only door into the simulation (spec section 6). Holds the GameSession, collects this turn's
    /// orders, runs End Turn and tells the screens to refresh. R-TURN-004's instant orders are committed and shown at once;
    /// deferred orders take effect at End Turn, in the order given. Each deferred order replaces an earlier one with the same key (one choice per event, one call-up level, one budget, one appointee
    /// per office, one policy level per policy, one build per hex, one work order per city and role (jobs, and under gdd-0.3 the arms
    /// workshops, #1722), one training order per city and track, one cancel per cohort, one pioneer order per unit).</summary>
    public sealed class SimBridge
    {
        readonly List<Command> deferred = new List<Command>();
        readonly HashSet<int> skipped = new HashSet<int>();
        readonly HashSet<string> endingCardsSeen = new HashSet<string>(StringComparer.Ordinal);

        public GameSession Session { get; private set; }
        public Content Content => Session.Content;
        /// <summary>The state the map and the cards show: the turn's start after its committed orders (R-TURN-004).</summary>
        // An empty order preview is equivalent to the turn start only without automatic go-to work.
        // RunOrders advances standing routes before any player order (spec6.3).
        public GameState State => Session.Committed.Count == 0 && !Session.State.Units.Values.Any(u => u.Order == Movement.GoTo)
            ? Session.State : Session.Now.State;
        /// <summary>The state the turn began with (the saved one): what End turn and the orders' prices start from.</summary>
        public GameState TurnStart => Session.State;
        /// <summary>The movement points each unit has spent this turn.</summary>
        public IReadOnlyDictionary<int, int> Spent => Session.Now.Spent;
        public IReadOnlyList<Command> Queued => deferred;
        /// <summary>The units skipped this turn: Settings' language switch carries them to the rebuilt bridge with Queued.</summary>
        public IReadOnlyCollection<int> Skipped => skipped;
        /// <summary>R-MOVE-010: the units End turn waits for, in ascending id, less those skipped this turn and those going home.</summary>
        public IReadOnlyList<int> NeedsOrders => Movement.NeedsOrders(Content, State, Spent).Where(id => !skipped.Contains(id) && !GoingHome(id)).ToList();
        /// <summary>The orders the last turn ran with (empty until a turn has run, and after a refused batch): what the player
        /// chose, as against what the turn delegated (OutcomePresenter plays a clip only for a choice).</summary>
        public IReadOnlyList<Command> LastBatch { get; private set; } = Array.Empty<Command>();
        /// <summary>The game date when the last turn's orders were given (the date before that turn ran).</summary>
        public DateTime LastBatchDate { get; private set; }
        /// <summary>The step before Session.Last (null until two turns have run), for "change since last turn". The session
        /// keeps it, so a loaded save has it from its replay (#398).</summary>
        public StepResult? BeforeLast => Session.BeforeLast;
        /// <summary>Raised after every change the screens show: an order queued or withdrawn, a turn, a load.</summary>
        public event Action? Changed;
        /// <summary>Raised after End Turn with the orders the simulation refused (possibly none).</summary>
        public event Action<IReadOnlyList<Rejection>>? TurnEnded;
        /// <summary>Raised after a move or unit order is committed, with the Why lines it added (an attack's result).</summary>
        public event Action<IReadOnlyList<Cause>>? Committed;
        /// <summary>The engagements the player has just seen resolve, with the lines of the units they destroyed, raised after
        /// <see cref="Changed"/> has redrawn the map (UnitAttackPresenter plays them, #1867): an attack order's at once, and at
        /// End Turn only the turn's new ones, not the open turn's attack orders, which the turn runs again first. Never on a
        /// load or a refused turn.</summary>
        public event Action<IReadOnlyList<Cause>>? CombatResolved;
        /// <summary>#2202: raised at End Turn with the step's result, after the step and before <see cref="Changed"/> redraws the
        /// map, so the enemy's playback (EnemyTurnPlayback) holds the tokens where they stood. Only on a turn the simulation ran:
        /// never on a refused turn, a load or a New Game. Its Why lines start with the open turn's own (the player's orders).</summary>
        public event Action<StepResult>? Stepped;
        /// <summary>Raised when Queue refuses an order, with the player-facing reason.</summary>
        public event Action<string>? Refused;
        /// <summary>A validated order was refused specifically for Attention; presentation-only advice signal.</summary>
        public event Action? RefusedForAttention;
        /// <summary>Raised when the player has answered the last objective card of the turn that ended the game
        /// (<see cref="SeeEndingCard"/>): the end screen shows then (#2536).</summary>
        public event Action? EndingCardsSeen;

        /// <summary>The cards of the turn that ended the game the player has answered (#2536): Settings' language switch carries
        /// them to the rebuilt bridge, as it carries Skipped.</summary>
        public IReadOnlyCollection<string> EndingCardsAnswered => endingCardsSeen;
        /// <summary>True while a card of the turn that ended the game waits: the objective cards that turn raised (R-OBJ-003,
        /// R-LOOP-004; the owner's choice "Show the card (Recommended)", 4 November 2026) show before the end screen.</summary>
        public bool EndingCardWaiting => State.PendingEvents.Any(id => IsEndingCard(id) && !endingCardsSeen.Contains(id));
        /// <summary>Whether the waiting event is a card of the turn that ended the game (EventSystem.EndingCard).</summary>
        public bool IsEndingCard(string id) => EventSystem.EndingCard(State, Content.Events.First(e => e.Id == id));
        /// <summary>Whether the player has answered this card of the turn that ended the game.</summary>
        public bool EndingCardSeen(string id) => endingCardsSeen.Contains(id);

        /// <summary>Answers a card of the turn that ended the game (#2536). An ended game runs no more turns, so the answer is
        /// no order: the card is marked seen, and once none waits <see cref="EndingCardsSeen"/> is raised. An objective's card
        /// has one option and its score is already counted (R-OBJ-003), so nothing in the state changes. Does nothing for
        /// any other event, or one that is not waiting.</summary>
        public void SeeEndingCard(string id)
        {
            if (!State.PendingEvents.Contains(id) || !IsEndingCard(id) || !endingCardsSeen.Add(id)) return;
            Notify(Changed, nameof(Changed));
            if (!EndingCardWaiting) Notify(EndingCardsSeen, nameof(EndingCardsSeen));
        }

        readonly UiText text;
        readonly Func<GameSession, IReadOnlyList<Command>, StepResult> step;

        /// <param name="step">How a turn is run; the default is Session.EndTurn. Tests pass a stepper that throws, to prove
        /// that a batch the simulation refuses outright cannot soft-lock the game.</param>
        public SimBridge(GameSession session, UiText text, Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null)
        {
            this.step = step ?? ((s, cmds) => s.EndTurn(cmds));
            Session = session ?? throw new ArgumentNullException(nameof(session));
            this.text = text ?? throw new ArgumentNullException(nameof(text));
        }

        /// <summary>The order's slot in the queue: a later order with the same key replaces the earlier one. Internal for
        /// SimBridgeGuardTests, which checks that every command type is listed here or is one per turn by design.</summary>
        internal static string Key(Command c) => c switch
        {
            BuyArms _ => Pools.BuyArmsKind,
            ChooseEventOption e => "event:" + e.EventId,
            SetPolicy p => "policy:" + p.Policy,
            Appoint a => "appoint:" + a.Office,
            MapAction m => FormattableString.Invariant($"map:{m.Q},{m.R}"),
            AssignWorkers w => "work:" + w.City + ":" + w.Role,   // #1722: a city's jobs and workshop orders keep their own slots
            Train t => "train:" + t.City + ":" + t.Track,
            CancelTraining x => FormattableString.Invariant($"untrain:{x.Cohort}"),
            ReturnCraftsmen r => "retcraft:" + r.City,
            ReassignCraftsmen r => "regcraft:" + r.City,
            ReassignPioneers r => "regpioneer:" + r.City + ":" + r.Track,
            Reinforce x => FormattableString.Invariant($"reinforce:{x.Unit}"),
            PioneerWork w => FormattableString.Invariant($"unit:{w.Unit}"),
            StopWork w => FormattableString.Invariant($"unit:{w.Unit}"),
            UnitOrder o when o.Order == Demobilization.SendHome => FormattableString.Invariant($"order:{o.Unit}"),
            StartProject p => FormattableString.Invariant($"project:{p.Q},{p.R}"),
            CancelProject x => FormattableString.Invariant($"unproject:{x.Project}"),
            ResolveCapture r => "capture:" + r.Settlement,
            EndOccupation e => "endocc:" + e.Settlement,
            _ => c.Kind,
        };

        /// <summary>The order's Attention price, or null when the ruleset has no Attention: what <see cref="Queue"/> charges and the card shows.</summary>
        public double? Price(Command c) => Content.UsesAttention ? AttentionSystem.Price(Content, TurnStart, c) : null;

        /// <summary>Whether the Attention left pays for the order (a queued order with its key is refunded first): the one
        /// check <see cref="Queue"/> refuses on, so the event card (#1034) and a refusal can never disagree.</summary>
        public bool CanPay(Command c) => !Content.UsesAttention || Price(c)!.Value <= LeftFor(c) + 1e-9;

        double LeftFor(Command c) { var old = QueuedLike(c); return AttentionLeft!.Value + (old != null ? Price(old)!.Value : 0); }

        /// <summary>Who End Turn hands the event to with the orders queued now (Simulation.DelegatedTo), or null for the
        /// cabinet: an appointment queued this turn is in office by then (#1034).</summary>
        public Person? DelegatedTo(GameEvent e) => Simulation.DelegatedTo(Content, TurnStart, All, e.Id);

        /// <summary>The vacant seats the player can fill, less those an appointment queued now fills (Cabinet.Vacancies): the
        /// side menu's Cabinet badge (#1109).</summary>
        public IReadOnlyList<Office> Vacancies => Cabinet.Vacancies(Content, TurnStart, All);

        /// <summary>Whether the Budget screen's <paramref name="draft"/> is not what End turn will apply and Submit can apply it
        /// (EconomySystem.Unsubmitted): the side menu's Budget badge (#1109).</summary>
        public bool BudgetUnsubmitted(IReadOnlyDictionary<string, double> draft) => EconomySystem.Unsubmitted(Content, TurnStart, draft, deferred);

        /// <summary>Attention left after queued orders, or null when the ruleset has no Attention.</summary>
        public double? AttentionLeft => Content.UsesAttention ? AttentionSystem.Left(Content, TurnStart, All) : null;

        /// <summary>The queued order with this key, or null.</summary>
        public Command? QueuedLike(Command c) => deferred.FirstOrDefault(q => Key(q) == Key(c));

        IReadOnlyList<Command> All => Session.Committed.Concat(deferred).ToList();

        /// <summary>Whether Send home is queued for the unit: it then takes no other order (spec 3.2), deferred or instant.</summary>
        public bool GoingHome(int unit) => deferred.Any(x => IsSendHome(x) && UnitOf(x) == unit);

        static bool IsSendHome(Command c) => c is UnitOrder o && o.Order == Demobilization.SendHome;

        /// <summary>The unit an order is given to (a move, a unit order, a reinforcement, pioneer work or its stop), or null.</summary>
        static int? UnitOf(Command c) => c switch
        {
            Move m => m.Unit,
            UnitOrder o => o.Unit,
            Reinforce x => x.Unit,
            PioneerWork w => w.Unit,
            StopWork w => w.Unit,
            _ => (int?)null,
        };

        /// <summary>Skips the unit for this turn: not an order, not saved, nothing in the game changes (spec 7.2).</summary>
        public void Skip(int unit) { if (skipped.Add(unit)) Notify(Changed, nameof(Changed)); }
        public bool IsSkipped(int unit) => skipped.Contains(unit);

        /// <summary>Null if the id is known, else the player-facing reason. The player sees only the kind of thing (#622: a
        /// content id means nothing to them), in the UI's language: the string order.kind.&lt;kind&gt; (#595). The id goes to
        /// the log, for a bug report.</summary>
        string? Unknown(string kind, string? id, IEnumerable<string> known)
        {
            if (!string.IsNullOrEmpty(id) && known.Contains(id)) return null;
            UnityEngine.Debug.Log($"Order refused: unknown {kind.Replace('_', ' ')} '{id}'");
            return text.Format("order.unknown", text["order.kind." + kind]);
        }

        /// <summary>Checks every id an order carries against the content, so End Turn can never be handed an id the
        /// simulation would throw on. Returns the player-facing reason, or null.</summary>
        string? Validate(Command c)
        {
            switch (c)
            {
                case SetPolicy p: return Unknown("policy", p.Policy, Content.Policies.Select(x => x.Id));
                case Appoint a: return Unknown("office", a.Office, Content.Offices.Select(x => x.Id)) ?? Unknown("person", a.Person, Content.People.Select(x => x.Id));
                case ChooseEventOption e:
                    var ev = Content.Events.FirstOrDefault(x => x.Id == e.EventId);
                    return ev == null ? Unknown("event", e.EventId, new string[0]) : Unknown("option", e.OptionId, ev.Options.Select(x => x.Id));
                case MapAction m: return Unknown("action", m.Action, MapActions.Actions);
                case AllocateBudget b:
                    if (b.Shares == null) return text["order.invalid"];
                    foreach (var k in b.Shares.Keys) { var r = Unknown("budget_line", k, Content.Rules.BudgetStart.Keys); if (r != null) return r; }
                    return null;
                case SetMobilization _: case SecurityOrder _: return null;
                // The GDD orders (#380): ids only. Roles, counts and limits are the sim's, which refuses them with its own
                // reason and refunds the Attention. The legacy content has no cities, so it queues none of these.
                case AssignWorkers w: return Unknown("city", w.City, Content.Cities.Select(x => x.Id));
                case Train t:
                    return Unknown("city", t.City, Content.Cities.Select(x => x.Id))
                        ?? Unknown("training", t.Track, Content.UnitTypes.Where(x => !string.IsNullOrEmpty(x.Facility)).Select(x => x.Id));
                // Return and reassignment (#1511): the city id only; the sim refuses a count, a track or a busy civilian with its own reason.
                case ReturnCraftsmen r: return Unknown("city", r.City, Content.Cities.Select(x => x.Id));
                case ReassignCraftsmen r: return Unknown("city", r.City, Content.Cities.Select(x => x.Id));
                case ReassignPioneers r: return Unknown("city", r.City, Content.Cities.Select(x => x.Id));
                case CancelTraining x:
                    return Unknown("cohort", x.Cohort.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Cohorts.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));
                // Replacements (#1510): ids only; the sim refuses a full, enemy or misplaced unit and the training checks itself.
                case Reinforce x:
                    return Unknown("unit", x.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)))
                        ?? Unknown("city", x.City, Content.Cities.Select(k => k.Id));
                // Pioneer work (#378, camp/field/swamp #1124, corridors #786): ids only; the sim refuses a busy unit, a built site or segment, a kind
                // mismatch or a short Treasury with its own reason. A corridor action names "corridor:N", N from 1.
                case PioneerWork w:
                    return Unknown("unit", w.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)))
                        ?? Unknown("pioneer_work", w.Action, new[] { Projects.BuildYishuv, Projects.BuildCamp, Projects.PlowFields, Projects.DrySwamp, Corridors.BuildRoad, Corridors.BuildRail })
                        ?? (Corridors.IsAction(w.Action)
                            ? Unknown("corridor_segment", w.Site, Content.Corridors.SelectMany(x => Enumerable.Range(1, x.Segments.Count).Select(n => x.Id + ":" + n.ToString(System.Globalization.CultureInfo.InvariantCulture))))
                            : Unknown("site", w.Site, Content.Sites.Select(x => x.Id)));
                case StopWork w: return Unknown("unit", w.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));
                // Movement (#744): the unit id only; the sim refuses an unreachable, full or forbidden hex with its own reason.
                case Move m: return Unknown("unit", m.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));

                // Standing orders (#746): the unit id only; the sim refuses an unknown order, a halutz or an enemy unit itself.
                case UnitOrder o: return Unknown("unit", o.Unit.ToString(System.Globalization.CultureInfo.InvariantCulture), State.Units.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));
                // City projects (#735): ids only; the sim refuses a far or taken hex, the policy gate and the turn's limit itself.
                case StartProject p:
                    return Unknown("city_project", p.ProjectKind, Content.ProjectKinds.Select(x => x.Id)) ?? Unknown("city", p.City, Content.Cities.Select(x => x.Id));
                case CancelProject x:
                    return Unknown("city_project", x.Project.ToString(System.Globalization.CultureInfo.InvariantCulture), State.CityProjects.Keys.Select(k => k.ToString(System.Globalization.CultureInfo.InvariantCulture)));
                // Buying Arms (#781): no ids; the sim refuses the count, stock capacity and debt ceiling itself.
                case BuyArms _: return null;
                // Answering a capture (#797): the sim refuses a place not awaiting the choice, or an outcome not built yet, with
                // its own reason and never throws on the id. The capture dialog is PR 10.
                case ResolveCapture _: return null;
                // Answering the end of an occupation (#799): the sim refuses a place not awaiting the end with its own reason.
                case EndOccupation _: return null;
                // Converting dollars (#813, R-MONEY-004): no ids; the sim refuses the amount itself (EconomySystem.DollarsRefusal).
                case ConvertDollars _: return null;
                default: return text["order.invalid"];
            }
        }

        /// <summary>The sim's English refusals that have a UI string: Orders.Check's (#2045) and the Arms-purchase refusals
        /// (#2198, #2590).
        /// Keyed on the English, so the same words from another check (Movement, Combat, Training, Demobilization give "That
        /// unit is not yours", "There is no such unit" too) read in the UI's language as well.</summary>
        static readonly Dictionary<string, string> ReasonKeys = new Dictionary<string, string>
        {
            // #813 (R-MONEY-004): the dollar conversion's refusals.
            [EconomySystem.RefusedDollarsMinimum] = "dollars.refused_minimum",
            [EconomySystem.RefusedDollarsNotAtWar] = "dollars.refused_not_at_war",
            [EconomySystem.RefusedDollarsMonthly] = "dollars.refused_monthly",
            [EconomySystem.RefusedDollarsTotal] = "dollars.refused_total",
            [EconomySystem.RefusedDollarsReserves] = "dollars.refused_reserves",
            [Orders.RefusedUnknownOrder] = "unit.order_refused.unknown_order",
            [Orders.RefusedNoUnit] = "unit.order_refused.no_unit",
            [Orders.RefusedNotMilitary] = "unit.order_refused.not_military",
            [Orders.RefusedNotYours] = "unit.order_refused.not_yours",
            [Orders.RefusedArtilleryHold] = "unit.order_refused.artillery_hold",
            [Orders.RefusedAlready] = "unit.order_refused.already",
            [Combat.RefusedNoHex] = "unit.attack_refused.no_hex",
            [Combat.RefusedTruce] = "unit.attack_refused.truce",
            [Combat.RefusedOutOfRange] = "unit.attack_refused.out_of_range",
            [Combat.RefusedNotAdjacent] = "unit.attack_refused.not_adjacent",
            [Combat.RefusedNoEnemy] = "unit.attack_refused.no_enemy",
            [Combat.RefusedNoPoints] = "unit.attack_refused.no_points",
            [Training.RefusedNoCity] = "unit.reinforce_refused.no_city",
            [Training.RefusedNoTraining] = "unit.reinforce_refused.no_training",
            [Training.RefusedCount] = "unit.reinforce_refused.count",
            [Pools.RefusedDebtCeiling] = "arms.refused_debt_ceiling",
            [Pools.RefusedStockCapacity] = "arms.refused_stock_capacity",
            [Orders.RefusedCardOrder] = "unit.order_refused.card_order",   // R-ENEMY-005: an operation card's refused go-to
            [Orders.RefusedLastGarrison] = "unit.order_refused.last_garrison",   // R-CTRL-013: a card's go-to held back
            // #2707: the move's and the go-to's refusals, Arms bought below one, the call-up's range and Send home's.
            [Movement.RefusedNoHex] = "unit.move_refused.no_hex",
            [Movement.RefusedCannotMove] = "unit.move_refused.cannot_move",
            [Movement.RefusedAlreadyThere] = "unit.move_refused.already_there",
            [Movement.RefusedOffLand] = "unit.move_refused.off_land",
            [Movement.RefusedEnemyHex] = "unit.move_refused.enemy_hex",
            [Movement.RefusedClosed] = "unit.move_refused.closed",
            [Movement.RefusedNoRoute] = "unit.move_refused.no_route",
            [Movement.RefusedOutOfReach] = "unit.move_refused.out_of_reach",
            [Pools.RefusedCount] = "arms.refused_count",
            [SecuritySystem.RefusedMobilization] = "defence.refused_mobilization",
            [Demobilization.RefusedNoArmistice] = "unit.send_home_refused.no_armistice",
            // #2707, batch 2: the workers, craftsmen and pioneers orders, pioneer work, a city project cancel and a training cancel.
            [Cities.RefusedNoRole] = "city.assign_refused.no_role",
            [Cities.RefusedNegativeWorkers] = "city.assign_refused.negative",
            [Qualification.RefusedReturnCount] = "city.qualification_refused.return_count",
            [Qualification.RefusedReassignCount] = "city.qualification_refused.reassign_count",
            [Qualification.RefusedNoQualification] = "city.qualification_refused.no_qualification",
            [Qualification.RefusedNotPioneer] = "unit.order_refused.not_pioneer",
            [Qualification.RefusedPioneerBusy] = "unit.order_refused.pioneer_busy",
            [Training.RefusedNoCohort] = "training.cancel_refused.no_group",
            [Projects.RefusedNotHalutz] = "site.refused.not_halutz",
            [Projects.RefusedNoWork] = "site.refused.no_work",
            [Projects.RefusedNoSite] = "site.refused.no_site",
            [Projects.RefusedNotBuilding] = "site.refused.not_building",
            [Projects.RefusedNoCityProject] = "city.project_reason.no_project",
            [Corridors.RefusedNoSegment] = "corridor.refused.no_segment",
            [EconomySystem.RefusedBudgetRequired] = "budget.refused.required",
            [EconomySystem.RefusedBudgetMinistry] = "budget.refused.ministry",
            [EconomySystem.RefusedBudgetFinite] = "budget.refused.finite",
            [EconomySystem.RefusedBudgetEveryMinistry] = "budget.refused.every_ministry",
            [EconomySystem.RefusedBudgetSum] = "budget.refused.sum",
            [EconomySystem.RefusedBudgetNegative] = "budget.refused.negative",
            [Orders.RefusedNamesNoHex] = "unit.order_refused.names_no_hex",
            // #2707, batch 3 (the owner's option (b)): a capture answer the end of turn refuses reads as the capture dialog's
            // reviewed capture.refusal.* line. "Deport is not built yet" and the two "not awaiting" answers have no reviewed line
            // that fits (capture.refusal.not_awaiting names the place, these do not), so they stay the sim's English.
            [SettlementControl.RefusedNoOneToDeport] = "capture.refusal.no_one_to_deport",
            [SettlementControl.RefusedUnknownOutcome] = "capture.refusal.unknown_outcome",
            // R-ENEMY-007 (#2543): an operation whose units are not in place, or whose front's armistice comes first or is signed.
            [EventSystem.RefusedOperationUnitsNotInPlace] = "event.operation_refused",
            [EventSystem.RefusedOperationArmisticeFirst] = "event.operation_refused_armistice_first",
            [EventSystem.RefusedOperationArmisticeSigned] = "event.operation_refused_armistice_signed",
            // #2707 batch 4: an appointment End turn refuses, as the Cabinet screen words it (CabinetPresenter.ReasonText)
            [Cabinet.RefusedOfficeUnknown] = "cabinet.reason.office_unknown",
            [Cabinet.RefusedPrimeMinister] = "cabinet.reason.prime_minister",
            [Cabinet.RefusedPresident] = "cabinet.reason.president",
            [Cabinet.RefusedPersonUnknown] = "cabinet.reason.person_unknown",
            [Cabinet.RefusedNoGovernment] = "cabinet.reason.no_government",
            // #3020: the refusals only a Historical ledger game gives (#1725 PR 7), with no values. Their constants stay internal
            // (#2964 Q4), so they are read by name from PopulationLedger.Refusals.
            [PopulationLedger.Refusals["Training.LedgerRefusedCraftsman"]] = "unit.reinforce_refused.ledger_craftsman",
            [PopulationLedger.Refusals["Qualification.LedgerRefusedCraftsmen"]] = "city.qualification_refused.ledger_craftsmen",
        };

        /// <summary>The sim's refusals that carry values (#2072: Combat.Check's Arms, Training.Reinforce's unit, settlement,
        /// course and counts): each format constant, read back from its English with its values in order, and its key.</summary>
        static readonly (Regex pattern, string key)[] ReasonFormats = new (string format, string key)[]
        {
            (Combat.RefusedArms, "unit.attack_refused.arms"),
            (Training.RefusedNotInCity, "unit.reinforce_refused.not_in_city"),
            (Training.RefusedNoCourse, "unit.reinforce_refused.no_course"),
            (Training.RefusedNoLosses, "unit.reinforce_refused.no_losses"),
            (Training.RefusedRoomOne, "unit.reinforce_refused.room_one"),
            (Training.RefusedRoomMany, "unit.reinforce_refused.room_many"),
            (Training.RefusedNoCamp, "unit.reinforce_refused.no_camp"),
            (Training.RefusedNoIndustry, "unit.reinforce_refused.no_industry"),
            (Training.RefusedNoHakhshara, "unit.reinforce_refused.no_hakhshara"),
            (Training.RefusedIdle, "unit.reinforce_refused.idle"),
            (Training.RefusedArms, "unit.reinforce_refused.arms"),
            // R-ARMS-005 (#1722): a workshop staffing order's refusals, the panel's and the end of turn's. RefusedPeople is
            // also the jobs order's refusal past its civilians and craftsmen less the staffed workshops (Cities.Assign).
            (Workshops.RefusedBuiltOne, "workshop.refused_built_one"),
            (Workshops.RefusedBuilt, "workshop.refused_built"),
            (Workshops.RefusedPeople, "workshop.refused_people"),
            (Workshops.RefusedPeopleNoJob, "workshop.refused_people_no_job"),
            // R-CITY-011 (#2477): a builder order past the city's projects being built (Projects.AssignBuilders).
            (Projects.RefusedBeingBuiltOne, "builder.refused_being_built_one"),
            (Projects.RefusedBeingBuilt, "builder.refused_being_built"),
            // R-PROJ-001 under gdd-0.3 (#1700 slice B): a second city project start in one city in one turn.
            (Projects.RefusedCityCap, "city.project_reason.city_cap"),
            // #2707: a hex at the stack limit, an instant order short of Attention (the queue's own line), a housing repair off its city.
            (Movement.RefusedFull, "unit.move_refused.full"),
            (AttentionSystem.RefusedAttention, "order.no_attention"),
            (Projects.RefusedRepairCityHex, "city.project_reason.repair_city_hex"),
            // #2707, batch 3 (option (b)): the capture and end-of-occupation answers that need a unit or a free hex, and an
            // annexed place that is already a city, as the capture dialog's reviewed lines; {0} is the place.
            (SettlementControl.RefusedOccupyNeedsUnit, "capture.refusal.needs_unit"),
            (SettlementControl.RefusedAnnexNeedsUnit, "capture.refusal.needs_unit"),
            (SettlementControl.RefusedWithdrawNeedsUnit, "capture.refusal.needs_unit"),
            (SettlementControl.RefusedNoFreeHex, "capture.refusal.no_free_hex"),
            (Cities.RefusedAlreadyCity, "capture.refusal.already_city"),
            // #2707 batch 4: the appointment refusals with a name or a date in them (ReasonValue words each in Hebrew)
            (Cabinet.RefusedHistoricalOffice, "cabinet.reason.historical_office"),
            (Cabinet.RefusedAbolished, "cabinet.reason.abolished"),
            (Cabinet.RefusedNotEstablished, "cabinet.reason.not_established"),
            (Cabinet.RefusedSeveralHolders, "cabinet.reason.several_holders"),
            (Cabinet.RefusedDied, "cabinet.reason.died"),
            (Cabinet.RefusedIsPresident, "cabinet.reason.is_president"),
            (Cabinet.RefusedIsChiefOfStaff, "cabinet.reason.is_chief_of_staff"),
            (Cabinet.RefusedAlreadyHolds, "cabinet.reason.already_holds"),
            (Cabinet.RefusedNotCareerOfficer, "cabinet.reason.not_career_officer"),
            (Cabinet.RefusedPartyNotCoalition, "cabinet.reason.party_not_coalition"),
            // #3020: the refusals only a Historical ledger game gives (#1725 PR 7) that carry values: Train's and Reinforce's
            // (LedgerRefusedStrength is Send home's too), a workshop staffing order's and a pioneer reassignment's.
            (PopulationLedger.Refusals["Training.LedgerRefusedCampFull"], "unit.reinforce_refused.ledger_camp_full"),
            (PopulationLedger.Refusals["Training.LedgerRefusedStrength"], "unit.reinforce_refused.ledger_strength"),
            (PopulationLedger.Refusals["Training.LedgerRefusedCarried"], "unit.reinforce_refused.ledger_carried"),
            (PopulationLedger.Refusals["Training.LedgerRefusedHalutzTrade"], "unit.reinforce_refused.ledger_halutz_trade"),
            (PopulationLedger.Refusals["Workshops.LedgerRefusedFree"], "workshop.refused_ledger_free"),
            (PopulationLedger.Refusals["Workshops.LedgerRefusedBuilders"], "workshop.refused_ledger_builders"),
            (PopulationLedger.Refusals["Qualification.LedgerRefusedFreePioneers"], "city.qualification_refused.ledger_free_pioneers"),
        }.Select(x => (new Regex("^" + string.Join("(.+?)", Regex.Split(x.format, @"\{\d+(?::[^}]*)?\}").Select(Regex.Escape)) + "$"), x.key)).ToArray();

        /// <summary>A sim refusal in the UI's language where it has a string (<see cref="ReasonKeys"/>, <see cref="ReasonFormats"/>),
        /// else the sim's English as given. The queue's refusals, the unit card's (InfoPanelPresenter) and the end of turn's
        /// (ToastPresenter) go through it. With <paramref name="c"/> a value that is a settlement's name reads as the UI names the
        /// town (its Hebrew name from <paramref name="townsHe"/> in Hebrew), a course's English as why.cause.course.* and a money
        /// amount in the content's format; in Hebrew a cabinet refusal's person, party and date too, and its office with
        /// <paramref name="date"/> (the turn's, for the title's days).</summary>
        public static string ReasonText(UiText text, string reason, Content? c = null, IReadOnlyDictionary<string, string>? townsHe = null,
                                        DateTime? date = null)
        {
            if (ReasonKeys.TryGetValue(reason, out var key))
            {
                if (reason != EconomySystem.RefusedDollarsMinimum) return text[key];
                return c == null ? reason : text.Format(key, PlayerText.Money(c, "fx_reserves", EconomySystem.DollarsMinimum));
            }
            foreach (var (pattern, format) in ReasonFormats)
                if (pattern.Match(reason) is { Success: true } m)
                {
                    // An office's Hebrew title takes its holder's form: in "{0} already holds the office of {1}" that is {0}.
                    var holder = format == "cabinet.reason.already_holds" ? c?.People.FirstOrDefault(p => p.Name == m.Groups[1].Value) : null;
                    return text.Format(format, CountNoun(text, format,
                        m.Groups.Cast<Group>().Skip(1).Select(v => (object)ReasonValue(text, v.Value, c, townsHe, date, holder)).ToArray()));
                }
            return reason;
        }

        /// <summary>#2530: an English count names its noun in the singular for 1 ("1 civilian without work"); the Hebrew
        /// strings name the number in a label, grammatical for any count. Any other count reads as the sim's own English.</summary>
        static object[] CountNoun(UiText text, string key, object[] values)
        {
            if (text["ui.lang"] == UiLanguage.Hebrew || values.Length != 2 || values[1] is not string n) return values;
            values[1] = key switch
            {
                "unit.reinforce_refused.idle" => n == "1" ? "1 civilian without work" : n + " civilians without work",
                "workshop.refused_people" => n == "1" ? "1 civilian or craftsman" : n + " civilians and craftsmen",
                "workshop.refused_people_no_job" => n == "1" ? "1 civilian or craftsman without a job" : n + " civilians and craftsmen without a job",
                "workshop.refused_ledger_free" => n == "1" ? "1 free civilian without an assignment" : n + " free civilians without an assignment",   // #3020
                "city.qualification_refused.ledger_free_pioneers" => n == "1" ? "1 free pioneer without work" : n + " free pioneers without work",   // #3020
                _ => values[1],
            };
            return values;
        }

        static string ReasonValue(UiText text, string value, Content? c, IReadOnlyDictionary<string, string>? townsHe,
                                  DateTime? date = null, Person? holder = null)
        {
            if (c == null) return value;
            var town = c.SettlementNames.FirstOrDefault(n => n.Value == value).Key;
            if (town != null)
                return text["ui.lang"] == UiLanguage.Hebrew && townsHe != null && townsHe.TryGetValue(town, out var he) && !string.IsNullOrWhiteSpace(he) ? he : value;
            var course = c.UnitTypes.FirstOrDefault(t => t.Facility != "" && Training.Course(t) == value);
            if (course != null) return text["why.cause.course." + Training.CourseId(course)];
            // #2707 batch 4: a cabinet refusal's person, party, office and date, in Hebrew as CabinetPresenter.ReasonText gives
            // them. An office's Hebrew title depends on the day (TitleHeOn), so with no date it keeps the English, as the UI
            // does outside a title's days. English keeps the sim's own words.
            if (text["ui.lang"] != UiLanguage.Hebrew) return value;
            if (c.People.FirstOrDefault(p => p.Name == value) is Person person) return ContentNames.Of(text, person);
            if (c.Parties.FirstOrDefault(p => p.Name == value) is Party party) return ContentNames.Of(text, party);
            if (date != null && c.Offices.FirstOrDefault(o => o.Title == value) is Office office) return ContentNames.Of(text, office, holder, date.Value);
            return DateTime.TryParseExact(value, "d MMMM yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day)
                ? Statecraft.Game.Map.Control1948.DateText(day, k => text[k]) : value;
        }

        /// <summary>Each settlement's Hebrew name (name_he), by id, for <see cref="Refuse"/>'s Hebrew (#2072): GameRoot sets it, as
        /// it sets the card's and the toast's.</summary>
        public IReadOnlyDictionary<string, string>? TownNamesHe { get; set; }

        string? Refuse(string reason) { reason = ReasonText(text, reason, Content, TownNamesHe); Refused?.Invoke(reason); return reason; }

        static IReadOnlyList<Cause> Engagements(IEnumerable<Cause> why) => why.Where(x => x.Key == WhyKeys.Engagement || x.Key == WhyKeys.Destroyed).ToList();

        // Under ?turnlog, during End turn, each handler is timed (TurnProbe, #2905); otherwise Start is 0 and Handler returns.
        static void Notify(Action? handlers, string evt)
        {
            if (handlers == null) return;
            foreach (Action handler in handlers.GetInvocationList())
            {
                var t = Boot.TurnProbe.Start();
                try { handler(); }
                catch (Exception e) { UnityEngine.Debug.LogException(e); }
                Boot.TurnProbe.Handler(evt, handler, t);
            }
        }

        static void Notify<T>(Action<T>? handlers, T value, string evt)
        {
            if (handlers == null) return;
            foreach (Action<T> handler in handlers.GetInvocationList())
            {
                var t = Boot.TurnProbe.Start();
                try { handler(value); }
                catch (Exception e) { UnityEngine.Debug.LogException(e); }
                Boot.TurnProbe.Handler(evt, handler, t);
            }
        }

        /// <summary>Queues an order (replacing one with the same key). Returns null, or why it was refused here: an id
        /// the content does not have, the game is over, or the order costs more attention than is left. A refusal is
        /// also raised as <see cref="Refused"/>.</summary>
        public string? Queue(Command c)
        {
            if (c == null) throw new ArgumentNullException(nameof(c));
            var bad = Validate(c);
            if (bad != null) return Refuse(bad);
            if (State.GameOver != null) return Refuse(text["order.game_over"]);
            if (UnitOf(c) is int unit && !IsSendHome(c) && GoingHome(unit)) return Refuse(text["order.going_home"]);
            if (Simulation.IsInstant(c))
            {
                var before = Session.Now.Why.Count;
                var refused = Session.Commit(c);
                if (refused != null) return Refuse(refused);
                WithdrawUnmetOperations();
                Notify(Changed, nameof(Changed));
                var added = Session.Now.Why.Skip(before).ToList();
                Notify(Committed, added, nameof(Committed));
                Notify(CombatResolved, Engagements(added), nameof(CombatResolved));
                return null;
            }
            if (c is AllocateBudget ab) c = new AllocateBudget(new Dictionary<string, double>(ab.Shares));   // a snapshot: later edits to the caller's dictionary must not change the order
            if (Content.UsesAttention && !CanPay(c))
            {
                Notify(RefusedForAttention, nameof(RefusedForAttention));   // presentation only: a failing listener never changes the refusal
                return Refuse(text.Format("order.no_attention", Price(c)!.Value, LeftFor(c)));
            }
            // Send home takes the unit's place in the queue: an order queued for it earlier (a reinforcement) is withdrawn, and
            // its Attention refunded, so End turn never acts on a unit it sends home in the same turn. Withdrawing only refunds,
            // so the check above still holds.
            if (IsSendHome(c)) deferred.RemoveAll(x => UnitOf(x) == UnitOf(c) && Key(x) != Key(c));
            var old = QueuedLike(c);
            if (old != null) deferred[deferred.IndexOf(old)] = c; else deferred.Add(c);
            Notify(Changed, nameof(Changed));
            return null;
        }

        /// <summary>R-ENEMY-007 (owner, 7 November 2026: "Re-show the card (Recommended)"): after an instant order, a queued
        /// operation choice whose required units are no longer in place in the state the card shows (<see cref="State"/>) is
        /// withdrawn, which refunds its Attention, so its card shows again with the missing unit's "Move ... before" line
        /// instead of End Turn refusing the choice and handing the card to its minister. The caller notifies.</summary>
        void WithdrawUnmetOperations()
        {
            foreach (var q in deferred.OfType<ChooseEventOption>().ToList())
            {
                var option = Content.Events.FirstOrDefault(e => e.Id == q.EventId)?.Options.FirstOrDefault(o => o.Id == q.OptionId);
                if (option != null && option.RequiresUnitRegions.Count != 0 && !EventSystem.OperationStatus(Content, State, option).Met)
                    deferred.Remove(q);
            }
        }

        public void Withdraw(Command c)
        {
            if (deferred.Remove(c)) Notify(Changed, nameof(Changed));
        }

        /// <summary>Runs the turn with the committed then deferred orders, clears the deferred queue, and notifies. If the
        /// simulation refuses the batch outright, committed orders stay in the open turn and deferred orders are cleared;
        /// the reason is raised through TurnEnded like any refusal.</summary>
        public StepResult EndTurn()
        {
            StepResult r;
            // The turn runs the open turn's orders first, as the open turn did (Simulation.Step and Preview share RunOrders),
            // so its first causes are the open turn's, already played when each order was given (#1867).
            int replayed = Session.Now.Why.Count;
            var batch = Session.Committed.Concat(deferred).ToList();
            var date = TurnStart.Date;
            Boot.TurnProbe.BeginTurn(TurnStart.Turn, date);   // ?turnlog (#2905): this call's sim step and handlers, one line
            var stepFrom = Boot.TurnProbe.Start();
            try   // the finally closes the probed turn on every path, an exception included (#3057); off, it does nothing
            {
                try { r = step(Session, deferred.ToList()); }   // a snapshot: the queue is cleared below
                catch (Exception e)   // any exception (M3 final review M7): never leave a queue that fails on every End Turn
                {
                    Boot.TurnProbe.Step(stepFrom);   // the failed step is timed too (#3057)
                    // A refusal (ArgumentException) is a clear warning, anything else the full exception: both leave a trace.
                    if (e is ArgumentException) UnityEngine.Debug.LogWarning("End Turn refused: " + e.Message);
                    else UnityEngine.Debug.LogException(e);
                    deferred.Clear(); skipped.Clear();
                    LastBatch = Array.Empty<Command>(); LastBatchDate = default(DateTime);
                    var reason = text["order.failed"];   // the message stays in the log above, not on screen (#622)
                    var failed = new StepResult(State, new Cause[0], batch.Select(x => new Rejection(x, reason)).ToList());
                    Notify(Changed, nameof(Changed));
                    Notify(TurnEnded, failed.Rejected, nameof(TurnEnded));
                    return failed;
                }
                Boot.TurnProbe.Step(stepFrom);
                LastBatch = batch; LastBatchDate = date;
                deferred.Clear(); skipped.Clear();
                Notify(Stepped, r, nameof(Stepped));
                Notify(Changed, nameof(Changed));
                Notify(CombatResolved, Engagements(r.Why.Skip(replayed)), nameof(CombatResolved));
                Notify(TurnEnded, r.Rejected, nameof(TurnEnded));
                return r;
            }
            finally { Boot.TurnProbe.EndTurn(UnityEngine.Debug.Log); }
        }

        /// <summary>Switches to another session (a loaded save), dropping queued orders and the last batch's metadata.</summary>
        public void Replace(GameSession session)
        {
            Session = session ?? throw new ArgumentNullException(nameof(session));
            LastBatch = Array.Empty<Command>(); LastBatchDate = default(DateTime);
            deferred.Clear(); skipped.Clear(); endingCardsSeen.Clear();
            Notify(Changed, nameof(Changed));
        }
    }
}