using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
///
/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti,
/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3).
///
public sealed class FinanceSystem : ISimSystem
{
public string Name => "Finance";
private double[] _running = [];
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
PayRunningCosts(w);
foreach (var c in w.Companies)
{
if (c.Bankrupt) continue;
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
{
c.Bankrupt = true;
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
$"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
}
}
if (ctx.IsNewMonth && ctx.Day > 0)
{
UpdateBookValues(w);
foreach (var c in w.Companies)
{
if (!c.Bankrupt) PayLoans(w, c);
c.Rating = ComputeRating(w, c);
Array.Clear(c.MonthEntries);
}
}
if (ctx.IsNewYear && ctx.Day > 0)
{
foreach (var c in w.Companies)
{
Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length);
Array.Clear(c.YearEntries);
}
}
}
/// Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi.
private void PayRunningCosts(World w)
{
if (_running.Length < w.Companies.Count) _running = new double[w.Companies.Count];
Array.Clear(_running);
double days = w.Calendar.DaysPerYear;
foreach (var v in w.Vehicles)
{
// il motore usurato consuma di più (10.1)
if (!v.Sold) _running[v.Owner.Value] += v.Def.RunningCostPerYear / days * Fleet.FuelFactor(w, v);
}
var sp = w.Data.Construction.Stations;
foreach (var s in w.Network.Stations)
{
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _running[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
}
foreach (var d in w.Network.Depots)
{
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _running[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
}
for (int i = 0; i < w.Companies.Count; i++)
{
if (_running[i] <= 0 || w.Companies[i].Bankrupt) continue;
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
}
}
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo.
public static void UpdateBookValues(World w)
{
var fb = w.Data.Balance.Finance;
var values = new long[w.Companies.Count];
double daysPerYear = w.Calendar.DaysPerYear;
long today = w.Clock.Day;
foreach (var e in w.Network.Edges)
{
if (e.State == Rail.EdgeState.Demolished) continue;
double age = (today - e.BuiltDay) / daysPerYear;
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
}
foreach (var s in w.Network.Stations)
{
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
}
foreach (var d in w.Network.Depots)
{
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
double age = (today - v.BoughtDay) / daysPerYear;
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
}
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
}
/// Rata mensile costante (alla francese) per il residuo e i mesi restanti.
public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft)
{
if (monthsLeft <= 0) return remaining;
double r = annualRate / 12;
if (r <= 0) return Money.FromCentsRounded((double)remaining.Cents / monthsLeft);
double factor = r / (1 - DMath.Pow(1 + r, -monthsLeft));
return Money.FromCentsRounded(remaining.Cents * factor);
}
private static void PayLoans(World w, Company c)
{
for (int i = c.Loans.Count - 1; i >= 0; i--)
{
var loan = c.Loans[i];
var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12);
var payment = MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
var principal = Money.Min(loan.Remaining, payment - interest);
if (principal.IsNegative) principal = Money.Zero;
w.Money.Transfer(Account.Of(c.Id), Account.External, interest, LedgerEntry.Interest);
w.Money.Transfer(Account.Of(c.Id), Account.External, principal, LedgerEntry.LoanRepaid);
loan.Remaining -= principal;
loan.MonthsLeft--;
if (loan.Remaining.Cents <= 0 || loan.MonthsLeft <= 0)
{
if (loan.Remaining.IsPositive)
w.Money.Transfer(Account.Of(c.Id), Account.External, loan.Remaining, LedgerEntry.LoanRepaid);
c.Loans.RemoveAt(i);
}
}
}
///
/// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) +
/// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json.
///
public static CreditRating ComputeRating(World w, Company c)
{
var fb = w.Data.Balance.Finance;
long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries;
long revenue = Company.Revenue(entries);
long profit = Company.OperatingProfit(entries);
double margin = revenue > 0 ? (double)profit / revenue : 0;
double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents);
double leverage = c.Debt.Cents / assets;
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1);
if (c.Bankrupt) return CreditRating.D;
for (int i = 0; i < fb.RatingByScore.Length; i++)
{
if (score >= fb.RatingByScore[i]) return (CreditRating)i;
}
return CreditRating.D;
}
/// Fido massimo della compagnia secondo il livello raggiunto.
public static Money MaxLoan(World w, Company c)
{
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
}
/// Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.
public static double LoanRate(World w, Company c) =>
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()];
}