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.

19.3 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.Linq;

namespace Statecraft.Sim
{
    public static class EconomySystem
    {
        public const string FxCrisis = "fx_crisis";

        /// <summary>The command kind that converts foreign currency into Money (R-MONEY-004).</summary>
        public const string ConvertDollarsKind = "convert_dollars";
        /// <summary>R-MONEY-004: the smallest conversion, in US$ millions. DollarsRefusal refuses below it and the UI words that
        /// refusal from it (SimBridge.ReasonText), so the two cannot drift apart (#2704).</summary>
        public const int DollarsMinimum = 1;
        /// <summary>The sim's English for a conversion below <see cref="DollarsMinimum"/>. A constant, since tests name it in
        /// attributes; DollarsTests pins it to DollarsMinimum.</summary>
        public const string RefusedDollarsMinimum = "Convert at least $1m";
        public const string RefusedDollarsNotAtWar = "Dollars can be converted only during the war";
        public const string RefusedDollarsMonthly = "That is more dollars than may be converted this month";
        public const string RefusedDollarsTotal = "That would pass the total of dollars that may be converted";
        public const string RefusedDollarsReserves = "There are not enough dollars in the reserves";

        public static void Init(Content c, GameState s)
        {
            s.Treasury = c.Rules.TreasuryStart;
            s.FxReserves = c.Rules.FxStart;
            s.Budget = new Dictionary<string, double>(c.Rules.BudgetStart);
        }

        /// <summary>The treasury's money in and out over <paramref name="yearFraction"/> of a year (1.0 = a year): tax,
        /// spending and the cost of the reserve call-up. Apply uses it, and the Budget screen shows it.</summary>
        public readonly struct TreasuryFlows
        {
            public readonly double Tax, Spending, Mobilization;
            public TreasuryFlows(double tax, double spending, double mobilization) { Tax = tax; Spending = spending; Mobilization = mobilization; }
        }

        /// <summary>#2199: whether <paramref name="w"/> is a cause of the Money (net) change, Treasury minus Debt (the top bar's
        /// Money, R-MONEY-001), its Delta that change: a Treasury line, and a city's job income (R-CITY-002), whose Target is the
        /// city. A borrowing line (Target debt) is not one: it moves the Treasury and the Debt by the same amount, and the cost it
        /// borrowed for has its own Treasury line. The turn's lines it picks add up to the change (MoneyCausesTests); the turn
        /// report and the meter tip show the largest (HudModel.Causes). An event's Debt line (R-EFX-009, #2457) is one too: the
        /// Debt it adds has no Treasury line, so it moves the Money (net) by <see cref="MoneyDelta"/>, its Delta negated.</summary>
        public static bool MovesMoney(Cause w) => w.Target == "treasury" || w.Key == CauseKeys.WagesPaid
            || (w.Target == "debt" && w.Key == CauseKeys.EventAmount);

        /// <summary>The change a <see cref="MovesMoney"/> line makes to the Money (net): its Delta, negated for a Debt line.</summary>
        public static double MoneyDelta(Cause w) => w.Target == "debt" ? -w.Delta : w.Delta;

        /// <summary>#2558: <paramref name="w"/> as the Money row (HudModel.Causes) words it. An event's Debt line becomes a
        /// Money line of its <see cref="MoneyDelta"/> with the same key and Args (the event's title), so it reads "Money IL
        /// -18.6m (Israel Bonds)" and not as a Debt gain beside the Money lines; any other line is returned as it is.</summary>
        public static Cause MoneyLine(Content c, Cause w)
        {
            if (w.Target != "debt" || w.Key != CauseKeys.EventAmount) return w;
            var delta = MoneyDelta(w);
            // "events" as a literal (every event_amount Debt line is EventSystem's), so WhyScreenTests' source scan sees it.
            return new Cause("events", "treasury", delta, $"{PlayerText.Change(c, "treasury", delta)} ({w.Args[0]})", key: w.Key, args: w.Args);
        }

        /// <summary>#2212: the one Money line for the causes a list leaves out. The turn report and the meter tip show the
        /// largest Money causes (HudModel.Causes, at most HudModel.MaxCauses); this is the sum of the turn's other lines
        /// <see cref="MovesMoney"/> picks (<paramref name="why"/> minus <paramref name="shown"/>, by reference), so the lines
        /// shown add up to the Money (net) change. Null when nothing is left over or the rest shows as IL 0.0m
        /// (PlayerText.MoneyChange's rounding). The line is the UI's, never one of the turn's (StepResult.Why).</summary>
        public static Cause? OtherMoney(Content c, IEnumerable<Cause> why, IReadOnlyCollection<Cause> shown)
        {
            var rest = why.Where(w => MovesMoney(w) && !shown.Contains(w)).Sum(MoneyDelta);
            if (PlayerText.MoneyChange(c, "treasury", rest) == PlayerText.MoneyChange(c, "treasury", 0)) return null;
            return new Cause("economy", "treasury", rest, $"{PlayerText.Change(c, "treasury", rest)} (other causes)", key: CauseKeys.MoneyOther);
        }

        /// <summary>#1725 PR 7: runs on an initialized Historical ledger (the dark start), reading its head count from
        /// GameState.TotalPopulation, that is every living record (R-MONEY-001; owner, 8 November 2026: "Everyone alive
        /// (Recommended)"); a synthetic or Open ledger stays refused (R-POP-002).</summary>
        public static TreasuryFlows Flows(Content c, GameState s, double yearFraction)
        {
            PopulationLedger.RefuseUnlessHistorical(s);
            var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;
            return new TreasuryFlows(r.TaxPerCapitaPerYear * pop * yearFraction, r.SpendingPerCapitaPerYear * pop * yearFraction,
                MobilizationCost(c, s.Date, s.Mobilization, yearFraction));
        }

        /// <summary>The reserve call-up's cost (pay and lost work) for <paramref name="level"/> (0..1) over a share of a year:
        /// the one rule Flows and the Defence screen both use (M3 final review M5).</summary>
        public static double MobilizationCost(Content c, DateTime date, double level, double yearFraction = 1.0) => c.RulesAt(date).MobilizationCostPerYear * level * yearFraction;

        /// <summary>Pays <paramref name="cost"/> from the Treasury, borrowing what it lacks: the shortfall goes to Debt and the
        /// Treasury stops at 0, as for map actions and the deficit. <paramref name="purpose"/> ends the causes ("for training").
        /// The GDD orders pay through it (owner decision "Allow borrowing", 2026-10-15; R-TRAIN-001, R-SITE-001).
        /// <paramref name="purposeKey"/> (a CauseKeys.Purpose) and <paramref name="purposeArgs"/> say the same purpose for the
        /// UI (CauseKeys.Paid and CauseKeys.Borrowed, B1); <paramref name="purpose"/> stays the English Message. The whole cost
        /// is a Money line first (CauseKeys.Paid, #2199), then any borrowing, as <see cref="PayNamedOrBorrow"/> writes it.</summary>
        public static void PayOrBorrow(Content c, GameState s, double cost, string purpose, List<Cause> why, string purposeKey, params string[] purposeArgs)
        {
            if (cost != 0) why.Add(Paid(c, cost, purpose, purposeKey, purposeArgs));
            PayNamedOrBorrow(c, s, cost, purpose, why, purposeKey, purposeArgs);
        }

        /// <summary>The Money line (CauseKeys.Paid) for <paramref name="cost"/> paid from the Treasury, as PayOrBorrow writes
        /// it. MapActions.Apply, which borrows for itself (CauseKeys.MapBorrowed), writes it too (#2199).</summary>
        public static Cause Paid(Content c, double cost, string purpose, string purposeKey, params string[] purposeArgs) =>
            new Cause("economy", "treasury", -cost, $"{PlayerText.Change(c, "treasury", -cost)} ({purpose})",
                key: CauseKeys.Paid, args: new[] { purposeKey }.Concat(purposeArgs).ToList());

        /// <summary><see cref="PayOrBorrow"/> for a cost its caller has already given its own Money line (civilian and military
        /// upkeep, a Deport, an event option's cost): only the borrowing line, if any.</summary>
        public static void PayNamedOrBorrow(Content c, GameState s, double cost, string purpose, List<Cause> why, string purposeKey, params string[] purposeArgs)
        {
            s.Treasury -= cost;
            if (s.Treasury >= 0) return;
            s.Debt += -s.Treasury;
            why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} {purpose}",
                key: CauseKeys.Borrowed, args: new[] { purposeKey }.Concat(purposeArgs).ToList()));
            s.Treasury = 0;
        }

        /// <summary>R-MONEY-004 (#813; owner, 2 November 2026: "Spend the dollars (Recommended)"): during the war (rung 4 or 5)
        /// <paramref name="amount"/> US$ millions of foreign currency leave the reserves and amount times the mvp.il_per_dollar rate in
        /// force on the turn's date, in IL millions, joins the Treasury, so the turn's deficit borrows that much less (R-MONEY-003). Refused, state untouched,
        /// below $1m, outside the war (<paramref name="startRung"/>, the rung the turn started at, below 4), past
        /// mvp.dollars_per_turn with <paramref name="thisTurn"/> (this turn's earlier conversions), past mvp.dollars_total, or
        /// below 0 reserves. Step has already refused it in the legacy loop.</summary>
        public static string? ConvertDollars(Content c, GameState s, int amount, int thisTurn, int startRung, List<Cause> why)
        {
            var refused = DollarsRefusal(c, s, amount, thisTurn, startRung);
            if (refused != null) return refused;
            var money = amount * c.RulesAt(s.Date).Mvp!.IlPerDollarOn(s.Date);
            s.FxReserves -= amount;
            s.Treasury += money;
            s.DollarsConverted += amount;
            why.Add(new Cause("economy", "treasury", money,
                $"Converted {PlayerText.Money(c, "fx_reserves", amount)} of foreign currency into Money: {PlayerText.MoneyChange(c, "treasury", money)}",
                key: CauseKeys.DollarsConverted, args: new[] { CauseKeys.Number(amount) }));
            why.Add(new Cause("economy", "fx_reserves", -amount,
                $"Foreign currency converted into Money: {PlayerText.MoneyChange(c, "fx_reserves", -amount)}",
                key: CauseKeys.DollarsConvertedFx, args: new[] { CauseKeys.Number(amount) }));
            return null;
        }

        /// <summary>R-MONEY-004's refusal of <paramref name="amount"/> in <paramref name="s"/>, after <paramref name="thisTurn"/>
        /// dollars converted earlier in the same turn, or null when it would be carried out. The war is
        /// <paramref name="startRung"/>, the rung the turn started at (an event's set_rung earlier in the turn does not change
        /// it), else the state's rung, which is the turn's start before End turn. ConvertDollars refuses on it, and the Defence
        /// screen says it before End turn.</summary>
        public static string? DollarsRefusal(Content c, GameState s, int amount, int thisTurn = 0, int? startRung = null)
        {
            var r = c.RulesAt(s.Date).Mvp!;   // the loader requires the three values in the GDD loop
            if (amount < DollarsMinimum) return RefusedDollarsMinimum;
            if ((startRung ?? s.Rung) < WarRung) return RefusedDollarsNotAtWar;
            if ((long)thisTurn + amount > r.DollarsPerTurn!.Value) return RefusedDollarsMonthly;
            if ((long)s.DollarsConverted + amount > r.DollarsTotal!.Value) return RefusedDollarsTotal;
            if (s.FxReserves - amount < 0) return RefusedDollarsReserves;
            return null;
        }

        /// <summary>The lowest rung of the war (R-MONEY-004): the rungs 4 and 5 of the #813 measurement, 15 May 1948 to 15
        /// March 1949 in the historical run.</summary>
        public const int WarRung = 4;

        /// <summary>R-MONEY-002: pays civilian-place upkeep in step 7, prorated by the turn's share of a year.</summary>
        public static void PayCivilianUpkeep(Content c, GameState s, MvpRules r, double yearFraction, List<Cause> why)
        {
            var cost = Cities.AnnualUpkeep(c, s, r) * yearFraction;
            if (cost == 0) return;
            why.Add(new Cause("economy", "treasury", -cost, $"{PlayerText.Change(c, "treasury", -cost)} (civilian upkeep)", key: CauseKeys.CivilianUpkeep));
            PayNamedOrBorrow(c, s, cost, "for civilian upkeep", why, CauseKeys.Purpose.CivilianUpkeep);
        }

        /// <summary>R-MONEY-001, R-MONEY-003: the turn's tax, spending, reserve call-up and foreign-currency flows. Runs on an
        /// initialized Historical ledger as <see cref="Flows"/> does, and changes no ledger record.</summary>
        public static void Apply(Content c, GameState s, double yearFraction, List<Cause> why)
        {
            PopulationLedger.RefuseUnlessHistorical(s);
            var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;
            var flows = Flows(c, s, yearFraction);
            var revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;
            s.Treasury += revenue - spending - mobilization;
            why.Add(new Cause("economy", "treasury", revenue - spending - mobilization,
                $"{PlayerText.Change(c, "treasury", revenue - spending - mobilization)} (tax {PlayerText.Money(c, "treasury", revenue)}, spending {PlayerText.Money(c, "treasury", spending)}, reserve call-up {PlayerText.Money(c, "treasury", mobilization)})",
                key: CauseKeys.MoneyFlows, args: new[] { CauseKeys.Number(revenue), CauseKeys.Number(spending), CauseKeys.Number(mobilization) }));
            if (s.Treasury < 0)
            {
                s.Debt += -s.Treasury;
                why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} to cover the deficit",
                    key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Deficit }));
                s.Treasury = 0;
            }

            var exports = r.ExportsPerYear * yearFraction;
            var inflow = r.CapitalInflowPerYear * yearFraction;
            var imports = r.ImportsPerCapitaPerYear * pop * yearFraction;
            var net = exports + inflow - imports;
            s.FxReserves += net;
            why.Add(new Cause("economy", "fx_reserves", net, $"{PlayerText.Change(c, "fx_reserves", net)} (exports {PlayerText.Money(c, "fx_reserves", exports)}, donations and loans {PlayerText.Money(c, "fx_reserves", inflow)}, imports {PlayerText.Money(c, "fx_reserves", imports)})",
                key: CauseKeys.FxFlows, args: new[] { CauseKeys.Number(exports), CauseKeys.Number(inflow), CauseKeys.Number(imports) }));

            bool on = s.ActiveSituations.Contains(FxCrisis);
            if (!on && s.FxReserves < 0) { s.ActiveSituations.Add(FxCrisis); why.Add(new Cause("economy", FxCrisis, 1, "Foreign currency reserves are exhausted", key: CauseKeys.FxCrisisBegan)); }
            else if (on && s.FxReserves > 0.25 * r.FxStart) { s.ActiveSituations.Remove(FxCrisis); why.Add(new Cause("economy", FxCrisis, -1, "Foreign currency crisis eased", key: CauseKeys.FxCrisisEased)); }

            // The consequence: with no currency to pay for them, food imports are cut while the crisis lasts. In the GDD loop
            // the cut falls on the Food stock's imports instead (R-FOOD-002, Q-POOL-4), and food_supply follows the stock.
            if (!c.IsGdd && s.ActiveSituations.Contains(FxCrisis) && r.FxCrisisFoodPerYear < 0)
            {
                var change = EffectsSystem.Shift(c, s, "food_supply", r.FxCrisisFoodPerYear * yearFraction);
                if (change != 0)
                    why.Add(new Cause("economy", "food_supply", change, $"{PlayerText.Change(c, "food_supply", change)} (foreign currency crisis: food imports cut)", key: CauseKeys.FxCrisisFood));
            }
        }

        /// <summary><see cref="Allocate"/>'s refusals (#2707); the UI maps each to its own string (SimBridge.ReasonText). The English is what a
        /// Rejected list and a save carry, so it does not change.</summary>
        public const string RefusedBudgetRequired = "Budget shares are required", RefusedBudgetMinistry = "The budget names a ministry that does not exist in this game",
            RefusedBudgetFinite = "Budget shares must be finite numbers", RefusedBudgetEveryMinistry = "The budget must give a share to every ministry, and only to them",
            RefusedBudgetSum = "Budget shares must sum to 1", RefusedBudgetNegative = "Budget shares cannot be negative";

        /// <summary>Returns null on success, or the reason the allocation was rejected.</summary>
        public static string? Allocate(Content c, GameState s, Dictionary<string, double> shares)
        {
            if (shares == null) return RefusedBudgetRequired;
            var unknown = shares.Keys.OrderBy(k => k, StringComparer.Ordinal).FirstOrDefault(k => c.Offices.All(o => o.Id != k) && !c.Rules.BudgetStart.ContainsKey(k));   // ordinal: play and replay name the same office
            if (unknown != null) return RefusedBudgetMinistry;
            if (shares.Values.Any(v => double.IsNaN(v) || double.IsInfinity(v))) return RefusedBudgetFinite;
            if (!new HashSet<string>(shares.Keys).SetEquals(c.Rules.BudgetStart.Keys))
                return RefusedBudgetEveryMinistry;
            // Summed in key order, not dictionary order, so play and replay agree to the bit whatever order the caller built the map in.
            if (Math.Abs(shares.OrderBy(kv => kv.Key, StringComparer.Ordinal).Sum(kv => kv.Value) - 1.0) > 1e-6) return RefusedBudgetSum;
            if (shares.Values.Any(v => v < 0)) return RefusedBudgetNegative;
            s.Budget = new Dictionary<string, double>(shares);
            return null;
        }

        /// <summary>#1109: whether the Budget screen's <paramref name="draft"/> differs from what End turn will apply (the
        /// AllocateBudget in <paramref name="pending"/>, this turn's queue, else today's budget) and Submit can still make them
        /// agree this turn: a draft back at today's budget withdraws the queued one for nothing; any other needs the Attention
        /// left once a queued budget is refunded (SimBridge.CanPay's rule) to pay for allocate_budget. False when the game is
        /// over. A query only: the side menu's Budget badge reads it, so the trap of an edited budget that End turn never
        /// applies is visible.</summary>
        public static bool Unsubmitted(Content c, GameState s, IReadOnlyDictionary<string, double> draft, IEnumerable<Command> pending)
        {
            var list = pending.ToList();
            var queued = list.OfType<AllocateBudget>().LastOrDefault();
            if (s.GameOver != null || Same(draft, queued?.Shares ?? s.Budget)) return false;
            return Same(draft, s.Budget) || !c.UsesAttention
                || AttentionSystem.Cost(c, s, "allocate_budget") <= AttentionSystem.Left(c, s, list.Where(x => !(x is AllocateBudget))) + 1e-9;
        }

        /// <summary>The Budget screen's comparison: every line of either map within 1e-9, a missing line counting as 0.</summary>
        static bool Same(IReadOnlyDictionary<string, double> a, IReadOnlyDictionary<string, double> b) =>
            a.Keys.Union(b.Keys).All(k => Math.Abs((a.TryGetValue(k, out var x) ? x : 0) - (b.TryGetValue(k, out var y) ? y : 0)) <= 1e-9);
    }
}