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.

57.6 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map.Units;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;

/// <summary>B1: the turn report, the meter tip and the Why screen word the economy, population, effect and security lines
/// (CauseKeys) in the player's language through CauseText. In English every row is the sim's Message, word for word, so
/// the English report is what it was before B1; in Hebrew each keyed line is Hebrew, its amounts the only Latin text.</summary>
public class CauseTextTests
{
    static readonly Content C = ContentLoader.Load(Paths.Content);
    static readonly IReadOnlyList<UnitEntry> NoRows = Array.Empty<UnitEntry>();
    static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
    static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");

    /// <summary>The golden seed's whole game, played by the reference player, turn by turn.</summary>
    static IEnumerable<StepResult> Turns()
    {
        var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
        for (int t = 0; t < 1000 && s.GameOver == null; t++)
        {
            var r = Simulation.Step(C, s, GoldenRun.Orders(C, s));
            yield return r;
            s = r.State;
        }
    }

    /// <summary>Before B1 the report and the tip showed each cause's Message; now CauseText's English. For a seeded game,
    /// every turn and every meter, the rows are the same, character for character, and so is every Why line.</summary>
    [Test]
    public void TheEnglishRowsAreTheSameAsBefore()
    {
        var en = En; int rows = 0, keyed = 0;
        foreach (var turn in Turns())
        {
            foreach (var id in HudModel.MeterIds)
            {
                var before = HudModel.Causes(turn, id, C, w => w.Message);
                CollectionAssert.AreEqual(before, HudModel.Causes(turn, id, C, w => CauseText.Line(w, C, NoRows, en)), id);
                rows += before.Count;
            }
            foreach (var w in turn.Why.Where(w => CauseKeys.All.Contains(w.Key)))
            {
                Assert.AreEqual(w.Message, CauseText.Line(w, C, NoRows, en), w.Key);
                keyed++;
            }
        }
        Assert.Greater(rows, 100, "precondition: the game has report rows");
        Assert.Greater(keyed, 400, "precondition: the game has keyed lines (531 at 7ec163c4)");
    }

    /// <summary>In Hebrew every keyed line of the seeded game is Hebrew: right to left, every placeholder filled, and no
    /// Latin letter outside a value UiText marked left to right (an amount such as "IL -6.8m").</summary>
    [Test]
    public void EveryKeyedLineIsHebrewInHebrew()
    {
        var he = He; var seen = new HashSet<string>();
        // GameRoot passes the map's sourced Hebrew settlement names to every report renderer.
        var names = Statecraft.Game.Map.SettlementPlacer.Parse(System.IO.File.ReadAllText(
            System.IO.Path.Combine(Paths.Content, "map", "settlements_1948.yaml"))).ToDictionary(s => s.Id, s => s.NameHe);
        foreach (var turn in Turns())
            foreach (var w in turn.Why.Where(w => CauseKeys.All.Contains(w.Key)))
            {
                AssertHebrew(CauseText.Line(w, C, NoRows, he, names), w.Key);
                seen.Add(w.Key);
            }
        Assert.GreaterOrEqual(seen.Count, 8, "precondition: the game reaches most keys: " + string.Join(", ", seen));
    }

    [Test]
    public void MissingHebrewPlaceNamesKeepTheMarkedEnglishFallback()
    {
        var row = new Cause("city", "hadera", 0, "Hadera: jobs paid IL\u00A00.0m", key: CauseKeys.WagesPaid);
        var missing = new Dictionary<string, string>();
        var line = CauseText.Line(row, C, NoRows, He);
        Assert.IsTrue(string.Equals(line, CauseText.Line(row, C, NoRows, He, missing), StringComparison.Ordinal));
        Assert.GreaterOrEqual(line.IndexOf(UiText.LeftToRightMark + "Hadera" + UiText.LeftToRightMark, StringComparison.Ordinal), 0);
        Assert.GreaterOrEqual(line.IndexOf("תשלום מעבודה", StringComparison.Ordinal), 0);
        var unmarked = Regex.Replace(line, UiText.LeftToRightMark + "[^" + UiText.LeftToRightMark + "]*" + UiText.LeftToRightMark, "");
        Assert.IsFalse(Regex.IsMatch(unmarked, "[A-Za-z]"));
    }

    [Test]
    public void PostponedAndLapsedOperationsNameTheUnitAndRegionsInBothLanguages()
    {
        var e = C.Events.Single(x => x.Id == "operation_horev");
        var s = Simulation.NewGame(C, 23, Mode.Historical);
        s.Date = e.From; s.PendingEvents.Clear(); s.PendingEvents.Add(e.Id);
        var why = new List<Cause>(); EventSystem.Delegate(C, s, why);
        var postponed = why.Single(x => x.Key == CauseKeys.OperationPostponed);
        var rows = UnitData.Parse(System.IO.File.ReadAllText(System.IO.Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        var en = CauseText.Line(postponed, C, rows, En);
        StringAssert.Contains("Golani Brigade", en); StringAssert.Contains("Negev", en); StringAssert.Contains("Southern Coast", en);
        StringAssert.DoesNotContain("golani", en); StringAssert.DoesNotContain("southern_coast", en);
        var he = CauseText.Line(postponed, C, rows, He);
        StringAssert.Contains("חטיבת גולני", he); StringAssert.Contains("הנגב", he); StringAssert.Contains("מישור החוף הדרומי", he);
        // The owner's choice, 7 November 2026: "Neutral form (Recommended)": the decision is the subject, so the verb agrees
        // with any card title, a plural one such as "קרבות עשרת הימים" included.
        StringAssert.Contains("ההחלטה על", he); StringAssert.Contains("נדחתה", he);
        Assert.IsFalse(Regex.IsMatch(he, "golani|southern_coast|negev"), he);

        // R-ENEMY-007 (owner, 7 November 2026: "6 turns (Recommended)"): a postponed card lapses after its wait, not at its window's end.
        s.Date = e.To!.Value; s.Turn += C.Rules.Mvp!.OperationWaitTurns!.Value + 1; why.Clear(); EventSystem.LapseExpiredOperations(C, s, why);
        var lapsed = why.Single(x => x.Key == CauseKeys.OperationLapsed);
        StringAssert.Contains("Golani Brigade", CauseText.Line(lapsed, C, rows, En));
        var heLapsed = CauseText.Line(lapsed, C, rows, He);
        StringAssert.Contains("חטיבת גולני", heLapsed);
        StringAssert.Contains("ההחלטה על", heLapsed); StringAssert.Contains("ירדה מן הפרק", heLapsed);
    }

    /// <summary>R-ENEMY-007 (owner, 7 November 2026): the lapse on a signed front, the lapse on a lost unit and the wait for
    /// the front's armistice, from the sim's own causes, each in both languages, Hebrew in the neutral form ("ההחלטה על").
    /// Horev postponed with Golani out of place, then each ending made.</summary>
    [Test]
    public void TheArmisticeAndLostUnitLinesAreWordedInBothLanguages()
    {
        var e = C.Events.Single(x => x.Id == "operation_horev");
        var rows = UnitData.Parse(System.IO.File.ReadAllText(System.IO.Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        GameState Postponed()
        {
            var s = Simulation.NewGame(C, 23, Mode.Historical);
            s.Date = e.From; s.PendingEvents.Clear(); s.PendingEvents.Add(e.Id);
            EventSystem.Delegate(C, s, new List<Cause>());
            Assert.IsTrue(s.PostponedOperations.ContainsKey(e.Id));
            return s;
        }
        var signed = Postponed(); signed.ChosenOptions["armistice_egypt"] = "sign";
        var why = new List<Cause>(); EventSystem.LapseExpiredOperations(C, signed, why);
        var lapsedSigned = why.Single(x => x.Key == CauseKeys.OperationLapsedSigned);
        StringAssert.Contains("Egypt", CauseText.Line(lapsedSigned, C, rows, En));
        var he = CauseText.Line(lapsedSigned, C, rows, He);
        StringAssert.Contains("ההחלטה על", he); StringAssert.Contains("מצרים", he);

        var lost = Postponed(); lost.Units.Remove(C.StartingForces.FindIndex(f => f.Row == "golani"));
        why.Clear(); EventSystem.LapseExpiredOperations(C, lost, why);
        var lapsedLost = why.Single(x => x.Key == CauseKeys.OperationLapsedUnitLost);
        StringAssert.Contains("Golani Brigade", CauseText.Line(lapsedLost, C, rows, En));
        StringAssert.Contains("חטיבת גולני", CauseText.Line(lapsedLost, C, rows, He));

        var waiting = Postponed();   // Horev postponed in December, still waiting when Egypt's card comes on 15 February 1949
        waiting.Date = new System.DateTime(1949, 2, 15); waiting.PendingEvents.Add("armistice_egypt");
        why.Clear(); EventSystem.Delegate(C, waiting, why);
        var waits = why.Single(x => x.Key == CauseKeys.OperationWaitsForArmistice);
        StringAssert.Contains("Egypt", CauseText.Line(waits, C, rows, En));
        StringAssert.Contains("מצרים", CauseText.Line(waits, C, rows, He));
    }

    /// <summary>The keyed lines the seeded game does not reach: a call-up order, a situation that ends, civilian upkeep and
    /// its borrowing, the currency crisis on both sides, and the legacy loop's food cut and UN ceasefire.</summary>
    [Test]
    public void TheRareLinesAreWordedInBothLanguages()
    {
        var why = new List<Cause>();
        var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
        Assert.IsNull(SecuritySystem.SetMobilization(C, s, 1.0, why));
        s.ActiveSituations.Add("food_crisis"); s.Indicators["food_supply"] = 0.6;
        EffectsSystem.UpdateSituations(C, s, why);
        // Civilian upkeep: the real content's places cost nothing yet, so the line is the sim's own (EconomySystem.PayCivilianUpkeep),
        // and the borrowing comes from PayNamedOrBorrow with that purpose.
        why.Add(new Cause("economy", "treasury", -2, PlayerText.Change(C, "treasury", -2) + " (civilian upkeep)", key: CauseKeys.CivilianUpkeep));
        EconomySystem.PayNamedOrBorrow(C, s, s.Treasury + 3, "for civilian upkeep", why, CauseKeys.Purpose.CivilianUpkeep);
        // #2212: Money's Other line, the rest of the causes a list leaves out (here all of them: the IL -2.0m upkeep).
        why.Add(EconomySystem.OtherMoney(C, why, new Cause[0])!);
        s.ActiveSituations.Add(EconomySystem.FxCrisis); s.FxReserves = 1e6;
        EconomySystem.Apply(C, s, 0.25, why);
        s.ActiveSituations.Remove(EconomySystem.FxCrisis); s.FxReserves = -1e6;
        EconomySystem.Apply(C, s, 0.25, why);

        var legacy = SimBridgeGddTests.Legacy;
        var l = Simulation.NewGame(legacy, GoldenRun.Seed, Mode.Historical);
        l.ActiveSituations.Add(EconomySystem.FxCrisis); l.FxReserves = -1e6;
        EconomySystem.Apply(legacy, l, 0.25, why);
        l.Rung = 5; l.CeasefireWeeksLeft = 1;
        SecuritySystem.Apply(legacy, l, 1, why);

        var keys = why.Where(w => CauseKeys.All.Contains(w.Key)).Select(w => w.Key).Distinct().ToList();
        foreach (var key in new[] { CauseKeys.CallUpSet, CauseKeys.SituationEnded, CauseKeys.CivilianUpkeep, CauseKeys.Borrowed, CauseKeys.MoneyOther,
                     CauseKeys.FxCrisisEased, CauseKeys.FxCrisisBegan, CauseKeys.FxCrisisFood, CauseKeys.Ceasefire })
            CollectionAssert.Contains(keys, key, "precondition");
        var en = En; var he = He;
        foreach (var w in why.Where(w => CauseKeys.All.Contains(w.Key)))
        {
            var content = w.Target == "food_supply" || w.Key == CauseKeys.Ceasefire ? legacy : C;
            Assert.AreEqual(w.Message, CauseText.Line(w, content, NoRows, en), w.Key);
            AssertHebrew(CauseText.Line(w, content, NoRows, he), w.Key);
        }
    }

    /// <summary>Borrowing for every purpose PayOrBorrow's callers give (the English purpose as each caller words it): English
    /// is the Message, Hebrew is Hebrew, and an event's title is its title_he.</summary>
    [Test]
    public void EveryBorrowingPurposeIsWordedInBothLanguages()
    {
        var place = C.SettlementTargets[0].Id; var placeName = C.SettlementNames[place];
        var housing = C.ProjectKinds.First(k => k.Id == "housing");
        var ev = C.Events.First(e => e.TitleHe != "");
        var purposes = new (string Key, string English, string[] Args)[]
        {
            (CauseKeys.Purpose.CivilianUpkeep, "for civilian upkeep", new string[0]),
            (CauseKeys.Purpose.MilitaryUpkeep, "for military upkeep", new string[0]),
            (CauseKeys.Purpose.Corridor, "to build a corridor segment", new string[0]),
            (CauseKeys.Purpose.Arms, "for Arms", new string[0]),
            (CauseKeys.Purpose.Training, "for training", new string[0]),
            (CauseKeys.Purpose.Prisoners, "for our soldiers held by the enemy", new string[0]),
            (CauseKeys.Purpose.TrainingCamp, "to build a training camp", new string[0]),
            (CauseKeys.Purpose.Plow, "to plow fields", new string[0]),
            (CauseKeys.Purpose.Drain, "to drain a swamp", new string[0]),
            (CauseKeys.Purpose.Yishuv, "to build a yishuv", new string[0]),
            (CauseKeys.Purpose.Project, "to build " + housing.Name, new[] { housing.Id }),
            (CauseKeys.Purpose.Deport, $"for the Deport of {placeName}", new[] { place }),
            (CauseKeys.Purpose.Occupation, $"for the occupation of {placeName}", new[] { place }),
            (CauseKeys.Purpose.Event, $"for {ev.Title}", new[] { ev.Id, ev.Title, "1" }),
            (CauseKeys.Purpose.Workshop, "for an arms workshop cycle", new string[0]),   // R-ARMS-006
            (CauseKeys.Purpose.HousingSurcharge, "for the housing surcharge", new string[0]),   // #1703, gdd-0.3 (Cities.SettleGdd03)
        };
        // A map action borrows with its own key (CauseKeys.MapBorrowed): its purpose names only its Paid line (#2199).
        CollectionAssert.AreEquivalent(CauseKeys.Purpose.All.Where(p => p != CauseKeys.Purpose.Deficit && p != CauseKeys.Purpose.MapAction),
            purposes.Select(p => p.Key), "every purpose");
        var en = En; var he = He;
        foreach (var (key, english, args) in purposes)
        {
            var why = new List<Cause>();
            var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
            EconomySystem.PayNamedOrBorrow(C, s, s.Treasury + 3, english, why, key, args);   // the borrowing line alone
            var line = why.Single();
            Assert.AreEqual(line.Message, CauseText.Line(line, C, NoRows, en), key);
            AssertHebrew(CauseText.Line(line, C, NoRows, he), key);
        }
        var title = new Cause("economy", "debt", 3, "x", key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Event, ev.Id, ev.Title, "1" });
        StringAssert.Contains(ev.TitleHe, CauseText.Line(title, C, NoRows, he), "the event's Hebrew title");
        StringAssert.Contains(housing.NameHe, CauseText.Line(new Cause("economy", "debt", 3, "x", key: CauseKeys.Borrowed,
            args: new[] { CauseKeys.Purpose.Project, housing.Id }), C, NoRows, he), "the project kind's Hebrew name");
    }

    /// <summary>#2199: PayOrBorrow's Money line (CauseKeys.Paid) for every purpose whose cost has no Money line of its own
    /// (the English purpose as each caller words it): English is the Message, Hebrew is Hebrew, and a project kind and a
    /// settlement are named in Hebrew. Civilian and military upkeep, a Deport and an event's cost write their own line and
    /// borrow through PayNamedOrBorrow, and the deficit borrows in EconomySystem.Apply, so none of them has a Paid line.</summary>
    [Test]
    public void EveryPaidPurposeIsWordedInBothLanguages()
    {
        var place = C.SettlementTargets[0].Id; var placeName = C.SettlementNames[place];
        var housing = C.ProjectKinds.First(k => k.Id == "housing");
        var purposes = new (string Key, string English, string[] Args)[]
        {
            (CauseKeys.Purpose.Corridor, "to build a corridor segment", new string[0]),
            (CauseKeys.Purpose.Arms, "for Arms", new string[0]),
            (CauseKeys.Purpose.Training, "for training", new string[0]),
            (CauseKeys.Purpose.Prisoners, "for our soldiers held by the enemy", new string[0]),
            (CauseKeys.Purpose.TrainingCamp, "to build a training camp", new string[0]),
            (CauseKeys.Purpose.Plow, "to plow fields", new string[0]),
            (CauseKeys.Purpose.Drain, "to drain a swamp", new string[0]),
            (CauseKeys.Purpose.Yishuv, "to build a yishuv", new string[0]),
            (CauseKeys.Purpose.Project, "to build " + housing.Name, new[] { housing.Id }),
            (CauseKeys.Purpose.Occupation, $"for the occupation of {placeName}", new[] { place }),
            (CauseKeys.Purpose.MapAction, "to build " + PlayerText.MapAction(C, MapActions.Housing), new[] { MapActions.Housing }),   // as MapActions.Apply
            (CauseKeys.Purpose.Workshop, "for an arms workshop cycle", new string[0]),   // R-ARMS-006
        };
        CollectionAssert.AreEquivalent(CauseKeys.Purpose.All.Except(new[] { CauseKeys.Purpose.Deficit, CauseKeys.Purpose.CivilianUpkeep,
            CauseKeys.Purpose.MilitaryUpkeep, CauseKeys.Purpose.Deport, CauseKeys.Purpose.Event, CauseKeys.Purpose.HousingSurcharge }), purposes.Select(p => p.Key), "every paying purpose");
        var en = En; var he = He;
        foreach (var (key, english, args) in purposes)
        {
            var why = new List<Cause>();
            var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
            EconomySystem.PayOrBorrow(C, s, s.Treasury + 3, english, why, key, args);
            var line = why.Single(w => w.Key == CauseKeys.Paid);
            Assert.AreEqual(line.Message, CauseText.Line(line, C, NoRows, en), key);
            AssertHebrew(CauseText.Line(line, C, NoRows, he), key);
        }
        StringAssert.Contains(housing.NameHe, CauseText.Line(new Cause("economy", "treasury", -3, "x", key: CauseKeys.Paid,
            args: new[] { CauseKeys.Purpose.Project, housing.Id }), C, NoRows, he), "the project kind's Hebrew name");
        StringAssert.Contains(he["info.map_action." + MapActions.Housing], CauseText.Line(new Cause("economy", "treasury", -3, "x", key: CauseKeys.Paid,
            args: new[] { CauseKeys.Purpose.MapAction, MapActions.Housing }), C, NoRows, he), "the map action's Hebrew name");
    }

    /// <summary>A line with no key yet keeps the sim's English; a unit line is still UnitNames' (#1399).</summary>
    [Test]
    public void OtherLinesAreUnchanged()
    {
        var plain = new Cause("economy", "treasury", -1, "Money IL\u00A0-1.0m (military upkeep)");
        Assert.AreEqual(plain.Message, CauseText.Line(plain, C, NoRows, He));
        var turn = Turns().First(t => t.Why.Any(w => WhyKeys.All.Contains(w.Key)));
        foreach (var w in turn.Why.Where(w => WhyKeys.All.Contains(w.Key)))
            Assert.AreEqual(UnitNames.Line(w, C, NoRows, He), CauseText.Line(w, C, NoRows, He));
    }

    /// <summary>#1680: a positive producer set prevents missing keys from being silently skipped by the existing tests.</summary>
    [Test]
    public void EveryEventAndUpkeepLineUsesATemplateAndKeepsItsEnglish()
    {
        var en = En; var he = He;
        var lines = Turns().SelectMany(t => t.Why).Where(w => w.System == "events" || w.Key == CauseKeys.MilitaryUpkeep).ToList();
        Assert.IsNotEmpty(lines);
        Assert.IsTrue(lines.Any(w => w.Key == CauseKeys.MilitaryUpkeep));
        foreach (var w in lines)
        {
            CollectionAssert.Contains(CauseKeys.All, w.Key, w.Message);
            Assert.AreEqual(w.Message, CauseText.Line(w, C, NoRows, en), w.Key);
            AssertHebrew(CauseText.Line(w, C, NoRows, he), w.Key);
        }
        var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
        foreach (var row in C.Events.SelectMany(e => e.Options).SelectMany(o => EventSystem.OptionEffects(C, s, o)))
        {
            CollectionAssert.Contains(CauseKeys.All, row.Key);
            Assert.AreEqual(row.Message, CauseText.Line(row, C, NoRows, en), row.Key);
            AssertHebrew(CauseText.Line(row, C, NoRows, he), row.Key);
        }
    }

    /// <summary>R-EFX-009 (#2457): the Debt line an option's debt_dollars writes (an EventAmount cause on "debt") is worded
    /// in both languages: English is the Message and starts "Debt"; Hebrew names חוב with the event's amount and title.</summary>
    [Test]
    public void TheEventDebtLineIsWordedInBothLanguages()
    {
        var debt = new Cause("events", "debt", 18.564, $"{PlayerText.Change(C, "debt", 18.564)} (Bonds)",
            key: CauseKeys.EventAmount, args: new[] { "Bonds", "אג״ח ישראל" });
        var en = CauseText.Line(debt, C, NoRows, En);
        Assert.AreEqual(debt.Message, en);
        StringAssert.StartsWith("Debt", en);
        var he = CauseText.Line(debt, C, NoRows, He);
        StringAssert.Contains("חוב", he);
        StringAssert.Contains(PlayerText.MoneyChange(C, "debt", 18.564), he);
        StringAssert.Contains("אג״ח ישראל", he);
        AssertHebrew(he, debt.Key);
    }

    /// <summary>#2558: in the Money row (the turn report and the Money meter tip, HudModel.Causes) the Israel Bonds Debt
    /// line reads as its Money effect (EconomySystem.MoneyLine), not as a Debt gain: "Money IL -18.6m (Israel Bonds)" in
    /// English, and in Hebrew כסף with the same change and the Hebrew title, without חוב.</summary>
    [Test]
    public void TheEventDebtLineReadsAsItsMoneyEffectInTheMoneyRow()
    {
        var debt = new Cause("events", "debt", 18.564, $"{PlayerText.Change(C, "debt", 18.564)} (Israel Bonds)",
            key: CauseKeys.EventAmount, args: new[] { "Israel Bonds", "מלווה העצמאות" });
        var turn = new StepResult(new GameState(), new List<Cause> { debt }, new Rejection[0]);
        CollectionAssert.AreEqual(new[] { "Money IL -18.6m (Israel Bonds)" },
            HudModel.Causes(turn, "treasury", C, w => CauseText.Line(w, C, NoRows, En)));
        var he = HudModel.Causes(turn, "treasury", C, w => CauseText.Line(w, C, NoRows, He)).Single();
        StringAssert.Contains("כסף", he);
        StringAssert.Contains(PlayerText.MoneyChange(C, "treasury", -18.564), he);
        StringAssert.Contains("מלווה העצמאות", he);
        StringAssert.DoesNotContain("חוב", he);
        AssertHebrew(he, debt.Key);
    }

    [Test]
    public void AResolvedEventUsesItsHistoricalContentSnapshots()
    {
        var w = new Cause("events", "example", 0, "Delegated to Previous name: Previous choice",
            key: CauseKeys.EventDelegated, args: new[] { "Previous choice", "הבחירה הקודמת", "Previous name", "השם הקודם" });
        Assert.AreEqual(w.Message, CauseText.Line(w, C, NoRows, En));
        var line = CauseText.Line(w, C, NoRows, He);
        StringAssert.Contains("השם הקודם", line);
        StringAssert.Contains("הבחירה הקודמת", line);
        AssertHebrew(line, w.Key);
    }

    [Test]
    public void ObjectiveAndExchangeEventRowsKeepEnglishAndRenderHebrew()
    {
        var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);
        var objective = C.Objectives.First(o => o.NameHe != "" && !s.Objectives.ContainsKey(o.Id));
        var lines = new List<Cause>();
        Assert.IsTrue(Objectives.Record(C, s, C.RulesAt(s.Date).Mvp!, objective.Id, s.Date, lines));
        var objectiveLine = lines.Single();
        Assert.AreEqual(CauseKeys.ObjectiveCompleted, objectiveLine.Key);
        StringAssert.Contains(objective.NameHe, CauseText.Line(objectiveLine, C, NoRows, He));
        foreach (var front in Prisoners.Fronts)
        {
            // Renderer fixtures use people counts, not population-unit Delta: preserve the producer's N0 display.
            lines.Add(new Cause("events", "prisoners", 2,
                $"Prisoners exchanged: 12,300 prisoners returned to {PlayerText.Capitalised(front)}",
                key: CauseKeys.PrisonersReturned, args: new[] { "12300", front }));
            lines.Add(new Cause("events", "prisoners", 3,
                $"Prisoners exchanged: 45,600 of our soldiers came home from {PlayerText.Capitalised(front)}",
                key: CauseKeys.SoldiersReturned, args: new[] { "45600", front }));
        }
        foreach (var row in lines)
        {
            CollectionAssert.Contains(CauseKeys.All, row.Key);
            Assert.AreEqual(row.Message, CauseText.Line(row, C, NoRows, En), row.Key);
            AssertHebrew(CauseText.Line(row, C, NoRows, He), row.Key);
        }
    }

    /// <summary>#1703 (R-HOUSE-005, gdd-0.3 only): the housing surcharge's Money line and the housing condition's Social
    /// cohesion line, worded as Cities.SettleGdd03 writes them: English is the Message, Hebrew is Hebrew.</summary>
    [Test]
    public void TheGdd03HousingLinesAreWordedInBothLanguages()
    {
        var lines = new[]
        {
            new Cause("economy", "treasury", -7.665, $"{PlayerText.Change(C, "treasury", -7.665)} (housing surcharge)", key: CauseKeys.HousingSurcharge),
            new Cause("city", "morale", -0.01, $"{PlayerText.Change(C, "morale", -0.01)} (housing condition)", key: CauseKeys.HousingCohesion),
        };
        var en = En; var he = He;
        foreach (var line in lines)
        {
            Assert.AreEqual(line.Message, CauseText.Line(line, C, NoRows, en), line.Key);
            AssertHebrew(CauseText.Line(line, C, NoRows, he), line.Key);
        }
        // The owner's word for the surcharge, 2 Nov 2026: "היטל דיור (Recommended)".
        var surcharge = CauseText.Line(lines[0], C, NoRows, he);
        Assert.IsTrue(surcharge.IndexOf("היטל דיור", StringComparison.Ordinal) >= 0, surcharge);
    }

    static void AssertHebrew(string line, string key)
    {
        Assert.IsTrue(UiDirection.RightToLeft(line), $"{key}: '{line}' reads right to left");
        Assert.Less(line.IndexOf("{", StringComparison.Ordinal), 0, key);
        var unmarked = Regex.Replace(line, UiText.LeftToRightMark + "[^" + UiText.LeftToRightMark + "]*" + UiText.LeftToRightMark, "");
        Assert.IsFalse(Regex.IsMatch(unmarked, "[A-Za-z]"), $"{key}: '{line}' has Latin text outside a marked value");
    }

    // Synthetic identities/titles are fixture text, native-review-pending; no content record is edited.
    [Test]
    public void ActualAppointmentRowsKeepDatedTitlesAfterHolderAndDateChange()
    {
        var c = RemainingFixture();
        var date = new DateTime(1948, 5, 15);
        c.Governments[0].From = date.AddDays(-1);
        c.Governments[0].Coalition.Add("party");
        c.Rules.AppointStabilityCostOtherParty = 0.1;
        c.Rules.AppointStabilityCostSameParty = 0.03;
        var office = c.Offices[0];
        office.TitleHe = "תפקיד קודם"; office.TitleHeFrom = date; office.TitleHeUntil = date.AddDays(1);
        c.People[1].Offices.Add(new OfficeTerm { Office = office.Id, From = date.AddDays(-1) });
        c.People[0].Party = "party";
        c.People.Add(new Person { Id = "next", Name = "Next", NameHe = "הבא", Party = "party" });
        var s = new GameState { Date = date, CoalitionStability = 1 };
        var why = new List<Cause>();
        Assert.IsNull(Cabinet.Appoint(c, s, office.Id, "person", why));
        Assert.IsNull(Cabinet.Appoint(c, s, office.Id, "next", why));
        var appointments = why.Where(x => x.Key == "appointed").ToArray();
        var reshuffles = why.Where(x => x.Key == "reshuffle").ToArray();
        Assert.AreEqual(2, appointments.Length); Assert.AreEqual(2, reshuffles.Length);
        CollectionAssert.AreEqual(new[] { "person", "תפקיד קודם", "former" }, appointments[0].Args);
        CollectionAssert.AreEqual(new[] { "", "former", "other", "Office", "תפקיד קודם" }, reshuffles[0].Args);
        CollectionAssert.AreEqual(new[] { "party", "person", "same", "Office", "תפקיד קודם" }, reshuffles[1].Args);
        Assert.AreEqual("Person appointed Office, replacing Former", appointments[0].Message);
        s.Date = date.AddDays(2); office.TitleHe = "תפקיד חדש";
        Assert.AreEqual("next", Cabinet.Holder(c, s, office.Id)!.Id);
        foreach (var row in why)
        {
            Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, En), row.Key);
            var he = CauseText.Line(row, c, NoRows, He);
            AssertHebrew(he, row.Key);
            StringAssert.DoesNotContain("תפקיד חדש", he);
            if (row.Key == "appointed" || row.Args[2] == "other") StringAssert.Contains("תפקיד קודם", he);
        }
    }

    [TestCase(false)] [TestCase(true)]
    public void ActualResidentRowsRenderAfterSettlementRecordsAreRemoved(bool fled)
    {
        // Existing CaptureDialog fixture pattern: real rules/map, synthetic capture eligibility and resident facts.
        // Deport's cards (#801, a `deported:` key) name targets this fixture's list leaves out (R-EVT-007), so they stay out too.
        var events = System.IO.Directory.GetFiles(System.IO.Path.Combine(Paths.Content, "events"), "*.yaml")
            .Where(f => !System.Text.RegularExpressions.Regex.IsMatch(System.IO.File.ReadAllText(f), @"(?m)^deported:"))
            .Select(f => "events/" + System.IO.Path.GetFileName(f));
        var c = ContentLoader.Load(rel => {
            var path = System.IO.Path.Combine(Paths.Content, rel);
            if (!System.IO.File.Exists(path)) return null;
            if (rel == "settlement_targets.yaml") return "targets:\n  - { id: lod, q: -3, r: 23, operation: Fixture, sources: [{ url: \"https://example.org/fixture\", checked: 2026-10-21 }], residents: stayed, residents_sources: [{ url: \"https://example.org/fixture\", checked: 2026-10-21 }], annexation: { people: { value: 60, status: sourced, date: 1948-11-08, sources: [{ url: \"https://example.org/fixture\", checked: 2026-10-21 }] }, employed_share: { value: 0.5, status: design } }, status: draft }\n";
            return System.IO.File.ReadAllText(path);
        }, events);
        var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
        s.Units.Clear(); s.Units.Add(100, new Unit(100, "veteran_soldier", -3, 23, side: Movement.PlayerSide, strength: 3));
        s.Settlements["lod"] = new SettlementControl(Movement.PlayerSide, SettlementControl.AwaitingChoice, s.Date, fled: fled);
        // Preview shares RunOrders with Step and invokes the real producers, without unrelated monthly effects.
        var occupied = Simulation.Preview(c, s, new Command[] { new ResolveCapture("lod", SettlementControl.Occupy) });
        Assert.IsEmpty(occupied.Rejected);
        var why = new List<Cause> { occupied.Why.Single(x => x.Key == "occupation_started") };
        s = occupied.State;
        s.Settlements["lod"] = new SettlementControl(Movement.PlayerSide, SettlementControl.AwaitingEnd, s.Date, fled: fled);
        s.Cities.Remove("lod");
        var annexed = Simulation.Preview(c, s, new Command[] { new EndOccupation("lod", SettlementControl.Annex) });
        Assert.IsEmpty(annexed.Rejected);
        why.Add(annexed.Why.Single(x => x.Key == "place_annexed"));
        annexed.State.Settlements.Clear();
        Assert.AreEqual(2, why.Count);
        CollectionAssert.AreEqual(new[] { "occupation_started", "place_annexed" }, why.Select(x => x.Key));
        s.Settlements.Clear();
        var names = new Dictionary<string, string> { ["lod"] = "לוד" };
        foreach (var row in why)
        {
            CollectionAssert.AreEqual(new[] { fled ? "1" : "0" }, row.Args);
            Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, En), row.Key);
            var he = CauseText.Line(row, c, NoRows, He, names);
            AssertHebrew(he, row.Key);
            StringAssert.Contains(fled ? "נמלטו" : row.Key == "place_annexed" ? "מצטרפים" : "לא השתנה", he);
        }
    }

    // #1682 synthetic content is deliberately not historical. These values exercise every new formatter branch,
    // including large counts, money rounding and Hebrew names. Actual producer metadata is gated in managed tests.
    static Content RemainingFixture() => new Content
    {
        Money = new List<MoneyAccount> { new MoneyAccount { Id = "treasury", Name = "Money", Prefix = "IL\u00A0" }, new MoneyAccount { Id = "debt", Name = "Debt", Prefix = "IL\u00A0" }, new MoneyAccount { Id = "fx_reserves", Name = "Foreign currency", Prefix = "$" } },
        SettlementNames = new Dictionary<string, string> { ["town"] = "Town" },
        Sites = new List<Site> { new Site { Id = "site", Name = "Site", NameHe = "אתר" } },
        Corridors = new List<CorridorDef> { new CorridorDef { Id = "road", Name = "Road", NameHe = "דרך" } },
        ProjectKinds = new List<ProjectKind> { new ProjectKind { Id = "housing", Name = "Housing", NameHe = "דיור" } },
        People = new List<Person> { new Person { Id = "person", Name = "Person", NameHe = "אדם" }, new Person { Id = "former", Name = "Former", NameHe = "קודם" } },
        Offices = new List<Office> { new Office { Id = "office", Title = "Office", TitleHe = "תפקיד נוכחי" } },
        Parties = new List<Party> { new Party { Id = "party", Name = "Party", NameHe = "מפלגה" }, new Party { Id = "other", Name = "Other", NameHe = "אחרת" } },
        Governments = new List<Government> { new Government { Id = "gov", Name = "Government", NameHe = "ממשלה" } },
        Legislatures = new List<Legislature> { new Legislature { Id = "leg", Body = "Body", BodyHe = "מועצה", Size = 120, Elected = new DateTime(1948, 5, 15) } },
    };

    static Cause[] RemainingRows() => new[]
    {
            new Cause("draft", "town", 1, "Town: 2000000000 groups in work", key: CauseKeys.WorkersAssigned, args: new[] { "2000000000" }),
            new Cause("draft", "town", 1.25, "Town: jobs paid IL\u00A0+1.3m", key: CauseKeys.WagesPaid),
            new Cause("draft", "town", 3, "Town: 3 groups of immigrants housed", key: CauseKeys.ImmigrantsHoused, args: new[] { "3" }),
            new Cause("draft", "town", 3, "Town: 3 groups more than its homes hold", key: CauseKeys.HousingShortage, args: new[] { "3" }),
            new Cause("draft", "town", 3, "Town: 3 groups of immigrants arrived and wait for homes", key: CauseKeys.ImmigrantsWaiting, args: new[] { "3" }),
            new Cause("draft", "units", 3, "Recruits became veteran soldiers", key: CauseKeys.RecruitsVeteran),
            new Cause("draft", "road", 1, "Road, segment 2: a group of halutzim began building, cost IL\u00A01.3m", key: CauseKeys.CorridorStarted, args: new[] { "road", "2", "1.25" }),
            new Cause("draft", "road", -1, "Road, segment 2: the halutzim stopped building; the Money spent is not returned", key: CauseKeys.CorridorCancelled, args: new[] { "road", "2" }),
            new Cause("draft", "road", 1, "Road, segment 2 built", key: CauseKeys.CorridorCompleted, args: new[] { "road", "2" }),
            new Cause("draft", "site", 1, "A group of halutzim became veteran pioneers", key: CauseKeys.PioneersVeteran),
            new Cause("draft", "debt", 1.25, "Borrowed IL\u00A01.3m to build a housing project", key: CauseKeys.MapBorrowed, args: new[] { "housing" }),
            new Cause("draft", "housing", 1, "Built a housing project: cost IL\u00A01.3m, Housing +2.5%, Social cohesion -2.5%", key: CauseKeys.MapBuilt, args: new[] { "1.25", "0.025", "-0.025" }),
            new Cause("draft", "site", 1, "Site: a group of halutzim began plowing, cost IL\u00A01.3m", key: CauseKeys.LandWorkStarted, args: new[] { "plow", "1.25" }),
            new Cause("draft", "site", 1, "Site: a group of halutzim began building a yishuv, cost IL\u00A01.3m", key: CauseKeys.SiteStarted, args: new[] { "yishuv", "1.25" }),
            new Cause("draft", "site", -1, "Site: the halutzim stopped building; the Money spent is not returned", key: CauseKeys.SiteCancelled),
            new Cause("draft", "site", 1, "Site founded", key: CauseKeys.SiteCompleted, args: new[] { "founded" }),
            new Cause("draft", "town", 1, "Town: Housing began, cost IL\u00A01.3m", key: CauseKeys.ProjectStarted, args: new[] { "housing", "1.25" }),
            new Cause("draft", "town", -1, "Town: Housing was cancelled; the Money spent is not returned", key: CauseKeys.ProjectCancelled, args: new[] { "housing" }),
            new Cause("draft", "town", 1, "Town: Housing was finished", key: CauseKeys.ProjectCompleted, args: new[] { "housing" }),
            new Cause("draft", "town", 1, "Town: a builder started on Housing", key: CauseKeys.ProjectBuilder, args: new[] { "housing" }),   // #1700
            new Cause("draft", "town", -1, "Town: a builder left Housing and is free again", key: CauseKeys.ProjectBuilderFreed, args: new[] { "housing" }),   // #1700 slice B
            new Cause("draft", "town", 0, "Town: Housing waits: no builder", key: CauseKeys.ProjectWaiting, args: new[] { "housing", Projects.NoBuilder }),
            new Cause("draft", "arms", 2000000000, "Bought 2000000000 Arms, cost IL\u00A01.3m", key: CauseKeys.ArmsBought, args: new[] { "1.25" }),
            new Cause("draft", "town", 2, "Town: arms workshops staffed: 2", key: CauseKeys.WorkshopWorkers, args: new[] { "2" }),
            new Cause("draft", "town", 1, "Town: an arms workshop made 1 Arms", key: CauseKeys.WorkshopArms),
            new Cause("draft", "town", 0, "Town: held by the enemy; no job income or project work this turn", key: CauseKeys.CityHeld),   // #1711
            new Cause("draft", "town", 0, "Town: an arms workshop has no worker without a job this month", key: CauseKeys.WorkshopPaused, args: new[] { Workshops.NoWorker }),
            new Cause("draft", "treasury", 1.44, "Converted $4.0m of foreign currency into Money: IL\u00A0+1.4m", key: CauseKeys.DollarsConverted, args: new[] { "4" }),
            new Cause("draft", "fx_reserves", -4, "Foreign currency converted into Money: $-4.0m", key: CauseKeys.DollarsConvertedFx, args: new[] { "4" }),   // #2527
            new Cause("draft", "food", 2000000000, "Site: the plowed land yielded 2000000000 units of Food", key: CauseKeys.FoodHarvest, args: new[] { "site" }),
            // #2530: a count of 1 names the singular; the helpers name "1 group"/"1 unit"/"1 turn" in English only.
            new Cause("draft", "town", 1, "Town: 1 group in work", key: CauseKeys.WorkersAssigned, args: new[] { "1" }),
            new Cause("draft", "town", 1, "Town: 1 group of immigrants housed", key: CauseKeys.ImmigrantsHoused, args: new[] { "1" }),
            new Cause("draft", "town", 1, "Town: 1 group more than its homes hold", key: CauseKeys.HousingShortage, args: new[] { "1" }),
            new Cause("draft", "town", 1, "Town: 1 group of immigrants arrived and wait for homes", key: CauseKeys.ImmigrantsWaiting, args: new[] { "1" }),
            new Cause("draft", "food", 1, "Site: the plowed land yielded 1 unit of Food", key: CauseKeys.FoodHarvest, args: new[] { "site" }),
            new Cause("draft", "town", 1, "Town: 1 turn of occupation left", key: CauseKeys.OccupationCountdown),
            new Cause("draft", "food", 0, "Food ran out: 2000000000 of 2000000001 units of the month's need went unmet", key: CauseKeys.FoodShortage, args: new[] { "2000000000", "2000000001" }),   // informational (#2527): the unmet, then the need
            new Cause("draft", "food", -1, "No Food imported (foreign currency crisis): the stock fell to 2000000000 units", key: CauseKeys.FoodWithoutImports, args: new[] { "2000000000" }),
            new Cause("draft", "food", 150, "The month's eating and Food imports brought the stock to 2000000000 units", key: CauseKeys.FoodImported, args: new[] { "2000000000" }),   // #2527
            new Cause("draft", "food", -2000000000, "The prisoners held ate 2000000000 units of Food", key: CauseKeys.PrisonerFood),
            new Cause("draft", "morale", -0.025, "The prisoners held went short of 2000000000 units of Food: Social cohesion -2.5%", key: CauseKeys.PrisonerFoodShortage, args: new[] { "2000000000" }),
            new Cause("draft", "town", 1, "Town: 1 group of craftsmen returned to civilian life and keep their training", key: CauseKeys.CraftsmenReturned, args: new[] { "1" }),
            new Cause("draft", "town", -3, "Town: 3 groups of qualified craftsmen are craftsmen again", key: CauseKeys.CraftsmenReassigned, args: new[] { "3" }),
            new Cause("draft", "42", 1, "Unit 42 returned to civilian life in Town and keeps its training", key: CauseKeys.PioneerReturned, args: new[] { "town" }),
            new Cause("draft", "town", -3, "Town: 3 groups of qualified veteran pioneers are units again", key: CauseKeys.PioneersReassigned, args: new[] { "3", "veteran" }),
            new Cause("draft", "town", -3, "Town: 3 groups began basic training as replacements for unit 42, cost IL\u00A01.3m", key: CauseKeys.TrainingStarted, args: new[] { "3", "basic", "42", "1.25" }),
            new Cause("draft", "arms", -3, "Town: basic training took 3 Arms", key: CauseKeys.TrainingArms, args: new[] { "town", "basic" }),
            new Cause("draft", "town", 3, "Town: 3 groups left basic training; the Money spent is not returned", key: CauseKeys.TrainingCancelled, args: new[] { "3", "basic" }),
            new Cause("draft", "arms", 3, "Town: basic training returned 3 Arms", key: CauseKeys.TrainingArmsReturned, args: new[] { "town", "basic" }),
            new Cause("city", "arms", 3, "Town: unit 42 returned 3 Arms", key: CauseKeys.SentHomeArmsReturned, args: new[] { "town", "42" }),   // #3020 (Demobilization.ArmsReturnedLine)
            new Cause("draft", "town", 0, "Town: unit 42 is no longer in Town, so its replacements stop training", key: CauseKeys.ReplacementsStopped, args: new[] { "42" }),
            new Cause("draft", "town", 3, "Town: 3 groups finished basic training and joined unit 42", key: CauseKeys.ReplacementsJoined, args: new[] { "3", "basic", "42" }),
            new Cause("draft", "town", 3, "Town: 3 groups finished artillery training and are artillery", key: CauseKeys.MilitaryTrained, args: new[] { "3", "artillery", "artillery" }),
            new Cause("draft", "town", 3, "Town: 3 groups finished pioneer training and are halutzim", key: CauseKeys.PioneersTrained, args: new[] { "3", "pioneer" }),
            new Cause("draft", "town", 3, "Town: 3 groups finished craft training and are craftsmen", key: CauseKeys.CraftsmenTrained, args: new[] { "3", "craft" }),
            new Cause("draft", "office", 0, "Person appointed Office, replacing Former", key: CauseKeys.Appointed, args: new[] { "person", "התפקיד שנשמר", "former" }),
            new Cause("draft", "coalition_stability", -0.025, "Coalition stability -2.5% (Party lost the Office)", key: CauseKeys.Reshuffle, args: new[] { "party", "former", "other", "Office", "התפקיד שנשמר" }),
            new Cause("draft", "appointments", -1, "A new government took office with its own ministers; your appointments ended", key: CauseKeys.AppointmentsEnded),
            new Cause("draft", "coalition_stability", -0.025, "Coalition stability -2.5% (public approval)", key: CauseKeys.ApprovalStability),
            new Cause("draft", "game_over", 0, "The coalition collapsed. Your premiership is over.", key: CauseKeys.CoalitionCollapsed),
            new Cause("draft", "leg", 0, "Body convened (120 seats, elected 15 May 1948); coalition holds 61/120", key: CauseKeys.LegislatureConvened, args: new[] { "61", "120" }),
            new Cause("draft", "gov", 0, "Government took office (Party)", key: CauseKeys.GovernmentTookOffice, args: new[] { "party" }),
            new Cause("draft", "gov", 0, "Party left the coalition; Other joined the coalition (coalition holds 61/120)", key: CauseKeys.CoalitionChanged, args: new[] { "party", "other", "61", "120" }),
            new Cause("draft", "era_ended", 0, "The chapter has ended", key: CauseKeys.EraEnded),
            new Cause("draft", "rationing", 0, "Body voted against Rationing at 25%, but its vote does not bind", key: CauseKeys.AdvisoryPolicyRejected, args: new[] { "leg", "0.25" }),
            new Cause("draft", "rationing", 0, "Body voted down Rationing at 25%", key: CauseKeys.PolicyRejected, args: new[] { "leg", "0.25" }),
            new Cause("draft", "rationing", 0.25, "Rationing set to 25%", key: CauseKeys.PolicySet),
            new Cause("draft", "budget", 0, "Body voted against the budget, but its vote does not bind", key: CauseKeys.AdvisoryBudgetRejected, args: new[] { "leg" }),
            new Cause("draft", "budget", 0, "Body voted the budget down", key: CauseKeys.BudgetRejected, args: new[] { "leg" }),
            new Cause("draft", "town", 0, "Town is captured: Israeli units hold it and no enemy unit is there. Its residents fled. It awaits a decision", key: CauseKeys.PlaceCaptured, args: new[] { "1" }),
            new Cause("draft", "town", 0, "Town is under enemy control again: enemy units hold it and no Israeli unit is there. Its residents fled when it was captured", key: CauseKeys.EnemyRegained, args: new[] { "1" }),
            new Cause("draft", "town", 0, "Town is lost: enemy units hold it and no Israeli unit is there", key: CauseKeys.PlaceLost),   // R-CTRL-006 (#1305)
            new Cause("draft", "town", 0, "Town is retaken: Israeli units hold it again and no enemy unit is there", key: CauseKeys.PlaceRetaken),
            new Cause("draft", "town", 0, "Town is annexed. Its residents fled when it was captured, so no people, homes or jobs are added", key: CauseKeys.PlaceAnnexed, args: new[] { "1" }),
            new Cause("draft", "town", 0, "Town: Israeli units withdrew and it is under enemy control again. Its residents fled when it was captured", key: CauseKeys.PlaceWithdrawn, args: new[] { "1", "1" }),
            new Cause("draft", "town", 0, "Town: Deport. Its residents are displaced and the place is depopulated", key: CauseKeys.PlaceDeported),
            new Cause("draft", "morale", -0.025, "Social cohesion -2.5% (Deport of Town)", key: CauseKeys.DeportEffect, args: new[] { "town" }),
            new Cause("draft", "treasury", -1.25, "Money IL\u00A0-1.3m (Deport of Town)", key: CauseKeys.DeportCost, args: new[] { "town" }),
            new Cause("draft", "town", 3, "Town is occupied for 3 turns: an Israeli unit stays there. Its residents fled when it was captured", key: CauseKeys.OccupationStarted, args: new[] { "1" }),
            new Cause("draft", "town", 0, "Town: no decision was made before the game ended, so it counts as a raid", key: CauseKeys.PendingBecameRaid),
            new Cause("draft", "town", 0, "Town: no Israeli unit holds it any more, so the occupation ended as a raid. It is under enemy control again. Its residents fled when it was captured", key: CauseKeys.OccupationLostUnit, args: new[] { "1" }),
            new Cause("draft", "town", 3, "Town: 3 turns of occupation left", key: CauseKeys.OccupationCountdown),
            new Cause("draft", "intl_standing", -0.025, "International support -2.5% (the places depopulated by Deport)", key: CauseKeys.DepopulationSupport),
    };

    [TestCase(false)]
    [TestCase(true)]
    public void ReviewedCaptureStringsKeepExactWordingAndDirectionMarks(bool useHebrewName)
    {
        var c = RemainingFixture(); var en = En; var he = He;
        var names = useHebrewName ? new Dictionary<string, string> { ["town"] = "עיר" } : null;
        var place = useHebrewName ? "עיר" : "\u200ETown\u200E";
        var countdown = new Cause("map", "town", 3, "Town: 3 turns of occupation left", key: CauseKeys.OccupationCountdown);
        var raid = new Cause("map", "town", 0,
            "Town: no decision was made before the game ended, so it counts as a raid", key: CauseKeys.PendingBecameRaid);
        Assert.IsTrue(string.Equals("{0}: מוחזק, תורות שנותרו: {1}", he["why.cause.occupation_countdown"], StringComparison.Ordinal));
        Assert.IsTrue(string.Equals("{0}: {1} of occupation left", en["why.cause.occupation_countdown"], StringComparison.Ordinal));   // #2530: the count names its noun ("1 turn"/"N turns")
        Assert.IsTrue(string.Equals("{0}: לא התקבלה החלטה עד סוף המשחק, ולכן הדבר נחשב לפשיטה", he["why.cause.pending_became_raid"], StringComparison.Ordinal));
        Assert.IsTrue(string.Equals("{0}: no decision was made before the game ended, so it counts as a raid", en["why.cause.pending_became_raid"], StringComparison.Ordinal));
        Assert.IsTrue(string.Equals("Town: 3 turns of occupation left", CauseText.Line(countdown, c, NoRows, en), StringComparison.Ordinal));
        Assert.IsTrue(string.Equals("Town: no decision was made before the game ended, so it counts as a raid", CauseText.Line(raid, c, NoRows, en), StringComparison.Ordinal));
        Assert.IsTrue(string.Equals(place + ": מוחזק, תורות שנותרו: \u200E3\u200E", CauseText.Line(countdown, c, NoRows, he, names), StringComparison.Ordinal));
        Assert.IsTrue(string.Equals(place + ": לא התקבלה החלטה עד סוף המשחק, ולכן הדבר נחשב לפשיטה", CauseText.Line(raid, c, NoRows, he, names), StringComparison.Ordinal));
    }

    [Test]
    public void EveryRemainingKeyPreservesEnglishAndFormatsHebrewIncludingLargeCounts()
    {
        var c = RemainingFixture(); var en = En; var he = He;
        var names = new Dictionary<string, string> { ["town"] = "עיר" };
        var rows = RemainingRows();
        foreach (var row in rows)
        {
            Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, en), row.Key);
            AssertHebrew(CauseText.Line(row, c, NoRows, he, names), row.Key);
        }
        CollectionAssert.AreEquivalent(CauseKeys.All.Except(new[] {
            CauseKeys.MoneyFlows, CauseKeys.FxFlows, CauseKeys.Borrowed, CauseKeys.Paid, CauseKeys.MoneyOther, CauseKeys.CivilianUpkeep,
            CauseKeys.FxCrisisBegan, CauseKeys.FxCrisisEased, CauseKeys.FxCrisisFood, CauseKeys.Arrived,
            CauseKeys.EffectChange, CauseKeys.SituationBegan, CauseKeys.SituationEnded, CauseKeys.RungChanged,
            CauseKeys.CallUpSet, CauseKeys.CallUpRaised, CauseKeys.CallUpLowered, CauseKeys.Ceasefire,
            CauseKeys.EventAmount, CauseKeys.EventChosen, CauseKeys.EventCity, CauseKeys.EventDelegated,
            CauseKeys.EventDelegatedPartial, CauseKeys.EventGrant, CauseKeys.EventNew, CauseKeys.EventPolicy,
            CauseKeys.OperationPostponed, CauseKeys.OperationLapsed, CauseKeys.OperationLapsedSigned, CauseKeys.OperationLapsedUnitLost,
            CauseKeys.OperationWaitsForArmistice,
            CauseKeys.EventRejoin, CauseKeys.EventSetRung, CauseKeys.EventStock, CauseKeys.EventUnlock,
            CauseKeys.MilitaryUpkeep, CauseKeys.HousingSurcharge, CauseKeys.HousingCohesion,
            CauseKeys.ObjectiveCompleted, CauseKeys.PrisonersReturned, CauseKeys.SoldiersReturned,
            CauseKeys.FieldFood }), rows.Select(x => x.Key).Distinct(), "all remaining keys");   // FieldFood (#2471): only the gdd-0.3 field fixture makes it, no turn yet, so no wording yet ("Per field, words later (Recommended)")
        var appointed = rows.Single(x => x.Key == CauseKeys.Appointed);
        StringAssert.Contains("התפקיד שנשמר", CauseText.Line(appointed, c, NoRows, he, names), "historical title, not current title");
    }

    // #3020 (#2975): Send home's Arms line on a Historical ledger game names the city, the unit and the Arms back, in English
    // as the sim's own message and in Hebrew as why.cause.training_arms_returned does, with the city's Hebrew name.
    [Test]
    public void SentHomeArmsReturnedNamesTheCityTheUnitAndTheArms()
    {
        var c = RemainingFixture();
        var names = new Dictionary<string, string> { ["town"] = "עיר" };
        var row = new Cause("city", "arms", 3, "Town: unit 42 returned 3 Arms", key: CauseKeys.SentHomeArmsReturned, args: new[] { "town", "42" });
        Assert.IsTrue(string.Equals("{0}: unit {1} returned {2} Arms", En["why.cause.sent_home_arms_returned"], StringComparison.Ordinal));
        Assert.IsTrue(string.Equals(row.Message, CauseText.Line(row, c, NoRows, En), StringComparison.Ordinal));
        var he = CauseText.Line(row, c, NoRows, He, names);
        AssertHebrew(he, row.Key);
        Assert.IsTrue(string.Equals(He.Format("why.cause.sent_home_arms_returned", "עיר", "42", 3.0), he, StringComparison.Ordinal), he);
        foreach (var part in new[] { "עיר", "יחידה", "42", "3" })
            Assert.GreaterOrEqual(he.IndexOf(part, StringComparison.Ordinal), 0, part);
    }

    [Test]
    public void RemainingOptionalBranchesKeepExactEnglishAndResidentSnapshots()
    {
        var c = RemainingFixture(); var en = En; var he = He;
        var names = new Dictionary<string, string> { ["town"] = "עיר" };
        var rows = new[]
        {
            new Cause("draft", "town", 0, "Town is captured: Israeli units hold it and no enemy unit is there. It awaits a decision", key: CauseKeys.PlaceCaptured, args: new[] { "0" }),
            new Cause("draft", "town", 0, "Town is under enemy control again: enemy units hold it and no Israeli unit is there", key: CauseKeys.EnemyRegained, args: new[] { "0" }),
            new Cause("draft", "town", 0, "Town is annexed. Its residents join the population", key: CauseKeys.PlaceAnnexed, args: new[] { "0" }),
            new Cause("draft", "town", 0, "Town is under enemy control again. Its residents are unchanged", key: CauseKeys.PlaceWithdrawn, args: new[] { "0", "0" }),
            new Cause("draft", "town", 0, "Town: the occupation period has ended. It awaits a decision", key: CauseKeys.OccupationCountdown),
            new Cause("draft", "office", 0, "Person appointed Office", key: CauseKeys.Appointed, args: new[] { "person", "התפקיד שנשמר", "" }),
            new Cause("draft", "coalition_stability", -0.025, "Coalition stability -2.5% (Former resents the reshuffle)", key: CauseKeys.Reshuffle, args: new[] { "", "former", "same", "Office", "התפקיד שנשמר" }),
            new Cause("draft", "town", -1, "Town: 1 group began armoured car training, cost IL\u00A01.3m", key: CauseKeys.TrainingStarted, args: new[] { "1", "armour", "", "1.25" }),
            new Cause("draft", "site", 1, "Site: a group of halutzim began draining the swamp, cost IL\u00A01.3m", key: CauseKeys.LandWorkStarted, args: new[] { "drain", "1.25" }),
            new Cause("draft", "site", 1, "Site: a group of halutzim began building a training camp, cost IL\u00A01.3m", key: CauseKeys.SiteStarted, args: new[] { "camp", "1.25" }),
            new Cause("draft", "town", 0, "Town: an arms workshop's next cycle waits: paying for it would take the debt past its ceiling", key: CauseKeys.WorkshopPaused, args: new[] { Workshops.DebtCeiling }),   // #1701 OQ4
            new Cause("draft", "town", 0, "Town: Housing waits: no person without a job is left for its builder", key: CauseKeys.ProjectWaiting, args: new[] { "housing", Projects.NoWorker }),   // #1700
        };
        // A renderer receives no live state: both resident variants must survive the settlement record's removal.
        foreach (var row in rows)
        {
            Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, en), row.Key);
            AssertHebrew(CauseText.Line(row, c, NoRows, he, names), row.Key);
        }
        var stayed = rows.Single(x => x.Key == CauseKeys.PlaceWithdrawn);
        StringAssert.Contains("מצב התושבים לא השתנה", CauseText.Line(stayed, c, NoRows, he, names));
        foreach (var verb in new[] { "built", "plowed", "drained", "founded" })
        {
            var row = new Cause("draft", "site", 1, "Site " + verb, key: CauseKeys.SiteCompleted, args: new[] { verb });
            Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, en));
            AssertHebrew(CauseText.Line(row, c, NoRows, he), row.Key);
        }
    }

    /// <summary>#1701: the Why screen (WhyPresenter.Show) words every arms workshop cause from why.cause.&lt;key&gt; with the city
    /// named, in both languages; a workshop key outside CauseText's remaining set fell to UnitNames.Line and threw on a
    /// missing why.line.&lt;key&gt; (the coordinator's Unity run at 7cbd257b6).</summary>
    [Test]
    public void EveryWorkshopCauseIsWordedFromItsWhyCauseKeyOnTheWhyScreen()
    {
        var c = RemainingFixture(); var en = En; var he = He;
        var names = new Dictionary<string, string> { ["town"] = "עיר" };
        var rows = new (Cause cause, string key, string[] extra)[]
        {
            (new Cause("city", "town", 2, "Town: arms workshops staffed: 2", key: CauseKeys.WorkshopWorkers, args: new[] { "2" }), "why.cause.workshop_workers", new[] { "2" }),
            (new Cause("city", "town", 1, "Town: an arms workshop made 1 Arms", key: CauseKeys.WorkshopArms), "why.cause.workshop_arms", new string[0]),
            (new Cause("city", "town", 0, "Town: an arms workshop has no worker without a job this month", key: CauseKeys.WorkshopPaused, args: new[] { Workshops.NoWorker }), "why.cause.workshop_paused.no_worker", new string[0]),
            (new Cause("city", "town", 0, "Town: an arms workshop's next cycle waits: paying for it would take the debt past its ceiling", key: CauseKeys.WorkshopPaused, args: new[] { Workshops.DebtCeiling }), "why.cause.workshop_paused.debt_ceiling", new string[0]),
        };
        foreach (var (cause, key, extra) in rows)
            foreach (var (text, town) in new[] { (en, "Town"), (he, "עיר") })
            {
                string line = "";
                Assert.DoesNotThrow(() => line = CauseText.Line(cause, c, NoRows, text, names), key);
                Assert.AreEqual(text.Format(key, new object[] { town }.Concat(extra).ToArray()), line, key);
            }
    }

    [Test]
    public void RemainingRowsPreserveTheWholeEnglishReportInBothLoops()
    {
        foreach (var c in new[] { C, SimBridgeGddTests.Legacy })
        {
            var state = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
            for (var turn = 0; turn < 1000 && state.GameOver == null; turn++)
            {
                var result = Simulation.Step(c, state, GoldenRun.Orders(c, state));
                foreach (var row in result.Why.Where(x => CauseKeys.All.Contains(x.Key)))
                    Assert.AreEqual(row.Message, CauseText.Line(row, c, NoRows, En), row.Key);
                state = result.State;
            }
            Assert.IsNotNull(state.GameOver);
        }
    }
}