aboutsummaryrefslogtreecommitdiff
path: root/src/Enmarcha.Backend/Services/Processors/VitrasaRealTimeProcessor.cs
blob: 43a215bbfc59cbcaf9678c22a031d9c02083ed77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
using Enmarcha.Sources.OpenTripPlannerGql.Queries;
using Costasdev.VigoTransitApi;
using Enmarcha.Backend.Configuration;
using Enmarcha.Backend.Types;
using Enmarcha.Backend.Types.Arrivals;
using Microsoft.Extensions.Options;

namespace Enmarcha.Backend.Services.Processors;

public class VitrasaRealTimeProcessor : AbstractRealTimeProcessor
{
    private readonly VigoTransitApiClient _api;
    private readonly FeedService _feedService;
    private readonly ILogger<VitrasaRealTimeProcessor> _logger;
    private readonly ShapeTraversalService _shapeService;
    private readonly AppConfiguration _configuration;

    public VitrasaRealTimeProcessor(
        VigoTransitApiClient api,
        FeedService feedService,
        ILogger<VitrasaRealTimeProcessor> logger,
        ShapeTraversalService shapeService,
        IOptions<AppConfiguration> options)
    {
        _api = api;
        _feedService = feedService;
        _logger = logger;
        _shapeService = shapeService;
        _configuration = options.Value;
    }

    public override async Task ProcessAsync(ArrivalsContext context)
    {
        if (!context.StopId.StartsWith("vitrasa:")) return;

        var normalizedCode = _feedService.NormalizeStopCode("vitrasa", context.StopCode);
        if (!int.TryParse(normalizedCode, out var numericStopId)) return;

        try
        {
            // Load schedule
            var todayDate = context.NowLocal.Date.ToString("yyyy-MM-dd");

            Epsg25829? stopLocation = null;
            if (context.StopLocation != null)
            {
                stopLocation = _shapeService.TransformToEpsg25829(context.StopLocation.Latitude, context.StopLocation.Longitude);
            }

            var realtime = await _api.GetStopEstimates(numericStopId);
            var estimates = realtime.Estimates
                .Where(e => !string.IsNullOrWhiteSpace(e.Route) && !e.Route.Trim().EndsWith('*'))
                .ToList();

            System.Diagnostics.Activity.Current?.SetTag("realtime.count", estimates.Count);

            var usedTripIds = new HashSet<string>();
            var newArrivals = new List<Arrival>();

            foreach (var estimate in estimates)
            {
                var estimateRouteNormalized = _feedService.NormalizeRouteNameForMatching(estimate.Route);

                var bestMatch = context.Arrivals
                    .Where(a => !usedTripIds.Contains(a.TripId))
                    .Where(a => a.Route.ShortName.Trim() == estimate.Line.Trim())
                    .Select(a =>
                    {
                        // Use tripHeadsign from GTFS if available, otherwise fall back to stop-level headsign
                        string scheduleHeadsign = a.Headsign.Destination;
                        if (a.RawOtpTrip is ArrivalsAtStopResponse.Arrival otpArr && !string.IsNullOrWhiteSpace(otpArr.Trip.TripHeadsign))
                        {
                            scheduleHeadsign = otpArr.Trip.TripHeadsign;
                        }
                        var arrivalRouteNormalized = _feedService.NormalizeRouteNameForMatching(scheduleHeadsign);
                        string? arrivalLongNameNormalized = null;
                        string? arrivalLastStopNormalized = null;

                        if (a.RawOtpTrip is ArrivalsAtStopResponse.Arrival otpArrival)
                        {
                            if (otpArrival.Trip.Route.LongName != null)
                            {
                                arrivalLongNameNormalized = _feedService.NormalizeRouteNameForMatching(otpArrival.Trip.Route.LongName);
                            }

                            var lastStop = otpArrival.Trip.Stoptimes.LastOrDefault();
                            if (lastStop != null)
                            {
                                arrivalLastStopNormalized = _feedService.NormalizeRouteNameForMatching(lastStop.Stop.Name);
                            }
                        }

                        // Strict route matching logic ported from VitrasaTransitProvider
                        // Check against Headsign, LongName, and LastStop
                        var routeMatch = IsRouteMatch(estimateRouteNormalized, arrivalRouteNormalized);

                        if (!routeMatch && arrivalLongNameNormalized != null)
                        {
                            routeMatch = IsRouteMatch(estimateRouteNormalized, arrivalLongNameNormalized);
                        }

                        if (!routeMatch && arrivalLastStopNormalized != null)
                        {
                            routeMatch = IsRouteMatch(estimateRouteNormalized, arrivalLastStopNormalized);
                        }

                        return new
                        {
                            Arrival = a,
                            TimeDiff = estimate.Minutes - a.Estimate.Minutes, // RealTime - Schedule
                            RouteMatch = routeMatch
                        };
                    })
                    .Where(x => x.RouteMatch) // Strict route matching
                    .Where(x => x.TimeDiff >= -7 && x.TimeDiff <= 75) // Allow 7m early (RealTime < Schedule) or 75m late (RealTime > Schedule)
                    .OrderBy(x => Math.Abs(x.TimeDiff)) // Best time fit
                    .FirstOrDefault();

                if (bestMatch != null)
                {
                    var arrival = bestMatch.Arrival;

                    var scheduledMinutes = arrival.Estimate.Minutes;
                    arrival.Estimate.Minutes = estimate.Minutes;

                    // Calculate delay badge
                    var delayMinutes = estimate.Minutes - scheduledMinutes;
                    arrival.Delay = new DelayBadge { Minutes = delayMinutes };

                    string scheduledHeadsign = arrival.Headsign.Destination;
                    if (arrival.RawOtpTrip is ArrivalsAtStopResponse.Arrival otpArr && !string.IsNullOrWhiteSpace(otpArr.Trip.TripHeadsign))
                    {
                        scheduledHeadsign = otpArr.Trip.TripHeadsign;
                    }

                    // Prefer real-time headsign UNLESS it's just the last stop name (which is less informative)
                    if (!string.IsNullOrWhiteSpace(estimate.Route))
                    {
                        bool isJustLastStop = false;

                        if (arrival.RawOtpTrip is ArrivalsAtStopResponse.Arrival otpArrival)
                        {
                            var lastStop = otpArrival.Trip.Stoptimes.LastOrDefault();
                            if (lastStop != null)
                            {
                                var arrivalLastStopNormalized = _feedService.NormalizeRouteNameForMatching(lastStop.Stop.Name);
                                isJustLastStop = estimateRouteNormalized == arrivalLastStopNormalized;
                            }
                        }

                        // Use real-time headsign unless it's just the final stop name
                        if (!isJustLastStop)
                        {
                            arrival.Headsign.Destination = estimate.Route;
                        }
                    }

                    // Calculate position
                    if (stopLocation != null)
                    {
                        Position? currentPosition = null;

                        if (arrival.RawOtpTrip is ArrivalsAtStopResponse.Arrival otpArrival &&
                            otpArrival.Trip.Geometry?.Points != null)
                        {
                            var decodedPoints = Decode(otpArrival.Trip.Geometry.Points)
                                .Select(p => new Position { Latitude = p.Lat, Longitude = p.Lon })
                                .ToList();

                            var shape = _shapeService.CreateShapeFromWgs84(decodedPoints);

                            // Ensure meters is positive
                            var meters = Math.Max(0, estimate.Meters);
                            var result = _shapeService.GetBusPosition(shape, stopLocation, meters);

                            currentPosition = result.BusPosition;

                            // Populate Shape GeoJSON
                            if (!context.IsReduced && currentPosition != null)
                            {
                                var features = new List<object>
                                {
                                    new
                                    {
                                        type = "Feature",
                                        geometry = new
                                        {
                                            type = "LineString",
                                            coordinates = decodedPoints.Select(p => new[] { p.Longitude, p.Latitude }).ToList()
                                        },
                                        properties = new { type = "route" }
                                    }
                                };

                                // Add stops if available
                                if (otpArrival.Trip.Stoptimes != null)
                                {
                                    foreach (var stoptime in otpArrival.Trip.Stoptimes)
                                    {
                                        features.Add(new
                                        {
                                            type = "Feature",
                                            geometry = new
                                            {
                                                type = "Point",
                                                coordinates = new[] { stoptime.Stop.Lon, stoptime.Stop.Lat }
                                            },
                                            properties = new
                                            {
                                                type = "stop",
                                                name = stoptime.Stop.Name
                                            }
                                        });
                                    }
                                }

                                arrival.Shape = new
                                {
                                    type = "FeatureCollection",
                                    features = features
                                };
                            }
                        }

                        if (currentPosition != null)
                        {
                            arrival.CurrentPosition = currentPosition;
                        }
                    }

                    usedTripIds.Add(arrival.TripId);
                }
                else
                {
                    _logger.LogInformation("Adding unmatched Vitrasa real-time arrival for line {Line} in {Minutes}m",
                        estimate.Line, estimate.Minutes);

                    // Try to find a "template" arrival with the same line to copy colors from
                    var template = context.Arrivals
                        .FirstOrDefault(a => a.Route.ShortName.Trim() == estimate.Line.Trim());

                    newArrivals.Add(new Arrival
                    {
                        TripId = $"vitrasa:rt:{estimate.Line}:{estimate.Route}:{estimate.Minutes}",
                        Route = new RouteInfo
                        {
                            GtfsId = $"vitrasa:{estimate.Line}",
                            ShortName = estimate.Line,
                            Colour = template?.Route.Colour ?? "FFFFFF",
                            TextColour = template?.Route.TextColour ?? "000000",
                        },
                        Headsign = new HeadsignInfo
                        {
                            Destination = estimate.Route
                        },
                        Estimate = new ArrivalDetails
                        {
                            Minutes = estimate.Minutes,
                            Precision = ArrivalPrecision.Confident
                        }
                    });
                }
            }

            context.Arrivals.AddRange(newArrivals);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error fetching Vitrasa real-time data for stop {StopId}", context.StopId);
        }

        foreach (var arr in context.Arrivals)
        {
            if (arr.Estimate.Minutes < 1 && arr.Estimate.Precision == ArrivalPrecision.Scheduled)
            {
                arr.Delete = true; // Remove arrivals that are scheduled right now, since they are likely already departed
            }
        }
    }

    private static bool IsRouteMatch(string a, string b)
    {
        return a == b || a.Contains(b) || b.Contains(a);
    }
}