using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Rail;
/// Tratto continuo su una linea: si sale in From e si scende in To.
public readonly record struct Hop(LineId Line, StationId From, StationId To, double Minutes);
/// Collegamento migliore verso una stazione: minuti di orologio dei treni e tratti.
public sealed record Connection(StationId Destination, double Minutes, Hop[] Hops)
{
public Hop First => Hops[0];
}
///
/// Grafo delle linee di una compagnia (guida 7, 9): nodi = stazioni, archi = fermate
/// consecutive di una linea con il tempo di percorrenza stimato. Dijkstra sugli stati
/// (stazione, linea) con penalità di cambio. Ricostruito quando cambiano rete, linee o treni.
///
public sealed class LineGraph
{
private readonly record struct Segment(int From, int To, LineId Line, double Minutes);
private readonly Dictionary> _out = new();
private readonly Dictionary> _reach = new();
private readonly double _transferMinutes;
public CompanyId Company { get; }
public int Version { get; }
/// Capacità giornaliera stimata per linea e classe (posti, unità merci).
public Dictionary DailyCapacity { get; } = new();
/// Durata di un giro completo per linea (minuti di orologio dei treni).
public Dictionary CycleMinutes { get; } = new();
public LineGraph(Simulation.World w, CompanyId company, int version)
{
Company = company;
Version = version;
var ops = w.Data.Construction.Operations;
double dwell = w.Data.Construction.Stations.MinDwellMinutes;
_transferMinutes = dwell * 2;
var net = w.Network;
var path = new List();
foreach (var line in w.Lines)
{
if (line.Removed || line.Owner != company || line.Stops.Count < 2) continue;
var trains = w.Trains.Where(t => !t.Removed && t.Line == line.Id).ToList();
double speed = trains.Count > 0 ? trains.Min(t => t.MaxSpeedKmh) : 60;
bool electric = trains.Any(t => t.NeedsElectrification);
double cycle = 0;
bool complete = true;
for (int i = 0; i < line.Stops.Count; i++)
{
var a = net.Stations[line.Stops[i].Station.Value];
var b = net.Stations[line.Stops[(i + 1) % line.Stops.Count].Station.Value];
if (a.Id == b.Id) continue;
if (!w.Pathfinder.FindPath(net, company, a.Node, EdgeId.None, b.Node, speed, electric, ops.MaxTurnDeg, path))
{
complete = false;
continue;
}
double seconds = 0;
foreach (var step in path) seconds += Pathfinder.EdgeTime(net.Edges[step.Edge.Value], speed / 3.6);
double minutes = seconds / 60 * 1.15 + dwell; // margine per accelerazioni e frenate
cycle += minutes;
if (!_out.TryGetValue(a.Id.Value, out var list)) _out[a.Id.Value] = list = [];
list.Add(new Segment(a.Id.Value, b.Id.Value, line.Id, minutes));
}
if (!complete || cycle <= 0) continue;
CycleMinutes[line.Id.Value] = cycle;
double tripsPerDay = w.Calendar.TrainMinutesPerDay / cycle;
double workers = 0, staff = 0, freight = 0;
foreach (var t in trains)
{
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
if (v.Def.Kind == Data.VehicleKind.Coach)
{
if (v.Def.Class == Data.PaxClass.Staff) staff += v.Def.PaxCapacity ?? 0;
else workers += v.Def.PaxCapacity ?? 0;
}
else if (v.Def.Kind == Data.VehicleKind.Wagon) freight += v.Def.Capacity ?? 0;
}
}
DailyCapacity[line.Id.Value] = (workers * tripsPerDay, staff * tripsPerDay, freight * tripsPerDay);
}
foreach (var list in _out.Values) list.Sort((x, y) => x.To != y.To ? x.To.CompareTo(y.To) : x.Line.Value.CompareTo(y.Line.Value));
}
/// Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili.
public IReadOnlyDictionary From(StationId origin)
{
if (_reach.TryGetValue(origin.Value, out var cached)) return cached;
var result = new Dictionary();
// stato = (stazione, linea su cui si viaggia); linea −1 = a terra all'origine
var best = new Dictionary<(int, int), double>();
var came = new Dictionary<(int, int), ((int, int) Prev, Segment Seg)>();
var open = new PriorityQueue<(int Station, int Line), (double, int, int)>();
best[(origin.Value, -1)] = 0;
open.Enqueue((origin.Value, -1), (0, origin.Value, -1));
while (open.TryDequeue(out var state, out var pri))
{
double cost = pri.Item1;
if (best.TryGetValue(state, out double known) && known < cost) continue;
if (state.Station != origin.Value && !result.ContainsKey(state.Station))
result[state.Station] = BuildConnection(state, cost, came, origin.Value);
if (!_out.TryGetValue(state.Station, out var segs)) continue;
foreach (var seg in segs)
{
double c = cost + seg.Minutes + (state.Line >= 0 && state.Line != seg.Line.Value ? _transferMinutes : 0);
var next = (seg.To, seg.Line.Value);
if (best.TryGetValue(next, out double old) && old <= c) continue;
best[next] = c;
came[next] = (state, seg);
open.Enqueue(next, (c, seg.To, seg.Line.Value));
}
}
_reach[origin.Value] = result;
return result;
}
private static Connection BuildConnection((int Station, int Line) state, double cost,
Dictionary<(int, int), ((int, int) Prev, Segment Seg)> came, int origin)
{
var segs = new List();
var s = state;
while (came.TryGetValue(s, out var link))
{
segs.Add(link.Seg);
s = link.Prev;
}
segs.Reverse();
var hops = new List();
foreach (var seg in segs)
{
if (hops.Count > 0 && hops[^1].Line == seg.Line)
{
var last = hops[^1];
hops[^1] = last with { To = new StationId(seg.To), Minutes = last.Minutes + seg.Minutes };
}
else
{
hops.Add(new Hop(seg.Line, new StationId(seg.From), new StationId(seg.To), seg.Minutes));
}
}
return new Connection(new StationId(state.Station), cost, hops.ToArray());
}
}
/// Grafi delle linee per compagnia, ricostruiti quando cambia la versione della rete o delle linee.
public sealed class LineGraphCache
{
private readonly Dictionary _graphs = new();
/// Contatore delle modifiche a linee, treni assegnati e composizioni.
public int LinesVersion { get; private set; }
public void Touch() => LinesVersion++;
public LineGraph For(Simulation.World w, CompanyId company)
{
int version = w.Network.Version * 100_003 + LinesVersion;
if (_graphs.TryGetValue(company.Value, out var g) && g.Version == version) return g;
g = new LineGraph(w, company, version);
_graphs[company.Value] = g;
return g;
}
}