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.

47.3 KB
Raw Blame
#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map.Units;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;

/// <summary>The turn report (#1037): after End Turn, each top-bar number that changed, with the change the bar shows and its
/// main causes, which are the sim's own cause messages (StepResult.Why). The fixed turn is the opening one: GoldenRun.Seed,
/// Historical, no orders, so One Army goes to its minister.</summary>
public class TurnReportTests
{
    static readonly Content C = ContentLoader.Load(Paths.Content);
    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 HUD, the screens' navigation, the Why screen, the decision card and the report on Game.uxml.</summary>
    sealed class Kit : System.IDisposable
    {
        public readonly UiTestKit Ui = new UiTestKit();
        public readonly SimBridge Bridge; public readonly ScreenNav Nav; public readonly EventCardPresenter Card; public readonly TurnReportPresenter Report;
        readonly List<System.IDisposable> owned = new List<System.IDisposable>();

        public Kit(UiText text, System.Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null)
        {
            Bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text, step);
            owned.Add(new HudPresenter(Ui.Root, Bridge, text));
            owned.Add(Nav = new ScreenNav(Ui.Root));
            owned.Add(new WhyPresenter(Ui.Root, Bridge, text));
            owned.Add(Card = new EventCardPresenter(Ui.Root, Bridge, text, null));
            owned.Add(Report = new TurnReportPresenter(Ui.Root, Bridge, text, Nav));
        }

        public VisualElement Q(string name) => Ui.Q<VisualElement>(name);

        public void Dispose()
        {
            for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
            Ui.Dispose();
        }
    }

    /// <summary>A row's causes, one label each, in order.</summary>
    static List<string> Causes(UiTestKit ui, string meter) =>
        ui.Q<VisualElement>("turn-report-causes-" + meter).Query<Label>(className: "turn-report-cause").ToList().Select(l => l.text).ToList();

    /// <summary>The main B1 occupation/deport keys use the real map names in report and meter paths too: the cost's Money
    /// line (occupation: PayOrBorrow's Paid line; Deport: its own line, as SettlementControl writes it), and the borrowing
    /// line's own wording. Borrowing is not a Money cause (#2199), so the meter shows the cost's line.
    /// This is only a formatter fixture: it does not enable or execute the disabled Deport command.</summary>
    [TestCase(CauseKeys.Purpose.Occupation)]
    [TestCase(CauseKeys.Purpose.Deport)]
    public void ReportAndMeterCausesUseSourcedHebrewPlacesAndKeepEnglishFallback(string purpose)
    {
        const string city = "tel_aviv";
        var namesHe = Statecraft.Game.Map.SettlementPlacer.Parse(
            File.ReadAllText(Path.Combine(Paths.Content, "map", "settlements_1948.yaml")))
            .ToDictionary(s => s.Id, s => s.NameHe);
        Assert.IsTrue(namesHe.ContainsKey(city) && namesHe[city] != "", "sourced map name required");
        using var k = new Kit(He);
        k.Bridge.EndTurn();
        var last = k.Bridge.Session.Last!;
        var why = new List<Cause>();
        var placeName = PlayerText.Settlement(C, city);
        var englishPurpose = purpose == CauseKeys.Purpose.Deport ? $"for the Deport of {placeName}" : $"for the occupation of {placeName}";
        var cost = last.State.Treasury + 3;
        if (purpose == CauseKeys.Purpose.Occupation)
            EconomySystem.PayOrBorrow(C, last.State, cost, englishPurpose, why, purpose, city);
        else
        {
            why.Add(new Cause("economy", "treasury", -cost, $"{PlayerText.Change(C, "treasury", -cost)} (Deport of {placeName})", key: CauseKeys.DeportCost, args: new[] { city }));
            EconomySystem.PayNamedOrBorrow(C, last.State, cost, englishPurpose, why, purpose, city);
        }
        Assert.AreEqual(2, why.Count, "the cost's Money line, then the borrowing");
        var cause = why[1];
        Assert.AreEqual(CauseKeys.Borrowed, cause.Key);
        // Existing TurnReportTests uses this setter for a precise report fixture; no simulation input or content is changed.
        typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(k.Bridge.Session,
            new StepResult(last.State, why, last.Rejected));
        var reportLines = TurnReportPresenter.Lines(k.Bridge, He, null, namesHe)
            .Single(row => row.Meter == "treasury").Causes;
        using var tip = new MeterTip(k.Ui.Root, k.Bridge, He, System.Array.Empty<VisualElement>()) { TownNamesHe = namesHe };
        var meterLines = tip.Lines(k.Q("meter-treasury")).causes;
        foreach (var lines in new[] { reportLines, meterLines })
        {
            Assert.IsNotEmpty(lines);
            var line = string.Join("\n", lines);
            StringAssert.Contains(namesHe[city], line);
            StringAssert.DoesNotContain(placeName, line);
            Assert.IsTrue(UiDirection.RightToLeft(line));
        }
        Assert.AreEqual(cause.Message, CauseText.Line(cause, C, System.Array.Empty<UnitEntry>(), En, namesHe));
        var missingNames = new Dictionary<string, string>();
        StringAssert.Contains(placeName, CauseText.Line(cause, C, System.Array.Empty<UnitEntry>(), He, missingNames),
            "missing name_he retains main's English fallback, never an invented translation");
    }

    [Test]
    public void TheFixedTurnReportsEachChangedNumberWithTheSimsOwnCauses()
    {
        using var k = new Kit(En);
        Assert.IsFalse(k.Report.IsOpen, "no report before a turn");
        var turn = k.Bridge.EndTurn();
        Assert.IsTrue(k.Report.IsOpen, "End Turn opens the report");
        Assert.AreEqual(DisplayStyle.Flex, k.Q("turn-report").style.display.value);

        var m = HudModel.From(k.Bridge, En);
        var changed = HudModel.MeterIds.Where(id => m.For(id).Delta.Length > 0).ToArray();
        Assert.GreaterOrEqual(changed.Length, 3, "the opening turn moves at least three numbers in the bar");
        var rows = k.Ui.Q<ScrollView>("turn-report-rows").Children().ToList();
        CollectionAssert.AreEqual(changed.Select(id => "turn-report-" + id).Concat(new[] { "turn-report-food", "turn-report-arms" }).Append("turn-report-" + TurnReportPresenter.EnemyRow), rows.Select(r => r.name),
            "every changed bar number, then Food and Arms stocks, then enemy orders (#1293)");
        var messages = new HashSet<string>(turn.Why.Select(w => w.Message));
        foreach (var id in changed)
        {
            // The heading is the bar's caption and the very change the bar shows next to the number.
            var heading = k.Ui.Q<Label>("turn-report-heading-" + id).text;
            var expectedHeading = id == "immigration"
                ? En.Format("report.immigration_line", En["hud.caption.immigration"], k.Ui.Q<Label>("immigration-delta").text,
                    k.Ui.Q<Label>("immigration-value").text)
                : En.Format("report.line", En["hud.caption." + id], k.Ui.Q<Label>(id + "-delta").text);
            Assert.AreEqual(expectedHeading, heading, id);
            var causes = k.Ui.Root.Q("turn-report-causes-" + id);
            var expected = HudModel.Causes(turn, id, C, w => CauseText.Line(w, C, System.Array.Empty<UnitEntry>(), En));
            if (expected.Count == 0) { Assert.IsNull(causes, id + ": no cause line without a cause"); continue; }
            var lines = Causes(k.Ui, id);
            CollectionAssert.AreEqual(expected, lines, id);
            Assert.LessOrEqual(lines.Count, HudModel.MaxCauses + (id == "treasury" ? 1 : 0), id);   // Money's Other line (#2212)
            foreach (var line in lines.Take(HudModel.MaxCauses)) Assert.IsTrue(messages.Contains(line), $"{id}: '{line}' is a cause of StepResult.Why, word for word");
        }
        // The fixed turn's own causes, the larger first and at most MaxCauses (2): Security moved by One Army and the
        // defence of Degania, the same size, in the order the cards came (R-EVT-006); the border villages' smaller effect
        // (the second line before #1565) is left out.
        var security = Causes(k.Ui, "security");
        CollectionAssert.AreEqual(new[] { "Security +1.5% (One Army)", "Security +1.5% (The Defence of Degania)" }, security);
        StringAssert.StartsWith("Money ", Causes(k.Ui, "treasury")[0], "Money's main cause is the economy's line");
        // #2212: Money's two largest causes, then one Other line for the rest (EconomySystem.OtherMoney), so the lines add
        // up to the change the heading shows.
        var money = Causes(k.Ui, "treasury");
        var shown = new List<Cause>();
        HudModel.Causes(turn, "treasury", C, w => { shown.Add(w); return ""; });
        Assert.AreEqual(HudModel.MaxCauses + 1, money.Count, "the opening turn has more Money causes than the two shown");
        Assert.AreEqual(CauseKeys.MoneyOther, shown[shown.Count - 1].Key);
        Assert.AreEqual(shown[shown.Count - 1].Message, money[money.Count - 1]);
        StringAssert.EndsWith(" (other causes)", money[money.Count - 1]);
        var s = k.Bridge.State; var prev = k.Bridge.Session.Previous!;
        Assert.AreEqual((s.Treasury - s.Debt) - (prev.Treasury - prev.Debt), shown.Sum(w => w.Delta), 1e-9, "the lines add up to the Money (net) change");
        Assert.IsNull(k.Ui.Root.Q("turn-report-causes-support"), "no cause names Public support (an average of the indicators)");
    }

    /// <summary>#2576 shape (b): Immigration keeps the change in arrivals as the report's number, while the current
    /// arrival count and the population lines below it are labelled as this turn's arrivals, in both UI languages.</summary>
    [Test]
    public void ImmigrationReportsTheChangeAndLabelsThisTurnsArrivalsInBothLanguages()
    {
        foreach (var (text, heading, causesHeading, cause) in new[]
        {
            (En, "Immigration: change +20; arrivals this turn: 120", "Main arrivals this turn:", "120 immigrants arrived (Asia)"),
            (He, "עלייה: שינוי של +20; עולים שהגיעו בתור הזה: 120", "הגעות עיקריות בתור הזה:", "עולים שהגיעו (אסיה): 120"),
        })
        {
            var arrivals = new Queue<double>(new[] { 100d, 120d, 100d });
            using var k = new Kit(text, (g, cmds) =>
            {
                var result = g.EndTurn(cmds);
                var n = arrivals.Dequeue();
                var arrival = new Cause("population", "asia", n,
                    System.FormattableString.Invariant($"{n:N0} immigrants arrived (Asia)"), key: CauseKeys.Arrived);
                var controlled = new StepResult(result.State,
                    result.Why.Where(w => w.System != "population").Concat(new[] { arrival }).ToList(), result.Rejected);
                typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(g, controlled);
                return controlled;
            });

            k.Bridge.EndTurn();
            k.Bridge.EndTurn();

            var meter = HudModel.From(k.Bridge, text).Immigration;
            Assert.AreEqual(text.Format("hud.people", 120), meter.Value);
            Assert.AreEqual(text.Format("hud.delta_people", 20), meter.Delta);
            var plain = k.Ui.Q<Label>("turn-report-heading-immigration").text.Replace(UiText.LeftToRightMark.ToString(), "");
            Assert.AreEqual(heading, plain);
            var reportCauses = Causes(k.Ui, "immigration");
            CollectionAssert.AreEqual(new[] { cause }, reportCauses.Select(x => x.Replace(UiText.LeftToRightMark.ToString(), "")).ToList());

            using var tip = new MeterTip(k.Ui.Root, k.Bridge, text, System.Array.Empty<VisualElement>());
            var tipLines = tip.Lines(k.Q("meter-immigration"));
            Assert.AreEqual(causesHeading, tipLines.words.Split('\n').Last());
            CollectionAssert.AreEqual(reportCauses, tipLines.causes, "the report and MeterTip label the same current-turn arrivals");

            // A fall: 120 then 100 reads as a change of -20 beside this turn's 100 arrivals.
            k.Bridge.EndTurn();
            var fell = text.Format("report.immigration_line", text["hud.caption.immigration"], text.Format("hud.delta_people", -20),
                text.Format("hud.people", 100)).Replace(UiText.LeftToRightMark.ToString(), "");
            Assert.AreEqual(fell, k.Ui.Q<Label>("turn-report-heading-immigration").text.Replace(UiText.LeftToRightMark.ToString(), ""));
        }
    }

    /// <summary>#1293: the opening turn's enemy orders (R-ENEMY-001): the four scripted forces march (R-ENEMY-002) and the
    /// others fortify (R-ENEMY-003). After the bar's numbers the report lists each order, in the sim's order, its unit named
    /// by its units_1948.yaml row, in the player's language.</summary>
    [Test]
    public void TheEnemysOrdersAreReportedInBothLanguages()
    {
        var rows = UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        foreach (var hebrew in new[] { false, true })
        {
            var text = hebrew ? He : En;
            using var k = new Kit(text);
            k.Report.Units = rows;
            var turn = k.Bridge.EndTurn();
            var orders = turn.Why.Where(w => w.EnemyOrder != "").ToList();
            CollectionAssert.IsSupersetOf(orders.Select(w => w.EnemyOrder), new[] { Movement.Kind, Orders.Fortify }, "the opening turn has enemy moves and fortifies");
            var expected = orders.Select(w =>
            {
                var row = rows.First(u => u.Id == C.StartingForces[int.Parse(w.Target, System.Globalization.CultureInfo.InvariantCulture)].Row);
                return text.Format("report.enemy_" + w.EnemyOrder, hebrew ? row.NameHe : row.Name);
            }).ToList();
            Assert.AreEqual(text["report.enemy"], k.Ui.Q<Label>("turn-report-heading-" + TurnReportPresenter.EnemyRow).text);
            var lines = Causes(k.Ui, TurnReportPresenter.EnemyRow);
            CollectionAssert.AreEqual(expected, lines);
            CollectionAssert.Contains(lines, hebrew ? "הלגיון הערבי עבר לעמדה חדשה" : "Arab Legion moved to a new position", "the Legion's march on Latrun");
        }
    }

    /// <summary>Each settlement's Hebrew name by id, from the map's own rows.</summary>
    static Dictionary<string, string> NamesHe() => Statecraft.Game.Map.SettlementPlacer.Parse(
        File.ReadAllText(Path.Combine(Paths.Content, "map", "settlements_1948.yaml"))).ToDictionary(s => s.Id, s => s.NameHe);

    /// <summary>A kit whose opening turn runs as usual and whose result then gets <paramref name="added"/> through
    /// Session.Last's private setter (as AnAttackThatNamesNoAttackersGivesNoLine does), before the report reads it. The real
    /// content is gdd-0.1, which has no workshop, so the workshop causes are added; that the sim gives them under gdd-0.3 only
    /// is ArmsWorkshopTests.Gdd01RunsNoWorkshopCycle's.</summary>
    static Kit EndTurnWith(UiText text, IReadOnlyList<Cause> added, IReadOnlyDictionary<string, string> namesHe)
    {
        var k = new Kit(text, (g, cmds) =>
        {
            var r = g.EndTurn(cmds);
            var result = new StepResult(r.State, r.Why.Concat(added).ToList(), r.Rejected);
            typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(g, result);
            return result;
        });
        k.Report.TownNamesHe = namesHe;
        k.Bridge.EndTurn();
        return k;
    }

    static Cause Made(string city) => new Cause("city", city, 1, city + ": an arms workshop made 1 Arms", key: CauseKeys.WorkshopArms);
    static Cause Paused(string city, string why) => new Cause("city", city, 0, city + ": an arms workshop waits", key: CauseKeys.WorkshopPaused, args: new[] { why });

    /// <summary>#1701 A1 (owner, 2 November 2026: "Yes, in the panel (Recommended)"; the option: "The turn-report panel shows
    /// 'Workshop in &lt;city&gt;: +1 Arms' and 'Workshop in &lt;city&gt; paused: debt ceiling'."): the sim's workshop causes
    /// (R-ARMS-006) get their own row after the stocks, in the sim's order, the city named in the player's language. A city
    /// with one such cause keeps the A1 wording. A no-worker pause is not one of the ruled lines and stays on the Why screen.
    /// The expected lines are literals in both languages, not the keys formatted again.</summary>
    [Test]
    public void TheWorkshopsArmsAndCeilingPauseAreReportedInBothLanguages()
    {
        var namesHe = NamesHe();
        var added = new[] { Made("tel_aviv"), Paused("haifa", Workshops.NoWorker), Paused("haifa", Workshops.DebtCeiling) };
        foreach (var hebrew in new[] { false, true })
        {
            using var k = EndTurnWith(hebrew ? He : En, added, namesHe);
            k.Q("turn-report-" + TurnReportPresenter.WorkshopRow);   // asserts the row's own name, which the no-row test queries
            Assert.AreEqual(hebrew ? "סדנאות נשק" : "Arms workshops", k.Ui.Q<Label>("turn-report-heading-" + TurnReportPresenter.WorkshopRow).text);
            CollectionAssert.AreEqual(hebrew
                    ? new[] { "סדנת נשק (תל אביב): תוספת נשק: 1", "סדנת נשק (חיפה) בהמתנה: תקרת החוב" }
                    : new[] { "Workshop in Tel Aviv: +1 Arms", "Workshop in Haifa paused: debt ceiling" },
                Causes(k.Ui, TurnReportPresenter.WorkshopRow), "the owner's ruled wording");
        }
    }

    /// <summary>#1701 A1 follow-up (owner, 2 November 2026: "Combine per city (Recommended)"; the option: "'Workshops in Tel
    /// Aviv (6): +6 Arms'; pauses likewise combined with a count."): a city's workshop Arms are one line with their count, and
    /// so are its ceiling pauses, in the order each first appears among the sim's causes; a city with one keeps the A1 line.
    /// The count is the number of the sim's causes, which each give 1 Arms (R-ARMS-006). Hebrew puts the count in brackets
    /// after the city's name, as English does, and the Arms as "Label: N" (HE-04), each number between left-to-right marks
    /// as UiText.Format puts it.</summary>
    [Test]
    public void AnotherWorkshopInTheSameCityJoinsItsLine()
    {
        var namesHe = NamesHe();
        var added = new[]
        {
            Paused("haifa", Workshops.DebtCeiling), Made("tel_aviv"), Paused("haifa", Workshops.DebtCeiling), Made("haifa"),
            Made("tel_aviv"), Made("tel_aviv"), Paused("haifa", Workshops.NoWorker),
        };
        foreach (var hebrew in new[] { false, true })
        {
            using var k = EndTurnWith(hebrew ? He : En, added, namesHe);
            CollectionAssert.AreEqual(hebrew
                    ? new[]
                    {
                        "סדנאות נשק (חיפה) (‎2‎) בהמתנה: תקרת החוב",
                        "סדנאות נשק (תל אביב) (‎3‎): תוספת נשק: ‎3‎",
                        "סדנת נשק (חיפה): תוספת נשק: 1",
                    }
                    : new[] { "Workshops in Haifa (2) paused: debt ceiling", "Workshops in Tel Aviv (3): +3 Arms", "Workshop in Haifa: +1 Arms" },
                Causes(k.Ui, TurnReportPresenter.WorkshopRow));
        }
    }

    /// <summary>#1701 A1: a turn whose only workshop cause is a no-worker pause (on the Why screen only) has no workshop row,
    /// so the filter, not the content, keeps the row out.</summary>
    [Test]
    public void ANoWorkerPauseAloneGivesNoWorkshopRow()
    {
        using var k = EndTurnWith(En, new[] { Paused("haifa", Workshops.NoWorker) }, NamesHe());
        Assert.IsTrue(k.Bridge.Session.Last!.Why.Any(w => w.Key == CauseKeys.WorkshopPaused), "the pause is in the turn");
        Assert.IsNotEmpty(k.Ui.Q<ScrollView>("turn-report-rows").Children().ToList(), "the report has its other rows");
        Assert.IsNull(k.Ui.Root.Q("turn-report-" + TurnReportPresenter.WorkshopRow), "no workshop row");
        Assert.IsNull(k.Ui.Root.Q("turn-report-heading-" + TurnReportPresenter.WorkshopRow), "no workshop heading");
    }

    static Cause Held(string city) => new Cause("city", city, 0, city + ": held by the enemy; no job income or project work this turn", key: CauseKeys.CityHeld);

    /// <summary>R-CITY-010 (#1711): a city the enemy holds changes no number, so its sim line (Delta 0) gets a row of its own
    /// after the stocks and before the enemy's orders, one line a city in the sim's order, named in the player's language.
    /// The real content is gdd-0.1, which holds no city, so the lines are added; that the sim gives them under gdd-0.3 only is
    /// NoCityLossDefeatTests.OnlyAGdd03HeldCityGetsTheLine's. The expected lines are literals in both languages.</summary>
    [Test]
    public void HeldCitiesAreReportedInBothLanguages()
    {
        var namesHe = NamesHe();
        foreach (var hebrew in new[] { false, true })
        {
            using var k = EndTurnWith(hebrew ? He : En, new[] { Held("tel_aviv"), Held("haifa") }, namesHe);
            Assert.AreEqual(hebrew ? "ערים בשליטת האויב" : "Cities held by the enemy",
                k.Ui.Q<Label>("turn-report-heading-" + TurnReportPresenter.HeldRow).text);
            CollectionAssert.AreEqual(hebrew
                    ? new[]
                    {
                        "תל אביב: בשליטת האויב: אין הכנסה מעבודה ואין עבודה על מיזמים בתור הזה",
                        "חיפה: בשליטת האויב: אין הכנסה מעבודה ואין עבודה על מיזמים בתור הזה",
                    }
                    : new[]
                    {
                        "Tel Aviv: held by the enemy; no job income or project work this turn",
                        "Haifa: held by the enemy; no job income or project work this turn",
                    },
                Causes(k.Ui, TurnReportPresenter.HeldRow));
            var rows = k.Ui.Q<ScrollView>("turn-report-rows").Children().Select(r => r.name).ToList();
            int held = rows.IndexOf("turn-report-" + TurnReportPresenter.HeldRow);
            Assert.Greater(held, rows.IndexOf("turn-report-arms"), "after the stocks");
            Assert.AreEqual(rows.IndexOf("turn-report-" + TurnReportPresenter.EnemyRow), held + 1, "just before the enemy's orders");
        }
    }

    /// <summary>R-ENEMY-007 (#2543): a postponed or lapsed operation changes no number (Delta 0), but the rule says the turn
    /// report names the units and why, so its lines get a row of their own, before the held cities, in the sim's order and
    /// the player's language. The lines are the sim's own, from Operation Horev delegated with Golani out of place, then lapsed.
    /// Red without the row: the report has no operations row and the lines are only on the Why screen.</summary>
    [Test]
    public void PostponedAndLapsedOperationsAreReportedInBothLanguages()
    {
        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);
        s.Date = e.To!.Value; s.Turn += C.Rules.Mvp!.OperationWaitTurns!.Value + 1; EventSystem.LapseExpiredOperations(C, s, why);   // after its wait (R-ENEMY-007)
        var added = why.Where(w => w.Key == CauseKeys.OperationPostponed || w.Key == CauseKeys.OperationLapsed).ToList();
        Assert.AreEqual(new[] { CauseKeys.OperationPostponed, CauseKeys.OperationLapsed }, added.Select(w => w.Key).ToArray());
        var rows = UnitData.Parse(System.IO.File.ReadAllText(System.IO.Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        foreach (var hebrew in new[] { false, true })
        {
            var text = hebrew ? He : En;
            using var k = new Kit(text, (g, cmds) =>
            {
                var r = g.EndTurn(cmds);
                var result = new StepResult(r.State, r.Why.Concat(added).ToList(), r.Rejected);
                typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(g, result);
                return result;
            });
            k.Report.Units = rows;
            k.Bridge.EndTurn();
            Assert.AreEqual(hebrew ? "מבצעים צבאיים" : "Military operations",
                k.Ui.Q<Label>("turn-report-heading-" + TurnReportPresenter.OperationsRow).text);
            CollectionAssert.AreEqual(added.Select(w => CauseText.Line(w, C, rows, text)).ToList(), Causes(k.Ui, TurnReportPresenter.OperationsRow));
            StringAssert.Contains(hebrew ? "חטיבת גולני" : "Golani Brigade", Causes(k.Ui, TurnReportPresenter.OperationsRow)[0]);
            var order = k.Ui.Q<ScrollView>("turn-report-rows").Children().Select(r => r.name).ToList();
            Assert.Greater(order.IndexOf("turn-report-" + TurnReportPresenter.OperationsRow), order.IndexOf("turn-report-arms"), "after the stocks");
        }
    }

    /// <summary>R-CITY-010 (#1711): a turn with no held city has no held row.</summary>
    [Test]
    public void ATurnWithNoHeldCityGivesNoHeldRow()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();
        Assert.IsTrue(k.Report.IsOpen, "the report has its other rows");
        Assert.IsNull(k.Ui.Root.Q("turn-report-" + TurnReportPresenter.HeldRow), "no held row");
    }

    /// <summary>#1297: a standing enemy attack (R-ENEMY-003) is reported on every turn it engages, not only on the turn it is
    /// ordered. The opening turn is set up as a later one: the Arab Liberation Army already attacks Golani's hex, which it keeps
    /// (no order is given this turn) and which engages in step 2 (R-COMBAT-002).</summary>
    [Test]
    public void AStandingEnemyAttackIsReportedOnATurnItIsNotOrdered()
    {
        var rows = UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        int golani = C.StartingForces.ToList().FindIndex(f => f.Row == "golani"), ala = C.StartingForces.ToList().FindIndex(f => f.Row == "arab_liberation_army");
        foreach (var hebrew in new[] { false, true })
        {
            var text = hebrew ? He : En;
            using var k = new Kit(text);
            k.Report.Units = rows;
            var s = k.Bridge.Session.State; var g = s.Units[golani]; var a = s.Units[ala];
            s.Units[golani] = new Unit(g.Id, g.Type, a.Q, a.R - 1, g.Service, g.Side, 1);   // next to the ALA, weak enough to attack
            s.Units[ala] = new Unit(a.Id, a.Type, a.Q, a.R, a.Service, a.Side, a.Strength, Combat.Attack, $"{a.Q},{a.R - 1}");
            var turn = k.Bridge.EndTurn();
            Assert.IsFalse(turn.Why.Any(w => w.Message.StartsWith($"Unit {ala} will attack")), "the attack stands: no order this turn");
            Assert.IsTrue(turn.Why.Any(w => w.Message.StartsWith($"The attack on hex {a.Q},{a.R - 1}")), "and it engages");
            var lines = Causes(k.Ui, TurnReportPresenter.EnemyRow);
            CollectionAssert.Contains(lines, hebrew ? "צבא ההצלה פתח בהתקפה על אחת היחידות שלכם" : "Arab Liberation Army launched an attack on one of your units");
        }
    }

    /// <summary>#1297 review: an attack cause's Target is a hex ("q,r"), not a unit, so one that names no attackers gives no
    /// line rather than a parse that throws. Combat fills the attackers for every enemy engagement today, so the turn is
    /// replaced with one such cause through Session.Last's private setter.</summary>
    [Test]
    public void AnAttackThatNamesNoAttackersGivesNoLine()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();
        var last = k.Bridge.Session.Last!;
        typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(k.Bridge.Session,
            new StepResult(last.State, new[] { new Cause("map", "3,0", 0, "The attack on hex 3,0", Combat.Attack) }, last.Rejected));
        Assert.IsFalse(TurnReportPresenter.Lines(k.Bridge, En).Any(l => l.Meter == TurnReportPresenter.EnemyRow));
    }

    /// <summary>#2534 review (#2538): a new enemy attack order that also engages on its turn names the attacker once in the
    /// enemy-orders row, not twice - the order's cause and the engagement's both carry the unit. The turn is replaced with
    /// both causes through Session.Last's private setter, as in AnAttackThatNamesNoAttackersGivesNoLine.</summary>
    [Test]
    public void ANewAttackOrderThatEngagesNamesTheAttackerOnce()
    {
        var rows = UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
        int ala = C.StartingForces.ToList().FindIndex(f => f.Row == "arab_liberation_army");
        foreach (var hebrew in new[] { false, true })
        {
            var text = hebrew ? He : En;
            using var k = new Kit(text);
            var a = k.Bridge.Session.State.Units[ala];
            var order = new Cause("map", ala.ToString(System.Globalization.CultureInfo.InvariantCulture), 0, $"Unit {ala} will attack hex 3,0",
                Combat.Attack, new[] { ala }, WhyKeys.AttackOrdered, new[] { new UnitRef(a) });
            var engagement = new Cause("map", "3,0", 0, "The attack on hex 3,0",
                Combat.Attack, new[] { ala }, WhyKeys.Engagement, new[] { new UnitRef(a) });
            k.Bridge.EndTurn();
            var last = k.Bridge.Session.Last!;
            typeof(GameSession).GetProperty(nameof(GameSession.Last))!.SetValue(k.Bridge.Session,
                new StepResult(last.State, new[] { order, engagement }, last.Rejected));
            var row = TurnReportPresenter.Lines(k.Bridge, text, rows).Single(l => l.Meter == TurnReportPresenter.EnemyRow);
            CollectionAssert.AreEqual(
                new[] { hebrew ? "צבא ההצלה פתח בהתקפה על אחת היחידות שלכם" : "Arab Liberation Army launched an attack on one of your units" },
                row.Causes, "one line for the unit, though the order and the engagement both name it");
        }
    }

    /// <summary>#2527 review: the Food shortage's line is informational (delta 0), and the turn report's Food row still
    /// names it, after the lines that have a number.</summary>
    [Test]
    public void AShortageTurnStillNamesTheShortageInTheFoodRow()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();
        var last = k.Bridge.Session.Last!;
        var shortage = new Cause("economy", "food", 0, "Food ran out: 60 of 100 units of the month's need went unmet",
            key: CauseKeys.FoodShortage, args: new[] { "60", "100" });
        var import = new Cause("economy", "food", 260, "The month's eating and Food imports brought the stock to 300 units",
            key: CauseKeys.FoodImported, args: new[] { "300" });
        var turn = new StepResult(last.State, new[] { shortage, import }, last.Rejected);
        CollectionAssert.AreEqual(
            new[] { "The month's eating and Food imports brought the stock to 300 units",
                "Food ran out: 60 of 100 units of the month's need went unmet" },
            TurnReportPresenter.StockCauses(turn, Pools.FoodTarget, w => w.Message));
    }

    [Test]
    public void ItCoversTheHudUntilClosedAndThenTheCardIsBack()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();   // the second turn opens with The First Truce and The Altalena
        Assert.IsTrue(k.Report.IsOpen);
        Assert.IsFalse(k.Q("top-bar").enabledSelf, "the top bar is covered");
        Assert.IsFalse(k.Q("left-column").enabledSelf, "the screens' buttons are covered");
        Assert.IsFalse(k.Q("event-layer").enabledSelf, "the decision card is covered");
        Assert.IsTrue(k.Q("turn-report").enabledSelf, "the report itself takes input");
        UiTestKit.Press(k.Ui.Q<Button>("turn-report-close"));
        Assert.IsFalse(k.Report.IsOpen);
        Assert.AreEqual(DisplayStyle.None, k.Q("turn-report").style.display.value);
        Assert.IsTrue(k.Q("top-bar").enabledSelf && k.Q("left-column").enabledSelf && k.Q("event-layer").enabledSelf, "everything is back");
        Assert.IsFalse(k.Q("turn-report").enabledSelf, "a closed report takes no input");
        Assert.IsFalse(k.Report.Close(), "closing it again does nothing");
    }

    [Test]
    public void CancelClosesItAndSeeAllOpensTheWhyScreen()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();
        var close = k.Ui.Q<Button>("turn-report-close");
        using (var e = NavigationCancelEvent.GetPooled()) { e.target = close; close.SendEvent(e); }
        Assert.IsFalse(k.Report.IsOpen, "Esc or a gamepad's Cancel closes it");
        var turn = k.Bridge.EndTurn();
        Assert.IsTrue(k.Report.IsOpen, "each turn has its own report");
        UiTestKit.Press(k.Ui.Q<Button>("turn-report-all"));
        Assert.IsFalse(k.Report.IsOpen);
        Assert.AreEqual("why", k.Nav.Current, "See all opens the Why screen");
        Assert.AreEqual(turn.Why.Count, k.Ui.Root.Q<ScrollView>("why-rows").Query<Label>(className: "why-line").ToList().Count, "with every cause of the turn");
    }

    [Test]
    public void AnOutcomeClipCoversTheReportAndHandsItBack()
    {
        using var k = new Kit(En);
        k.Bridge.EndTurn();
        var root = k.Q("root");
        root.AddToClassList(OutcomePresenter.OpenClass);
        ScreenNav.DisableCovered(root);
        Assert.IsFalse(k.Q("turn-report").enabledSelf, "under a clip the report takes no input");
        root.RemoveFromClassList(OutcomePresenter.OpenClass);
        ScreenNav.DisableCovered(root);
        Assert.IsTrue(k.Q("turn-report").enabledSelf, "and takes it again when the clip ends");
        Assert.IsFalse(k.Q("event-layer").enabledSelf, "the card stays covered by the report");
    }

    [Test]
    public void ARefusedOrderStillReportsTheTurnAndARefusedTurnDoesNot()
    {
        // A turn that ran with one order refused: the turn happened, so it is reported.
        using (var k = new Kit(En, (g, cmds) =>
        {
            var r = g.Step(cmds);
            return new StepResult(r.State, r.Why, new[] { new Rejection(new SetMobilization(0.5), "refused for the test") });
        }))
        {
            k.Bridge.EndTurn();
            Assert.IsTrue(k.Report.IsOpen, "a refused order does not hide the turn's report");
        }
        // A batch the sim refused outright (SimBridge.EndTurn's failure): nothing happened, so there is nothing to report.
        using (var k = new Kit(En, (g, cmds) => throw new System.ArgumentException("refused for the test")))
        {
            LogAssert.Expect(LogType.Warning, "End Turn refused: refused for the test");
            k.Bridge.EndTurn();
            Assert.IsFalse(k.Report.IsOpen, "a refused turn has no report");
        }
    }

    [Test]
    public void HebrewShowsTheHebrewWordsAndCaptions()
    {
        using var k = new Kit(He);
        k.Bridge.EndTurn();
        Assert.AreEqual(He["report.title"], k.Ui.Q<Label>("turn-report-title").text);
        Assert.AreEqual(He["report.intro"], k.Ui.Q<Label>("turn-report-intro").text);
        Assert.AreEqual(He["report.all"], k.Ui.Q<Button>("turn-report-all").text);
        Assert.AreEqual(He["report.close"], k.Ui.Q<Button>("turn-report-close").text);
        var heading = k.Ui.Q<Label>("turn-report-heading-security").text;
        StringAssert.StartsWith(He["hud.caption.security"] + ":", heading);
        // In a right-to-left line the change keeps its sign in front ("+2%", not "2%+"): UiText.Format marks it (#543).
        StringAssert.Contains(UiText.LeftToRightMark + k.Ui.Q<Label>("security-delta").text + UiText.LeftToRightMark, heading);
        var causes = Causes(k.Ui, "security");
        CollectionAssert.AreEqual(HudModel.Causes(k.Bridge.Session.Last, "security", C, w => CauseText.Line(w, C, System.Array.Empty<UnitEntry>(), He)), causes,
            "the causes are the sim's, worded as on the Why screen");
        // B1: the treasury's tax-and-spending line is Hebrew (a line with no key yet, such as an event's, stays English).
        Assert.IsTrue(UiDirection.RightToLeft(Causes(k.Ui, "treasury")[0]), "the money line is in Hebrew");
        // #2212: Money's Other line too (why.cause.money_other).
        var money = Causes(k.Ui, "treasury");
        Assert.AreEqual(HudModel.MaxCauses + 1, money.Count, "the two largest Money causes and the Other line");
        Assert.IsTrue(UiDirection.RightToLeft(money[money.Count - 1]), "the Other line is in Hebrew");
        StringAssert.Contains("(סיבות אחרות)", money[money.Count - 1]);
        // B1: one label a cause, so a Hebrew line and a line still in English each take their own direction.
        Assert.AreEqual(HudModel.Causes(k.Bridge.Session.Last, "security", C, w => w.Message).Count,
            k.Q("turn-report-causes-security").Query<Label>(className: "turn-report-cause").ToList().Count);
    }

    /// <summary>The smoke run plays as a player does: it closes each turn's report before the next turn (GameRoot.Smoke).</summary>
    [Test]
    public void TheSmokeRunClosesTheReportEachTurn()
    {
        using var k = new Kit(En);
        // This report-only fixture has no map/card. Supply its unit skips at each turn start.
        void SkipUnits() { foreach (var id in k.Bridge.NeedsOrders.ToList()) k.Bridge.Skip(id); }
        SkipUnits();
        k.Bridge.TurnEnded += _ => SkipUnits();
        var log = new List<string>();
        var run = GameRoot.Smoke(k.Ui.Root, k.Bridge, k.Card, 3, log.Add);
        while (run.MoveNext()) { }
        StringAssert.StartsWith("SMOKE OK 3 turns", log[log.Count - 1], string.Join("\n", log));
        Assert.IsFalse(k.Report.IsOpen);
    }

    /// <summary>#1680: four arrivals stay visible without covering the report's heading or first causes, even while
    /// the next decision card waits underneath. Closing the report restores the card's own toast placement.</summary>
    [UnityTest]
    public IEnumerator FourArrivalsClearTheReportWhileTheNextCardWaits()
    {
        foreach (var hebrew in new[] { false, true })
        {
            var rt = new RenderTexture(1920, 1080, 0);
            var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
            ps.targetTexture = rt;
            var go = new GameObject("ArrivalToastReportLayout"); go.SetActive(false);
            var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps;
            doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
            go.SetActive(true);
            var root = doc.rootVisualElement;
            var hud = root.Q("root"); hud.RemoveFromClassList("loading");
            if (hebrew) hud.AddToClassList(UiLanguage.HebrewClass);
            var text = hebrew ? He : En;
            var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
            var owned = new List<System.IDisposable>();
            owned.Add(new HudPresenter(root, bridge, text));
            var nav = new ScreenNav(root); owned.Add(nav);
            var card = new EventCardPresenter(root, bridge, text, null); owned.Add(card);
            var report = new TurnReportPresenter(root, bridge, text, nav); owned.Add(report);
            var toast = new ToastPresenter(root, bridge, text); owned.Add(toast);
            // Layout inputs only: the real presenter must retain all four lines, in either direction.
            var arrivals = hebrew
                ? new[] { "כרמלי הגיעה ליעד", "גבעתי הגיעה ליעד", "עציוני הגיעה ליעד", "הנגב הגיעה ליעד" }
                : new[] { "Carmeli arrived at its destination", "Givati arrived at its destination",
                    "Etzioni arrived at its destination", "Negev arrived at its destination" };
            try
            {
                bridge.EndTurn();
                toast.Show(arrivals);
                for (int i = 0; i < 30 && !(root.Q("turn-report-panel").layout.width > 0); i++) yield return null;
                for (int i = 0; i < 3; i++) yield return null;
                string at = hebrew ? "he" : "en";
                Assert.IsTrue(report.IsOpen, at);
                Assert.IsNotNull(card.Shown, at + ": a decision waits under the report");
                Assert.IsTrue(hud.ClassListContains(EventCardPresenter.OpenClass), at);
                Assert.IsFalse(root.Q("event-layer").enabledSelf, at + ": the card is covered");
                Assert.IsTrue(root.Q("turn-report").enabledSelf, at + ": the report stays usable");
                var label = root.Q<Label>("toast"); var bounds = label.worldBound;
                CollectionAssert.AreEqual(arrivals, label.text.Split('\n'), at + ": no arrival is discarded");
                Assert.AreEqual(DisplayStyle.Flex, label.resolvedStyle.display, at);
                Assert.Greater(bounds.width, 0, at); Assert.Greater(bounds.height, 0, at);
                Assert.IsTrue(root.worldBound.Contains(bounds.min) && root.worldBound.Contains(bounds.max), at + ": toast stays in the window");
                foreach (var name in new[] { "turn-report-title", "turn-report-intro", "turn-report-heading-security" })
                    Assert.IsFalse(bounds.Overlaps(root.Q(name).worldBound), at + ": " + name + " is readable");
                var firstCause = root.Q("turn-report-panel").Query<Label>(className: "turn-report-cause").ToList().First();
                Assert.IsFalse(bounds.Overlaps(firstCause.worldBound), at + ": first cause is readable");
                Assert.IsFalse(hud.ClassListContains(EventCardPresenter.ModalClass), at + ": a covered card cannot center the toast");
                Assert.IsFalse(root.Q("map-focus").enabledSelf, at + ": removing modal does not uncover the map");
                report.Close();
                for (int i = 0; i < 3; i++) yield return null;
                Assert.IsTrue(root.Q("event-layer").enabledSelf, at + ": card is usable again");
                Assert.IsTrue(hud.ClassListContains(EventCardPresenter.ModalClass), at + ": card placement restored");
                CollectionAssert.AreEqual(arrivals, label.text.Split('\n'), at + ": closing keeps every arrival");
            }
            finally
            {
                for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
                Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
            }
        }
    }

    /// <summary>At a laptop's 1280x720 and a phone's 390x844, in English and Hebrew: the report lies in the window, every
    /// line within its panel, its two buttons shown, and the keyboard focus on Close.</summary>
    [UnityTest]
    public IEnumerator ItFitsLaptopAndPhoneInBothLanguages([Values(100, 125, 150)] int uiScale)   // #40: at the Settings scale choices (#2219 review)
    {
        var problems = new List<string>();
        foreach (var hebrew in new[] { false, true })
            foreach (var (w, h) in new[] { (1280, 720), (390, 844), (360, 800), (2560, 1080) })   // and the ends of the verified range (SettingsPresenter.VerifiedShapes)
            {
                string at = $"{(hebrew ? "he" : "en")} {w}x{h} at {uiScale}%";
                var rt = new RenderTexture(w, h, 0);
                var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
                ps.targetTexture = rt;
                if (uiScale != 100) ps.referenceResolution = new Vector2Int(Mathf.RoundToInt(1920f * 100f / uiScale), Mathf.RoundToInt(1080f * 100f / uiScale));   // #40: the panel as the Settings scale choice sets it
                var go = new GameObject("TurnReportLayout"); go.SetActive(false);
                var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps;
                doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
                go.SetActive(true);
                var root = doc.rootVisualElement;
                root.Q("root").RemoveFromClassList("loading");
                var text = hebrew ? He : En;
                root.Q("root").EnableInClassList(UiLanguage.HebrewClass, text["ui.lang"] == UiLanguage.Hebrew);   // as GameRoot
                var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
                var owned = new List<System.IDisposable>();
                owned.Add(new HudPresenter(root, bridge, text));
                var nav = new ScreenNav(root); owned.Add(nav);
                owned.Add(new EventCardPresenter(root, bridge, text, null));
                var report = new TurnReportPresenter(root, bridge, text, nav); owned.Add(report);
                if (hebrew) owned.Add(new UiDirection(root, bridge));
                try
                {
                    bridge.EndTurn();
                    for (int i = 0; i < 30 && !(root.Q("turn-report-panel").layout.width > 0); i++) yield return null;
                    for (int i = 0; i < 3; i++) yield return null;
                    var window = root.worldBound; var panel = root.Q("turn-report-panel").worldBound;
                    var causesStyle = root.Q("turn-report-causes-security").resolvedStyle;
                    float expectedLeft = hebrew ? 2f : 14f, expectedRight = hebrew ? 14f : 2f;
                    // The panel snaps layout to whole screen pixels, so a stylesheet px reads within one screen pixel of itself.
                    float snap = 1f / HudPresenter.ScreenPxPerPanelPx(root.panel) + 0.01f;
                    if (Mathf.Abs(causesStyle.paddingLeft - expectedLeft) > snap || Mathf.Abs(causesStyle.paddingRight - expectedRight) > snap)
                        problems.Add($"{at}: Security causes padding is {causesStyle.paddingLeft}px left and {causesStyle.paddingRight}px right, expected {expectedLeft}px and {expectedRight}px");
                    if (!(panel.width > 0 && panel.height > 0)) problems.Add($"{at}: the report is not shown");
                    if (panel.xMin < window.xMin - 0.5f || panel.yMin < window.yMin - 0.5f || panel.xMax > window.xMax + 0.5f || panel.yMax > window.yMax + 0.5f)
                        problems.Add($"{at}: the report {panel} leaves the window {window}");
                    foreach (var label in root.Q("turn-report-panel").Query<Label>().ToList().Where(l => !string.IsNullOrEmpty(l.text)))
                        if (label.worldBound.xMin < panel.xMin - 1 || label.worldBound.xMax > panel.xMax + 1)
                            problems.Add($"{at}: '{label.name}' {label.worldBound} is wider than the report {panel}");
                    foreach (var name in new[] { "turn-report-all", "turn-report-close" })
                    {
                        var b = root.Q<Button>(name).worldBound;
                        if (!(b.height > 0) || b.yMax > panel.yMax + 1 || b.xMin < panel.xMin - 1 || b.xMax > panel.xMax + 1) problems.Add($"{at}: {name} {b} is not inside the report {panel}");
                    }
                    if (root.focusController?.focusedElement != root.Q<Button>("turn-report-close")) problems.Add($"{at}: the focus is on {(root.focusController?.focusedElement as VisualElement)?.name ?? "nothing"}, not Close");
                }
                finally
                {
                    for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
                    Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
                }
            }
        Assert.IsEmpty(problems, string.Join("\n", problems));
    }
}