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.

34.7 KB
Raw Blame
using System;
using System.Globalization;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Statecraft.Sim;

/// <summary>The national Food pool (GDD Phase 2 PR 3; D-C2 "National pools"): the stock, the turn's eating and imports in
/// step 7, and food_supply derived from it (maintainer decision of 16 October 2026, option (b), #382: a stock term from
/// months of cover, rationing and events on top, the unmet share lowering it further; the stock stops at 0).</summary>
public class PoolsTests
{
    static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());

    /// <summary>The GDD fixture: 1000 people in units of 10 eat 100 units a month; k_food 0.1, cover_months 3.</summary>
    static Content Gdd(string mvpExtra = "  k_food: 0.1\n  cover_months: 3\n", string? model = null, string rulesExtra = "")
    {
        var files = Fixture.Gdd();
        files["rules.yaml"] = files["rules.yaml"].Replace("  k_food: 0.1\n  cover_months: 3\n", "").Replace("mvp:\n", "mvp:\n" + mvpExtra) + rulesExtra;
        if (model != null) files["model.yaml"] = model;
        return ContentLoader.Load(Fixture.Write(files));
    }

    static GameState Step(Content c, GameState s) => Simulation.Step(c, s, Array.Empty<Command>()).State;
    static StepResult StepWithWhy(Content c, GameState s) => Simulation.Step(c, s, Array.Empty<Command>());

    // R-FOOD-001
    [Fact]
    public void TheStockStartsAtItsMonthsOfCover()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        Assert.Equal(100, s.FoodNeed);              // 1000 people / 10 per unit, one unit of Food per unit a month
        Assert.Equal(3 * 100, s.Food);              // cover_months of the start's need
        Assert.Equal(0, s.FoodUnmet);

        var r = Simulation.NewGame(Real, GoldenRun.Seed, Mode.Historical);
        var m = Real.Rules.Mvp!;
        Assert.Equal((int)Math.Round(r.TotalPopulation / m.PeoplePerUnit, MidpointRounding.AwayFromZero), r.FoodNeed);
        Assert.Equal(m.CoverMonths!.Value * r.FoodNeed, r.Food);
    }

    // R-FOOD-003
    [Fact]
    public void AFullStockLeavesFoodSupplyWhereItWas()
    {
        // The stock term is exactly 0 at cover_months of cover, so the start's food_supply is the indicator's base.
        var s = Simulation.NewGame(Gdd(), 1, Mode.Historical);
        Assert.Equal(0.4, s.Indicators["food_supply"]);
        Assert.Equal(0.0, Pools.FoodTerm(Gdd(), s));
    }

    // R-FOOD-002
    [Fact]
    public void ImportsKeepTheStockAtItsCoverInANormalTurn()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        var next = Step(c, s);
        Assert.Equal(next.FoodNeed * 3, next.Food);
        Assert.Equal(0, next.FoodUnmet);
        Assert.Equal(0.4, next.Indicators["food_supply"]);
    }

    // #2527: the month's eating and the import top-up add their own Why line, and the Food row's lines add up to the
    // stock's change (the line nets the eating and the import, so it stays silent in a steady turn and matches the
    // change when the stock starts under cover).
    [Fact]
    public void TheEatingAndImportAddTheirOwnWhyLineAndTheFoodLinesAddUp()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Food = 150;                   // under the 300 of cover, so the month's eating and import show a net +150
        var r = StepWithWhy(c, s);
        Assert.Equal(300, r.State.Food);
        var line = Assert.Single(r.Why, w => w.Key == CauseKeys.FoodImported);
        Assert.Equal(("economy", "food", 150.0), (line.System, line.Target, line.Delta));
        Assert.Equal(new[] { "300" }, line.Args);
        Assert.Equal(r.State.Food - 150, r.Why.Where(w => w.System == "economy" && w.Target == "food").Sum(w => w.Delta));
    }

    // #2527 review: below the month's need the shortage line is informational (delta 0, the unmet in its args), so the
    // Food row's lines still add up to the stock's change: +260 = 0 + 260 for Food 40, need 100, cover 300.
    [Fact]
    public void BelowTheNeedTheShortageIsInformationalAndTheFoodLinesStillAddUp()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Food = 40;                    // below the month's need of 100: 60 go unmet, the import brings the stock to its cover
        var r = StepWithWhy(c, s);
        Assert.Equal(300, r.State.Food);
        Assert.Equal(60, r.State.FoodUnmet);
        var shortage = Assert.Single(r.Why, w => w.Key == CauseKeys.FoodShortage);
        Assert.Equal(0.0, shortage.Delta);
        Assert.Equal(new[] { "60", "100" }, shortage.Args);
        Assert.Equal("Food ran out: 60 of 100 units of the month's need went unmet", shortage.Message);
        Assert.Equal(r.State.Food - 40, r.Why.Where(w => w.System == "economy" && w.Target == "food").Sum(w => w.Delta));
    }

    // #2527: a steady turn (the stock already at its cover) nets to nothing, so no line is invented.
    [Fact]
    public void ASteadyTurnAddsNoImportLine()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        var r = StepWithWhy(c, s);
        Assert.Equal(300, r.State.Food);
        Assert.DoesNotContain(r.Why, w => w.Key == CauseKeys.FoodImported);
    }

    // R-FOOD-002 (Q-POOL-4: the fx crisis cuts the imports, not food_supply directly)
    [Fact]
    public void ACurrencyCrisisCutsTheImportsSoTheStockFalls()
    {
        var c = Gdd(rulesExtra: "fx_crisis_food_per_year: -0.4\n");   // the legacy loop's direct cut, set so its absence shows
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.ActiveSituations.Add(EconomySystem.FxCrisis);
        s.FxReserves = -1000;                       // stays exhausted through the step
        var r = StepWithWhy(c, s);
        Assert.Equal(300 - 100, r.State.Food);      // ate a month's need, imported nothing
        Assert.Equal(0, r.State.FoodUnmet);
        Assert.Contains(r.Why, w => w.System == "economy" && w.Target == "food" && w.Message.Contains("foreign currency crisis"));
        // The legacy direct cut does not also act in the GDD loop: the only change is the stock term.
        Assert.Equal(0.0, r.State.IndicatorShifts["food_supply"]);
    }

    // R-FOOD-002 (Q-POOL-5: the stock stops at 0, and the unmet share is counted)
    [Fact]
    public void TheStockStopsAtZero()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.ActiveSituations.Add(EconomySystem.FxCrisis);
        s.FxReserves = -1000;
        s.Food = 40;                                // less than the 100 the nation eats this turn
        var r = StepWithWhy(c, s);
        Assert.Equal(0, r.State.Food);
        Assert.Equal(100 - 40, r.State.FoodUnmet);
        Assert.Contains(r.Why, w => w.System == "economy" && w.Message.Contains("60 of 100"));
        var again = Step(c, r.State);               // still no imports: nothing to eat, never below 0
        Assert.Equal(0, again.Food);
        Assert.Equal(again.FoodNeed, again.FoodUnmet);
    }

    // R-FOOD-001 to R-FOOD-003 under the gdd-0.3 ruleset (#2653): the Food code is shared by every GDD loop, so the same
    // start stock, monthly eating and imports hold there. The fixture with the real balance catalogue, as DefeatTests does.
    [Fact]
    public void TheFoodCasesHoldUnderGdd03()
    {
        var files = Fixture.Gdd();
        files["eras.yaml"] = files["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: " + SaveGame.Gdd03Ruleset);
        files[Gdd03BalanceCatalogue.FileName] = System.IO.File.ReadAllText(System.IO.Path.Combine(RealContentTests.ContentRoot(), Gdd03BalanceCatalogue.FileName));
        var c = ContentLoader.Load(Fixture.Write(files));
        Assert.Equal(SaveGame.Gdd03Ruleset, c.Ruleset);
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        Assert.Equal(100, s.FoodNeed);                              // R-FOOD-001: 1000 people / 10 per unit
        Assert.Equal(3 * 100, s.Food);                              // cover_months of the start's need
        Assert.Equal(0, s.FoodUnmet);
        Assert.Equal(0.4, s.Indicators["food_supply"]);             // R-FOOD-003: a full stock adds no term
        Assert.Equal(0.0, Pools.FoodTerm(c, s));

        var next = Step(c, s);                                      // R-FOOD-002: imports bring it back to its cover
        Assert.Equal(next.FoodNeed * 3, next.Food);
        Assert.Equal(0, next.FoodUnmet);
        Assert.Equal(0.4, next.Indicators["food_supply"]);

        s.ActiveSituations.Add(EconomySystem.FxCrisis);             // R-FOOD-002: no imports, the stock falls and stops at 0
        s.FxReserves = -1000;
        s.Food = 40;
        var r = StepWithWhy(c, s);
        Assert.Equal(0, r.State.Food);
        Assert.Equal(100 - 40, r.State.FoodUnmet);
        Assert.Contains(r.Why, w => w.System == "economy" && w.Message.Contains("60 of 100"));
        Assert.Equal(-0.1 - 0.6, Pools.FoodTerm(c, r.State), 12);         // R-FOOD-003: empty, -k_food, and 60% unmet
    }

    // R-FOOD-003
    [Fact]
    public void FoodSupplyFollowsTheStock()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        double Level(int food, int unmet)
        {
            var x = s.Clone(); x.Food = food; x.FoodUnmet = unmet;
            EffectsSystem.Apply(c, x, new List<Cause>());
            return x.Indicators["food_supply"];
        }
        Assert.Equal(0.4, Level(300, 0), 12);                       // three months: no term
        Assert.Equal(0.4 - 0.1 / 3, Level(200, 0), 12);             // two months: a third of k_food off
        Assert.Equal(0.4 - 0.1, Level(0, 0), 12);                   // empty: all of k_food off
        Assert.Equal(0.4 - 0.1 - 0.2, Level(0, 20), 12);            // 20% of the need unmet: 0.2 further
        Assert.Equal(0.0, Level(0, 100), 12);                       // nothing eaten: clamped at 0, never below
        Assert.True(Level(400, 0) > 0.4);                           // more than the cover lifts it
    }

    // R-FOOD-003: rationing and events still act on top of the stock term.
    [Fact]
    public void RationingAndEventsStillActOnFoodSupply()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Food = 0;                                                 // the term at its lowest, -k_food
        var rationed = s.Clone();
        rationed.Policies["rationing"] = 1.0;
        EffectsSystem.Apply(c, s, new List<Cause>());
        EffectsSystem.Apply(c, rationed, new List<Cause>());
        var feeds = rationed.EffectContributions["rationing_food"];
        Assert.True(feeds > 0);
        Assert.Equal(0.4 - 0.1, s.Indicators["food_supply"], 12);
        Assert.Equal(0.4 - 0.1 + feeds, rationed.Indicators["food_supply"], 12);   // rationing on top of the stock term
        var moved = EffectsSystem.Shift(c, s, "food_supply", -0.05); // an event's shift
        Assert.Equal(-0.05, moved, 12);
        EffectsSystem.Apply(c, s, new List<Cause>());
        Assert.Equal(0.4 - 0.1 - 0.05, s.Indicators["food_supply"], 12);
    }

    // R-FOOD-002: step 7 reads the need of the people at the turn's start (the legacy head count grows after the resolver).
    [Fact]
    public void TheTurnEatsWhatTheStartOfTheTurnNeeds()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.ActiveSituations.Add(EconomySystem.FxCrisis);
        s.FxReserves = -1000;
        s.Population["veterans"] = 2000;                            // 200 units now; the state's stored need is still 100
        var next = Step(c, s);
        Assert.Equal(300 - 200, next.Food);                         // the need is re-read at step 7, before arrivals
        Assert.True(next.TotalPopulation > 2000);                   // natural increase came after it
        Assert.Equal(200, next.FoodNeed);
    }

    // R-FOOD-002 (Q-POOL-4) and R-FOOD-003: the sourced 1951 currency crisis still cuts food in the real game.
    [Fact]
    public void The1951CurrencyCrisisStillCutsFood()
    {
        var s = Simulation.NewGame(Real, GoldenRun.Seed, Mode.Historical);
        var history = new List<GameState> { s };
        while (s.GameOver == null) { s = Simulation.Step(Real, s, GoldenRun.Orders(Real, s)).State; history.Add(s); }
        var first = history.FindIndex(x => x.ActiveSituations.Contains(EconomySystem.FxCrisis));
        Assert.True(first > 0 && first < history.Count - 1, "the crisis must begin before the last turn");
        var before = history[first];                                // the crisis began in this turn's economy
        var cut = history[first + 1];                               // the next turn's imports are cut
        Assert.True(history.Take(first + 1).All(x => x.Food == Real.Rules.Mvp!.CoverMonths!.Value * x.FoodNeed), "before the crisis the stock holds its cover");
        Assert.True(cut.Food < cut.FoodNeed * Real.Rules.Mvp!.CoverMonths!.Value, "the crisis cut the imports");
        Assert.True(cut.Indicators["food_supply"] < before.Indicators["food_supply"], "food_supply fell with the stock");
        Assert.All(history, x => Assert.True(x.Food >= 0));
    }

    // R-FOOD-001, R-LOOP-002: the pool is hashed in the GDD loop, and the legacy loop's text is unchanged.
    [Fact]
    public void ThePoolIsHashedOnlyWhenSet()
    {
        var legacy = Simulation.NewGame(ContentLoader.Load(Fixture.Write()), 1, Mode.Historical);
        Assert.DoesNotContain("\nfood=", legacy.Describe());
        var s = Simulation.NewGame(Gdd(), 1, Mode.Historical);
        Assert.Contains("\nfood=300,100,0", s.Describe());
        var other = s.Clone(); other.FoodUnmet = 1;
        Assert.NotEqual(s.Hash(), other.Hash());
        Assert.Equal(300, s.Food);                                   // a clone does not share the pool
    }

    // R-FOOD-001: missing or out-of-range values are load errors, never a default.
    [Theory]
    [InlineData("  cover_months: 3\n", "mvp.k_food", "required")]
    [InlineData("  k_food: 0.1\n", "mvp.cover_months", "required")]
    [InlineData("  k_food: -0.1\n  cover_months: 3\n", "mvp.k_food", "between 0 and 1")]
    [InlineData("  k_food: 1.5\n  cover_months: 3\n", "mvp.k_food", "between 0 and 1")]
    [InlineData("  k_food: .nan\n  cover_months: 3\n", "mvp.k_food", "between 0 and 1")]
    [InlineData("  k_food: 0.1\n  cover_months: 0\n", "mvp.cover_months", ">= 1")]
    public void TheFoodValuesAreRequired(string extra, string field, string message)
    {
        var ex = Assert.Throws<ContentException>(() => Gdd(extra));
        Assert.Equal(field, ex.Field);
        Assert.Contains(message, ex.Message);
    }

    // R-FOOD-001: cover_months has a ceiling, so the stock's int multiply cannot wrap (#2804 item 5). The ceiling itself loads.
    [Theory]
    [InlineData(121)]
    [InlineData(int.MaxValue)]
    public void CoverMonthsAboveTheCeilingFailsLoad(int months)
    {
        var ex = Assert.Throws<ContentException>(() => Gdd(FormattableString.Invariant($"  k_food: 0.1\n  cover_months: {months}\n")));
        Assert.Equal(("rules.yaml", "mvp.cover_months"), (ex.File, ex.Field));
        Assert.Contains("<= 120", ex.Message);
    }

    // R-FOOD-001: at the ceiling the stock is exactly that many months of the fixture's need of 100.
    [Fact]
    public void CoverMonthsAtTheCeilingLoads()
    {
        var s = Simulation.NewGame(Gdd("  k_food: 0.1\n  cover_months: 120\n"), 1, Mode.Historical);
        Assert.Equal(120 * 100, s.Food);
    }

    // R-FOOD-003: the GDD loop needs the food_supply indicator the pool feeds.
    [Fact]
    public void TheGddLoopNeedsAFoodSupplyIndicator()
    {
        var model = Fixture.Files["model.yaml"]
            .Replace("  - id: food_supply\n    base: 0.4\n    name: Food supply\n", "")
            .Replace("    target: food_supply\n", "    target: morale\n")
            .Replace("    indicator: food_supply\n", "    indicator: morale\n");
        var ex = Assert.Throws<ContentException>(() => Gdd(model: model));
        Assert.Equal("mvp.k_food", ex.Field);
        Assert.Contains("food_supply", ex.Message);
    }

    // R-ARMS-001: the Arms stock starts at arms_start in the GDD loop; the legacy loop has no pool.
    [Fact]
    public void TheArmsStockStartsAtTheRulesValue()
    {
        Assert.Equal(20, Simulation.NewGame(Gdd(), 1, Mode.Historical).Arms);
        Assert.Equal(Real.Rules.Mvp!.ArmsStart!.Value, Simulation.NewGame(Real, GoldenRun.Seed, Mode.Historical).Arms);
        Assert.Equal(0, Simulation.NewGame(ContentLoader.Load(Fixture.Write()), 1, Mode.Historical).Arms);
    }

    // R-ARMS-001: the stock reaches the hash only when set (R-LOOP-002), and a clone does not share it.
    [Fact]
    public void TheArmsStockIsHashedOnlyWhenSet()
    {
        var legacy = Simulation.NewGame(ContentLoader.Load(Fixture.Write()), 1, Mode.Historical);
        Assert.DoesNotContain("\narms=", legacy.Describe());
        var s = Simulation.NewGame(Gdd(), 1, Mode.Historical);
        Assert.Contains("\narms=20", s.Describe());
        var other = s.Clone(); other.Arms = 19;
        Assert.NotEqual(s.Hash(), other.Hash());
        Assert.Equal(20, s.Arms);
    }

    // R-ARMS-002: BuyArms adds whole units at once and the Treasury pays arms_price for each.
    [Fact]
    public void BuyingArmsCostsMoney()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        var r = Simulation.Step(c, s, new Command[] { new BuyArms(4) });
        Assert.Empty(r.Rejected);
        Assert.Equal(24, r.State.Arms);
        Assert.Equal(Step(c, s).Treasury - 4 * 0.25, r.State.Treasury, 9);
        Assert.Contains(r.Why, x => x.System == "economy" && x.Target == "arms" && x.Delta == 4 && x.Message == "Bought 4 Arms, cost IL\u00A01.0m");
        Assert.Equal(1.0, c.Rules.AttentionCost["buy_arms"]);   // before the rung step (R-GOV-002)
    }

    // R-ARMS-002 with R-MONEY-003: a short Treasury borrows the shortfall, as every GDD cost does.
    [Fact]
    public void AShortTreasuryBorrowsForArms()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Treasury = 0.5;
        s.Debt = 3;
        var why = new List<Cause>();
        Assert.Null(Pools.BuyArms(c, s, 4, why));
        Assert.Equal((0.0, 24), (s.Treasury, s.Arms));
        Assert.Equal(3.5, s.Debt, 9);
        Assert.Contains(why, x => x.System == "economy" && x.Target == "debt" && x.Message == "Borrowed IL\u00A00.5m for Arms");
    }

    // R-ARMS-002: fewer than one unit is refused, the state as if the order had not been given (Attention refunded too),
    // and so is the order in the legacy loop.
    [Theory]
    [InlineData(0)]
    [InlineData(-3)]
    public void BuyingLessThanOneUnitIsRefused(int count)
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        var r = Simulation.Step(c, s, new Command[] { new BuyArms(count) });
        Assert.Equal("Buy at least 1 Arms", Assert.Single(r.Rejected).Reason);
        Assert.Equal(Step(c, s).Hash(), r.State.Hash());
        var legacy = ContentLoader.Load(Fixture.Write());
        var l = Simulation.NewGame(legacy, 1, Mode.Historical);
        Assert.Equal("That order is not available in this game", Assert.Single(Simulation.Step(legacy, l, new Command[] { new BuyArms(1) }).Rejected).Reason);
    }

    // R-ARMS-002: a purchase that would take the stock past a whole number's range is refused, never wrapped.
    [Fact]
    public void APurchaseBeyondTheStocksRangeIsRefused()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        var after = s.Clone();
        Assert.Equal(Pools.RefusedStockCapacity, Pools.BuyArms(c, after, int.MaxValue, new List<Cause>()));
        Assert.Equal(Pools.RefusedStockCapacity, Pools.BuyArmsRefusal(c, s, Array.Empty<Command>(), int.MaxValue));
        Assert.Equal(s.Hash(), after.Hash());
    }

    // #2198, owner 2 Nov 2026 "Refuse buys over ceiling (Recommended)": a purchase whose borrowing would take the debt past
    // mvp.debt_ceiling is refused, the state untouched. The debt after is PayOrBorrow's: the debt plus what the Treasury
    // lacks (the fixture's ceiling is 10, its price 0.25 an Arms).
    [Fact]
    public void APurchaseThatWouldBorrowPastTheDebtCeilingIsRefused()
    {
        var c = Gdd();
        Assert.Equal(10.0, c.Rules.Mvp!.DebtCeiling);
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Treasury = 0.5;
        s.Debt = 8;
        var after = s.Clone();
        var why = new List<Cause>();
        // 11 Arms cost 2.75: 0.5 from the Treasury, 2.25 borrowed, debt 10.25 > 10.
        Assert.Equal("Buying that many Arms would take the debt past its ceiling", Pools.BuyArms(c, after, 11, why));
        Assert.Equal((0.5, 8.0, 20), (after.Treasury, after.Debt, after.Arms));
        Assert.Equal(s.Hash(), after.Hash());
        Assert.Empty(why);
    }

    // #2198: debt landing exactly on the ceiling is allowed (the ceiling is not passed); one unit more is refused.
    [Fact]
    public void APurchaseThatBorrowsExactlyToTheCeilingIsAllowed()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Treasury = 0.5;
        s.Debt = 8;
        var more = s.Clone();
        // 10 Arms cost 2.5: 0.5 from the Treasury, 2.0 borrowed, debt exactly 10.
        Assert.Null(Pools.BuyArms(c, s, 10, new List<Cause>()));
        Assert.Equal((0.0, 10.0, 30), (s.Treasury, s.Debt, s.Arms));
        Assert.NotNull(Pools.BuyArms(c, more, 11, new List<Cause>()));
        Assert.Equal((0.5, 8.0, 20), (more.Treasury, more.Debt, more.Arms));
    }

    // #2198: a purchase the Treasury pays in full borrows nothing, so the ceiling never refuses it, even with the debt
    // already past the ceiling.
    [Fact]
    public void APurchasePaidFromTheTreasuryIgnoresTheCeiling()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Treasury = 3;
        s.Debt = 12;
        Assert.Null(Pools.BuyArms(c, s, 12, new List<Cause>()));
        Assert.Equal((0.0, 12.0, 32), (s.Treasury, s.Debt, s.Arms));
    }

    // #2198 changes only Arms: every other cost still borrows past the ceiling (R-MONEY-003; Q22 stands for them).
    [Fact]
    public void OtherBorrowingStillPassesTheCeiling()
    {
        var c = Gdd();
        var s = Simulation.NewGame(c, 1, Mode.Historical);
        s.Treasury = 0;
        s.Debt = 10;
        var why = new List<Cause>();
        EconomySystem.PayOrBorrow(c, s, 5, "for training", why, CauseKeys.Purpose.Arms);
        Assert.Equal((0.0, 15.0), (s.Treasury, s.Debt));
        var t = Simulation.Step(c, s, Array.Empty<Command>()).State;
        Assert.True(t.Debt > s.Debt, $"the turn's own borrowing still adds to a debt past the ceiling ({s.Debt} -> {t.Debt})");
    }

    // #2198, the reported case: on the real content, 999 Arms on the first turn (IL 979m borrowed, debt IL 985m against the
    // IL 250m ceiling) is refused, and the turn is the turn with no order (the Attention refunded too).
    [Fact]
    public void TheReportedFirstTurnPurchaseOf999ArmsIsRefused()
    {
        var s = Simulation.NewGame(Real, GoldenRun.Seed, Mode.Historical);
        var r = Simulation.Step(Real, s, new Command[] { new BuyArms(999) });
        Assert.Equal("Buying that many Arms would take the debt past its ceiling", Assert.Single(r.Rejected).Reason);
        Assert.Equal(Step(Real, s).Hash(), r.State.Hash());
        Assert.Equal(s.Arms, r.State.Arms);
    }

    // R-ARMS-001 to R-ARMS-003: missing or negative values are load errors, never a default.
    [Theory]
    [InlineData("  arms_start: 20\n", "  arms_start: -1\n", "mvp.arms_start", ">= 0")]
    [InlineData("  arms_start: 20\n", "", "mvp.arms_start", "required")]
    [InlineData("  arms_price: 0.25\n", "", "mvp.arms_price", "required")]
    [InlineData("  arms_price: 0.25\n", "  arms_price: -0.1\n", "mvp.arms_price", "finite number >= 0")]
    [InlineData("  arms_price: 0.25\n", "  arms_price: .inf\n", "mvp.arms_price", "finite number >= 0")]
    [InlineData("  arms_per_recruit_group: 2\n", "", "mvp.arms_per_recruit_group", "required")]
    [InlineData("  arms_per_recruit_group: 2\n", "  arms_per_recruit_group: -2\n", "mvp.arms_per_recruit_group", ">= 0")]
    public void TheArmsValuesAreRequired(string line, string replacement, string field, string message)
    {
        var files = Fixture.Gdd();
        Assert.Contains(line, files["rules.yaml"]);
        files["rules.yaml"] = files["rules.yaml"].Replace(line, replacement);
        var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(files)));
        Assert.Equal(field, ex.Field);
        Assert.Contains(message, ex.Message);
    }

    // R-ARMS-002: the order survives a save (the `arms N` line) and replays to the same state.
    [Fact]
    public void TheArmsOrderSurvivesASave()
    {
        var g = GameSession.New(Real, GoldenRun.Seed, Mode.Historical);
        g.Step(new Command[] { new BuyArms(25) });
        g.Step(new Command[0]);
        var text = g.Save.Write();
        Assert.Contains("\narms 25\n", text);
        var loaded = GameSession.Load(Real, text, out _).State;
        Assert.Equal(g.State.Hash(), loaded.Hash());
        Assert.Equal(Real.Rules.Mvp!.ArmsStart!.Value + 25, loaded.Arms);
    }

    // R-ARMS-002, R-FOOD-002: the keyed lines carry the values the UI words, as invariant text whatever the culture.
    [Fact]
    public void TheArmsAndFoodLinesCarryTheirKeyedValuesInvariantly()
    {
        var culture = Thread.CurrentThread.CurrentCulture;
        try
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
            var c = Gdd();

            var s = Simulation.NewGame(c, 1, Mode.Historical);
            var why = new List<Cause>();
            Assert.Null(Pools.BuyArms(c, s, 3, why));                 // fixture arms_price 0.25: cost 0.75
            var bought = Assert.Single(why, w => w.Key == CauseKeys.ArmsBought);
            Assert.Equal(("economy", "arms", 3.0), (bought.System, bought.Target, bought.Delta));
            Assert.Equal(new[] { "0.75" }, bought.Args);               // the cost, not the count; never "0,75"

            var f = Simulation.NewGame(c, 1, Mode.Historical);
            f.ActiveSituations.Add(EconomySystem.FxCrisis);
            f.Food = 40;                                               // need is 100 (1000 people / 10)
            why = new List<Cause>();
            Pools.Consume(c, f, c.RulesAt(f.Date).Mvp!, why);
            var keyed = why.Where(w => w.Key != "").ToList();
            Assert.Equal(new[] { CauseKeys.FoodShortage, CauseKeys.FoodWithoutImports }, keyed.Select(w => w.Key));
            Assert.Equal(0.0, keyed[0].Delta);                         // informational (#2527): the unmet is in the args
            Assert.Equal(new[] { "60", "100" }, keyed[0].Args);        // the unmet, then the need
            Assert.Equal("Food ran out: 60 of 100 units of the month's need went unmet", keyed[0].Message);
            Assert.Equal(-40.0, keyed[1].Delta);
            Assert.Equal(new[] { "0" }, keyed[1].Args);                // the stock after eating
            Assert.Equal("No Food imported (foreign currency crisis): the stock fell to 0 units", keyed[1].Message);
            Assert.Equal(0, f.Food);                                   // no import in the crisis

            var stocked = Simulation.NewGame(c, 1, Mode.Historical);
            stocked.ActiveSituations.Add(EconomySystem.FxCrisis);
            stocked.Food = 150;
            why = new List<Cause>();
            Pools.Consume(c, stocked, c.RulesAt(stocked.Date).Mvp!, why);
            var withoutImports = Assert.Single(why, w => w.Key == CauseKeys.FoodWithoutImports);
            Assert.Equal(new[] { "50" }, withoutImports.Args);         // the remaining stock, not the zero import quantity
        }
        finally { Thread.CurrentThread.CurrentCulture = culture; }
    }


    // ---- gdd-0.3: the need from the population ledger (#2470) ----

    static readonly PopulationLocation North = new PopulationLocation("north", 0, 0, "camp");

    static PopulationInventoryRow LedgerRow(int ordinal, PopulationStatus status, PopulationAssignment assignment)
    {
        var captured = status == PopulationStatus.Captured;
        var where = assignment.Kind == PopulationAssignmentKind.Travel ? new PopulationLocation("south", 1, 0, "port") : North;
        return new PopulationInventoryRow("fixture", ordinal, new PopulationUnit(0, status, 0, captured ? null : where, assignment,
            CivilianProfession.None, CivilianTier.None, 0, "basic", 0, PopulationEquipment.None, captured ? "captor" : null, captured ? North : null));
    }

    /// <summary>Eight living own records, each differently assigned: idle, at work, teaching, on a course, travelling,
    /// serving, in reception and held by the enemy.</summary>
    static GameState LedgerState() => PopulationLedger.CreateFixture(PopulationLedgerTests.Content(), PopulationLedgerTests.Bindings(), new[] {
        LedgerRow(0, PopulationStatus.FreeCivilian, PopulationAssignment.Unassigned),
        LedgerRow(1, PopulationStatus.FreeCivilian, new PopulationAssignment(PopulationAssignmentKind.Work, "field")),
        LedgerRow(2, PopulationStatus.FreeCivilian, new PopulationAssignment(PopulationAssignmentKind.Teaching, "teacher")),
        LedgerRow(3, PopulationStatus.Trainee, new PopulationAssignment(PopulationAssignmentKind.Course, "course")),
        LedgerRow(4, PopulationStatus.CivilianInTransit, new PopulationAssignment(PopulationAssignmentKind.Travel, "travel")),
        LedgerRow(5, PopulationStatus.ActiveSoldier, new PopulationAssignment(PopulationAssignmentKind.ActiveService, "service")),
        LedgerRow(6, PopulationStatus.Refugee, new PopulationAssignment(PopulationAssignmentKind.Reception, "reception")),
        LedgerRow(7, PopulationStatus.Captured, PopulationAssignment.Unassigned) });

    /// <summary>The month's frozen opening snapshot of the ledger, taken when the month's context is created.</summary>
    static Gdd03SyntheticMonthContext Month(GameState s) => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0,
        s.PopulationLedger.Units, new[] { "course", "field", "reception", "teacher" }.Select(f => new Gdd03SyntheticFacilitySnapshot(f, true, 1)),
        Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());

    // R-FOOD-001 (one unit is one population unit's food for a month) and R-FOOD-002 under gdd-0.3: every living own ledger
    // id eats one ration whatever its assignment, the stock stops at 0, and the import refills to cover_months of that need.
    [Fact]
    public void ALedgerGameEatsOneRationPerLivingOwnPopulationId()
    {
        var s = LedgerState(); s.Food = 5;
        var people = s.PopulationLedger.Units;
        var why = new List<Cause>();
        Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, Month(s), why);
        Assert.Equal((8, 3), (s.FoodNeed, s.FoodUnmet));   // 5 eaten of 8
        Assert.Equal(24, s.Food);                          // refilled to 3 months of 8
        Assert.Contains(why, x => x.Key == CauseKeys.FoodShortage);
        Assert.Equal(people, s.PopulationLedger.Units);   // counting moves no id, status or assignment
    }

    // R-FOOD-002: the foreign-currency crisis still stops the import in a ledger game.
    [Fact]
    public void ALedgerGameImportsNoFoodInTheForeignCurrencyCrisis()
    {
        var s = LedgerState(); s.Food = 20; s.ActiveSituations.Add(EconomySystem.FxCrisis);
        Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, Month(s), new List<Cause>());
        Assert.Equal((12, 8, 0), (s.Food, s.FoodNeed, s.FoodUnmet));
    }

    // R-FOOD-001: the count is one per id whatever order the snapshot holds them in, and a snapshot that repeats an id or
    // holds no record is refused rather than counted.
    [Fact]
    public void LedgerRationsIgnoreOrderAndRefuseARepeatedId()
    {
        var people = LedgerState().PopulationLedger.Units;
        Assert.Equal(8, Pools.Rations(people));
        Assert.Equal(8, Pools.Rations(people.Reverse()));
        Assert.Throws<ArgumentException>(() => Pools.Rations(people.Append(people[3])));
        Assert.Throws<ArgumentException>(() => Pools.Rations(people.Append(null!)));
        Assert.Throws<ArgumentNullException>(() => Pools.Rations(null!));
    }

    // R-POP-002: a ledger state given content of another ruleset is still refused before any Food moves.
    [Fact]
    public void ALedgerStateUnderAnotherRulesetStillRefusesConsume()
    {
        var s = LedgerState(); s.Food = 5; var hash = s.Hash();
        Assert.Throws<NotSupportedException>(() => Pools.Consume(PopulationLedgerTests.Content(SaveGame.GddRuleset), s, new MvpRules { CoverMonths = 3 }, Month(s), new List<Cause>()));
        Assert.Equal(hash, s.Hash());
    }

    /// <summary>R-FOOD-002 under gdd-0.3 (#2806 item 18): an invalid live ledger is refused before any Food moves, because
    /// Pools.Consume reconciles the ledger (Pools.cs:215) before it computes the need or writes Food. The ledger's API refuses
    /// every invalid change (Commit, Replace and Initialize all validate), so this test breaks the ledger through reflection
    /// on its private <c>units</c> field: it removes one registered record, so the created ids no longer equal the live ids.
    /// Reflection keeps the test test-only, with no test hook added to the sim.</summary>
    [Fact]
    public void AnInvalidLedgerIsRefusedBeforeAnyFoodMoves()
    {
        var s = LedgerState(); s.Food = 5;
        var month = Month(s);
        var units = (System.Collections.IDictionary)typeof(PopulationLedger)
            .GetField("units", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
            .GetValue(s.PopulationLedger)!;
        units.Remove(s.PopulationLedger.Units[0].Id);
        var hash = s.Hash(); var food = (s.Food, s.FoodNeed, s.FoodUnmet);
        var why = new List<Cause>();
        var ex = Assert.Throws<InvalidOperationException>(() => Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, month, why));
        Assert.Equal("Population id conservation failed.", ex.Message);
        Assert.Equal(hash, s.Hash());
        Assert.Equal(food, (s.Food, s.FoodNeed, s.FoodUnmet));
        Assert.Empty(why);
    }

    // R-FOOD-002 under gdd-0.3 (#2470): the need comes from the month's frozen snapshot, not the live ledger. A combat loss after the month
    // opened leaves the live ledger at 7 ids; the month still eats its 8 opening rations.
    [Fact]
    public void ALedgerGameEatsTheMonthsFrozenSnapshotNotTheLiveLedger()
    {
        var s = LedgerState(); s.Food = 0;
        var month = Month(s);
        s.PopulationLedger.RegisterCombatLoss(5, "fixture-loss");
        Assert.Equal(7, s.PopulationLedger.Units.Count);
        Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, month, new List<Cause>());
        Assert.Equal((8, 8, 24), (s.FoodNeed, s.FoodUnmet, s.Food));
    }
}