| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Linq; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using System.Text.Json.Serialization; |
| | | 5 | | using EHonda.KicktippAi.Core; |
| | | 6 | | using FirebaseAdapter.Models; |
| | | 7 | | using Google.Cloud.Firestore; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | using NodaTime; |
| | | 10 | | |
| | | 11 | | namespace FirebaseAdapter; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Firebase Firestore implementation of the prediction repository. |
| | | 15 | | /// </summary> |
| | | 16 | | public class FirebasePredictionRepository : IPredictionRepository |
| | | 17 | | { |
| | 1 | 18 | | private static readonly JsonSerializerOptions JustificationSerializerOptions = new() |
| | 1 | 19 | | { |
| | 1 | 20 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 1 | 21 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull |
| | 1 | 22 | | }; |
| | | 23 | | |
| | | 24 | | private readonly FirestoreDb _firestoreDb; |
| | | 25 | | private readonly ILogger<FirebasePredictionRepository> _logger; |
| | | 26 | | private readonly string _predictionsCollection; |
| | | 27 | | private readonly string _matchesCollection; |
| | | 28 | | private readonly string _bonusPredictionsCollection; |
| | | 29 | | private readonly string _competition; |
| | | 30 | | |
| | 1 | 31 | | public FirebasePredictionRepository(FirestoreDb firestoreDb, ILogger<FirebasePredictionRepository> logger) |
| | | 32 | | { |
| | 1 | 33 | | _firestoreDb = firestoreDb ?? throw new ArgumentNullException(nameof(firestoreDb)); |
| | 1 | 34 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | | 35 | | |
| | | 36 | | // Use unified collection names (no longer community-specific) |
| | 1 | 37 | | _predictionsCollection = "match-predictions"; |
| | 1 | 38 | | _matchesCollection = "matches"; |
| | 1 | 39 | | _bonusPredictionsCollection = "bonus-predictions"; |
| | 1 | 40 | | _competition = "bundesliga-2025-26"; // Remove community suffix |
| | | 41 | | |
| | 1 | 42 | | _logger.LogInformation("Firebase repository initialized"); |
| | 1 | 43 | | } |
| | | 44 | | |
| | | 45 | | public async Task SavePredictionAsync(Match match, Prediction prediction, string model, string tokenUsage, double co |
| | | 46 | | { |
| | | 47 | | try |
| | | 48 | | { |
| | 1 | 49 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 50 | | |
| | | 51 | | // Check if a prediction already exists for this match, model, and community context |
| | | 52 | | // Order by repredictionIndex descending to get the latest version for updating |
| | 1 | 53 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 54 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 55 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 56 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 57 | | .WhereEqualTo("competition", _competition) |
| | 1 | 58 | | .WhereEqualTo("model", model) |
| | 1 | 59 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 60 | | .OrderByDescending("repredictionIndex") |
| | 1 | 61 | | .Limit(1); |
| | | 62 | | |
| | 1 | 63 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 64 | | |
| | | 65 | | DocumentReference docRef; |
| | 1 | 66 | | bool isUpdate = false; |
| | 1 | 67 | | Timestamp? existingCreatedAt = null; |
| | 1 | 68 | | int repredictionIndex = 0; |
| | | 69 | | |
| | 1 | 70 | | if (snapshot.Documents.Count > 0) |
| | | 71 | | { |
| | | 72 | | // Update existing document (latest reprediction) |
| | 1 | 73 | | var existingDoc = snapshot.Documents.First(); |
| | 1 | 74 | | docRef = existingDoc.Reference; |
| | 1 | 75 | | isUpdate = true; |
| | | 76 | | |
| | | 77 | | // Preserve the original values |
| | 1 | 78 | | var existingData = existingDoc.ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 79 | | existingCreatedAt = existingData.CreatedAt; |
| | 1 | 80 | | repredictionIndex = existingData.RepredictionIndex; // Keep same reprediction index for override |
| | | 81 | | |
| | 1 | 82 | | _logger.LogDebug("Updating existing prediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId |
| | 1 | 83 | | match.HomeTeam, match.AwayTeam, existingDoc.Id, repredictionIndex); |
| | | 84 | | } |
| | | 85 | | else |
| | | 86 | | { |
| | | 87 | | // Create new document |
| | 1 | 88 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 89 | | docRef = _firestoreDb.Collection(_predictionsCollection).Document(documentId); |
| | 1 | 90 | | repredictionIndex = 0; // First prediction |
| | | 91 | | |
| | 1 | 92 | | _logger.LogDebug("Creating new prediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId}, re |
| | 1 | 93 | | match.HomeTeam, match.AwayTeam, documentId, repredictionIndex); |
| | | 94 | | } |
| | | 95 | | |
| | 1 | 96 | | var firestorePrediction = new FirestoreMatchPrediction |
| | 1 | 97 | | { |
| | 1 | 98 | | Id = docRef.Id, |
| | 1 | 99 | | HomeTeam = match.HomeTeam, |
| | 1 | 100 | | AwayTeam = match.AwayTeam, |
| | 1 | 101 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 102 | | Matchday = match.Matchday, |
| | 1 | 103 | | HomeGoals = prediction.HomeGoals, |
| | 1 | 104 | | AwayGoals = prediction.AwayGoals, |
| | 1 | 105 | | Justification = SerializeJustification(prediction.Justification), |
| | 1 | 106 | | UpdatedAt = now, |
| | 1 | 107 | | Competition = _competition, |
| | 1 | 108 | | Model = model, |
| | 1 | 109 | | TokenUsage = tokenUsage, |
| | 1 | 110 | | Cost = cost, |
| | 1 | 111 | | CommunityContext = communityContext, |
| | 1 | 112 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 113 | | RepredictionIndex = repredictionIndex |
| | 1 | 114 | | }; |
| | | 115 | | |
| | | 116 | | // Set CreatedAt: preserve existing value for updates unless overrideCreatedAt is explicitly requested |
| | 1 | 117 | | firestorePrediction.CreatedAt = (overrideCreatedAt || existingCreatedAt == null) ? now : existingCreatedAt.V |
| | | 118 | | |
| | 1 | 119 | | await docRef.SetAsync(firestorePrediction, cancellationToken: cancellationToken); |
| | | 120 | | |
| | 1 | 121 | | var action = isUpdate ? "Updated" : "Saved"; |
| | 1 | 122 | | _logger.LogInformation("{Action} prediction for match {HomeTeam} vs {AwayTeam} on matchday {Matchday} (repre |
| | 1 | 123 | | action, match.HomeTeam, match.AwayTeam, match.Matchday, repredictionIndex); |
| | 1 | 124 | | } |
| | 0 | 125 | | catch (Exception ex) |
| | | 126 | | { |
| | 0 | 127 | | _logger.LogError(ex, "Failed to save prediction for match {HomeTeam} vs {AwayTeam}", |
| | 0 | 128 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 129 | | throw; |
| | | 130 | | } |
| | 1 | 131 | | } |
| | | 132 | | |
| | | 133 | | public async Task<Prediction?> GetPredictionAsync(Match match, string model, string communityContext, CancellationTo |
| | | 134 | | { |
| | 1 | 135 | | return await GetPredictionAsync(match.HomeTeam, match.AwayTeam, match.StartsAt, model, communityContext, cancell |
| | 1 | 136 | | } |
| | | 137 | | |
| | | 138 | | public async Task<Prediction?> GetPredictionAsync(string homeTeam, string awayTeam, ZonedDateTime startsAt, string m |
| | | 139 | | { |
| | | 140 | | try |
| | | 141 | | { |
| | | 142 | | // Query by match characteristics, model, community context, and competition |
| | | 143 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 144 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 145 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 146 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 147 | | .WhereEqualTo("startsAt", ConvertToTimestamp(startsAt)) |
| | 1 | 148 | | .WhereEqualTo("competition", _competition) |
| | 1 | 149 | | .WhereEqualTo("model", model) |
| | 1 | 150 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 151 | | .OrderByDescending("repredictionIndex") |
| | 1 | 152 | | .Limit(1); |
| | | 153 | | |
| | 1 | 154 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 155 | | |
| | 1 | 156 | | if (snapshot.Documents.Count == 0) |
| | | 157 | | { |
| | 1 | 158 | | return null; |
| | | 159 | | } |
| | | 160 | | |
| | 1 | 161 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 162 | | return new Prediction( |
| | 1 | 163 | | firestorePrediction.HomeGoals, |
| | 1 | 164 | | firestorePrediction.AwayGoals, |
| | 1 | 165 | | DeserializeJustification(firestorePrediction.Justification)); |
| | | 166 | | } |
| | 0 | 167 | | catch (Exception ex) |
| | | 168 | | { |
| | 0 | 169 | | _logger.LogError(ex, "Failed to get prediction for match {HomeTeam} vs {AwayTeam} using model {Model} and co |
| | 0 | 170 | | homeTeam, awayTeam, model, communityContext); |
| | 0 | 171 | | throw; |
| | | 172 | | } |
| | 1 | 173 | | } |
| | | 174 | | |
| | | 175 | | public async Task<PredictionMetadata?> GetPredictionMetadataAsync(Match match, string model, string communityContext |
| | | 176 | | { |
| | | 177 | | try |
| | | 178 | | { |
| | | 179 | | // Query by match characteristics, model, community context, and competition. |
| | | 180 | | // Order by repredictionIndex descending to keep metadata reads aligned with latest prediction retrieval. |
| | 1 | 181 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 182 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 183 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 184 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 185 | | .WhereEqualTo("competition", _competition) |
| | 1 | 186 | | .WhereEqualTo("model", model) |
| | 1 | 187 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 188 | | .OrderByDescending("repredictionIndex") |
| | 1 | 189 | | .Limit(1); |
| | | 190 | | |
| | 1 | 191 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 192 | | |
| | 1 | 193 | | if (snapshot.Documents.Count == 0) |
| | | 194 | | { |
| | 0 | 195 | | return null; |
| | | 196 | | } |
| | | 197 | | |
| | 1 | 198 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 199 | | var prediction = new Prediction( |
| | 1 | 200 | | firestorePrediction.HomeGoals, |
| | 1 | 201 | | firestorePrediction.AwayGoals, |
| | 1 | 202 | | DeserializeJustification(firestorePrediction.Justification)); |
| | 1 | 203 | | var createdAt = firestorePrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 204 | | var contextDocumentNames = firestorePrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 205 | | |
| | 1 | 206 | | return new PredictionMetadata(prediction, createdAt, contextDocumentNames); |
| | | 207 | | } |
| | 0 | 208 | | catch (Exception ex) |
| | | 209 | | { |
| | 0 | 210 | | _logger.LogError(ex, "Failed to get prediction metadata for match {HomeTeam} vs {AwayTeam} using model {Mode |
| | 0 | 211 | | match.HomeTeam, match.AwayTeam, model, communityContext); |
| | 0 | 212 | | throw; |
| | | 213 | | } |
| | 1 | 214 | | } |
| | | 215 | | |
| | | 216 | | public async Task<IReadOnlyList<Match>> GetMatchDayAsync(int matchDay, CancellationToken cancellationToken = default |
| | | 217 | | { |
| | | 218 | | try |
| | | 219 | | { |
| | 1 | 220 | | var query = _firestoreDb.Collection(_matchesCollection) |
| | 1 | 221 | | .WhereEqualTo("competition", _competition) |
| | 1 | 222 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 223 | | .OrderBy("startsAt"); |
| | | 224 | | |
| | 1 | 225 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 226 | | |
| | 1 | 227 | | var matches = snapshot.Documents |
| | 1 | 228 | | .Select(doc => doc.ConvertTo<FirestoreMatch>()) |
| | 1 | 229 | | .Select(fm => new Match( |
| | 1 | 230 | | fm.HomeTeam, |
| | 1 | 231 | | fm.AwayTeam, |
| | 1 | 232 | | ConvertFromTimestamp(fm.StartsAt), |
| | 1 | 233 | | fm.Matchday, |
| | 1 | 234 | | fm.IsCancelled)) |
| | 1 | 235 | | .ToList(); |
| | | 236 | | |
| | 1 | 237 | | return matches.AsReadOnly(); |
| | | 238 | | } |
| | 0 | 239 | | catch (Exception ex) |
| | | 240 | | { |
| | 0 | 241 | | _logger.LogError(ex, "Failed to get matches for matchday {Matchday}", matchDay); |
| | 0 | 242 | | throw; |
| | | 243 | | } |
| | 1 | 244 | | } |
| | | 245 | | |
| | | 246 | | public async Task<Match?> GetStoredMatchAsync(string homeTeam, string awayTeam, int matchDay, string? model = null, |
| | | 247 | | { |
| | | 248 | | try |
| | | 249 | | { |
| | 1 | 250 | | var matchQuery = _firestoreDb.Collection(_matchesCollection) |
| | 1 | 251 | | .WhereEqualTo("competition", _competition) |
| | 1 | 252 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 253 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 254 | | .WhereEqualTo("awayTeam", awayTeam); |
| | | 255 | | |
| | 1 | 256 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 257 | | |
| | 1 | 258 | | if (matchSnapshot.Documents.Count > 0) |
| | | 259 | | { |
| | 0 | 260 | | if (matchSnapshot.Documents.Count > 1) |
| | | 261 | | { |
| | 0 | 262 | | _logger.LogWarning("Found {Count} stored match documents for {HomeTeam} vs {AwayTeam} on matchday {M |
| | | 263 | | } |
| | | 264 | | |
| | 0 | 265 | | return matchSnapshot.Documents |
| | 0 | 266 | | .Select(document => document.ConvertTo<FirestoreMatch>()) |
| | 0 | 267 | | .Select(firestoreMatch => new Match( |
| | 0 | 268 | | firestoreMatch.HomeTeam, |
| | 0 | 269 | | firestoreMatch.AwayTeam, |
| | 0 | 270 | | ConvertFromTimestamp(firestoreMatch.StartsAt), |
| | 0 | 271 | | firestoreMatch.Matchday, |
| | 0 | 272 | | firestoreMatch.IsCancelled)) |
| | 0 | 273 | | .OrderBy(match => match.StartsAt.ToInstant()) |
| | 0 | 274 | | .ThenBy(match => match.IsCancelled) |
| | 0 | 275 | | .First(); |
| | | 276 | | } |
| | | 277 | | |
| | 1 | 278 | | Query predictionQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 279 | | .WhereEqualTo("competition", _competition) |
| | 1 | 280 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 281 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 282 | | .WhereEqualTo("awayTeam", awayTeam); |
| | | 283 | | |
| | 1 | 284 | | if (!string.IsNullOrWhiteSpace(model)) |
| | | 285 | | { |
| | 1 | 286 | | predictionQuery = predictionQuery.WhereEqualTo("model", model); |
| | | 287 | | } |
| | | 288 | | |
| | 1 | 289 | | if (!string.IsNullOrWhiteSpace(communityContext)) |
| | | 290 | | { |
| | 1 | 291 | | predictionQuery = predictionQuery.WhereEqualTo("communityContext", communityContext); |
| | | 292 | | } |
| | | 293 | | |
| | 1 | 294 | | var predictionSnapshot = await predictionQuery.GetSnapshotAsync(cancellationToken); |
| | | 295 | | |
| | 1 | 296 | | if (predictionSnapshot.Documents.Count == 0) |
| | | 297 | | { |
| | 0 | 298 | | return null; |
| | | 299 | | } |
| | | 300 | | |
| | 1 | 301 | | if (predictionSnapshot.Documents.Count > 1) |
| | | 302 | | { |
| | 0 | 303 | | _logger.LogWarning("Found {Count} stored prediction documents for {HomeTeam} vs {AwayTeam} on matchday { |
| | | 304 | | } |
| | | 305 | | |
| | 1 | 306 | | var firestorePrediction = predictionSnapshot.Documents |
| | 1 | 307 | | .Select(document => document.ConvertTo<FirestoreMatchPrediction>()) |
| | 1 | 308 | | .OrderByDescending(prediction => prediction.RepredictionIndex) |
| | 1 | 309 | | .ThenByDescending(prediction => prediction.CreatedAt.ToDateTimeOffset()) |
| | 1 | 310 | | .ThenBy(prediction => prediction.StartsAt.ToDateTimeOffset()) |
| | 1 | 311 | | .ThenBy(prediction => prediction.Id, StringComparer.Ordinal) |
| | 1 | 312 | | .First(); |
| | | 313 | | |
| | 1 | 314 | | return new Match( |
| | 1 | 315 | | firestorePrediction.HomeTeam, |
| | 1 | 316 | | firestorePrediction.AwayTeam, |
| | 1 | 317 | | ConvertFromTimestamp(firestorePrediction.StartsAt), |
| | 1 | 318 | | firestorePrediction.Matchday); |
| | | 319 | | } |
| | 0 | 320 | | catch (Exception ex) |
| | | 321 | | { |
| | 0 | 322 | | _logger.LogError(ex, "Failed to get stored match {HomeTeam} vs {AwayTeam} for matchday {Matchday}", homeTeam |
| | 0 | 323 | | throw; |
| | | 324 | | } |
| | 1 | 325 | | } |
| | | 326 | | |
| | | 327 | | public async Task<IReadOnlyList<MatchPrediction>> GetMatchDayWithPredictionsAsync(int matchDay, string model, string |
| | | 328 | | { |
| | | 329 | | try |
| | | 330 | | { |
| | | 331 | | // Get all matches for the matchday |
| | 1 | 332 | | var matches = await GetMatchDayAsync(matchDay, cancellationToken); |
| | | 333 | | |
| | | 334 | | // Get predictions for all matches using the specified model and community context |
| | 1 | 335 | | var matchPredictions = new List<MatchPrediction>(); |
| | | 336 | | |
| | 1 | 337 | | foreach (var match in matches) |
| | | 338 | | { |
| | 1 | 339 | | var prediction = await GetPredictionAsync(match, model, communityContext, cancellationToken); |
| | 1 | 340 | | matchPredictions.Add(new MatchPrediction(match, prediction)); |
| | 1 | 341 | | } |
| | | 342 | | |
| | 1 | 343 | | return matchPredictions.AsReadOnly(); |
| | | 344 | | } |
| | 0 | 345 | | catch (Exception ex) |
| | | 346 | | { |
| | 0 | 347 | | _logger.LogError(ex, "Failed to get matches with predictions for matchday {Matchday} using model {Model} and |
| | 0 | 348 | | throw; |
| | | 349 | | } |
| | 1 | 350 | | } |
| | | 351 | | |
| | | 352 | | public async Task<IReadOnlyList<MatchPrediction>> GetAllPredictionsAsync(string model, string communityContext, Canc |
| | | 353 | | { |
| | | 354 | | try |
| | | 355 | | { |
| | 1 | 356 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 357 | | .WhereEqualTo("competition", _competition) |
| | 1 | 358 | | .WhereEqualTo("model", model) |
| | 1 | 359 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 360 | | .OrderBy("matchday"); |
| | | 361 | | |
| | 1 | 362 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 363 | | |
| | 1 | 364 | | var matchPredictions = snapshot.Documents |
| | 1 | 365 | | .Select(doc => doc.ConvertTo<FirestoreMatchPrediction>()) |
| | 1 | 366 | | .Select(fp => new MatchPrediction( |
| | 1 | 367 | | new Match(fp.HomeTeam, fp.AwayTeam, ConvertFromTimestamp(fp.StartsAt), fp.Matchday), |
| | 1 | 368 | | new Prediction( |
| | 1 | 369 | | fp.HomeGoals, |
| | 1 | 370 | | fp.AwayGoals, |
| | 1 | 371 | | DeserializeJustification(fp.Justification)))) |
| | 1 | 372 | | .ToList(); |
| | | 373 | | |
| | 1 | 374 | | return matchPredictions.AsReadOnly(); |
| | | 375 | | } |
| | 0 | 376 | | catch (Exception ex) |
| | | 377 | | { |
| | 0 | 378 | | _logger.LogError(ex, "Failed to get all predictions for model {Model} and community context {CommunityContex |
| | 0 | 379 | | throw; |
| | | 380 | | } |
| | 1 | 381 | | } |
| | | 382 | | |
| | | 383 | | public async Task<bool> HasPredictionAsync(Match match, string model, string communityContext, CancellationToken can |
| | | 384 | | { |
| | | 385 | | try |
| | | 386 | | { |
| | | 387 | | // Query by match characteristics, model, and community context instead of using deterministic ID |
| | 1 | 388 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 389 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 390 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 391 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 392 | | .WhereEqualTo("competition", _competition) |
| | 1 | 393 | | .WhereEqualTo("model", model) |
| | 1 | 394 | | .WhereEqualTo("communityContext", communityContext); |
| | | 395 | | |
| | 1 | 396 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 397 | | return snapshot.Documents.Count > 0; |
| | | 398 | | } |
| | 0 | 399 | | catch (Exception ex) |
| | | 400 | | { |
| | 0 | 401 | | _logger.LogError(ex, "Failed to check if prediction exists for match {HomeTeam} vs {AwayTeam} using model {M |
| | 0 | 402 | | match.HomeTeam, match.AwayTeam, model, communityContext); |
| | 0 | 403 | | throw; |
| | | 404 | | } |
| | 1 | 405 | | } |
| | | 406 | | |
| | | 407 | | public async Task SaveBonusPredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, string mode |
| | | 408 | | { |
| | | 409 | | try |
| | | 410 | | { |
| | 1 | 411 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 412 | | |
| | | 413 | | // Check if a prediction already exists for this question, model, and community context |
| | | 414 | | // Order by repredictionIndex descending to get the latest version for updating |
| | 1 | 415 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 416 | | .WhereEqualTo("questionText", bonusQuestion.Text) |
| | 1 | 417 | | .WhereEqualTo("competition", _competition) |
| | 1 | 418 | | .WhereEqualTo("model", model) |
| | 1 | 419 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 420 | | .OrderByDescending("repredictionIndex") |
| | 1 | 421 | | .Limit(1); |
| | | 422 | | |
| | 1 | 423 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 424 | | |
| | | 425 | | DocumentReference docRef; |
| | 1 | 426 | | bool isUpdate = false; |
| | 1 | 427 | | Timestamp? existingCreatedAt = null; |
| | 1 | 428 | | int repredictionIndex = 0; |
| | | 429 | | |
| | 1 | 430 | | if (snapshot.Documents.Count > 0) |
| | | 431 | | { |
| | | 432 | | // Update existing document (latest reprediction) |
| | 1 | 433 | | var existingDoc = snapshot.Documents.First(); |
| | 1 | 434 | | docRef = existingDoc.Reference; |
| | 1 | 435 | | isUpdate = true; |
| | | 436 | | |
| | | 437 | | // Preserve the original values |
| | 1 | 438 | | var existingData = existingDoc.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 439 | | existingCreatedAt = existingData.CreatedAt; |
| | 1 | 440 | | repredictionIndex = existingData.RepredictionIndex; // Keep same reprediction index for override |
| | | 441 | | |
| | 1 | 442 | | _logger.LogDebug("Updating existing bonus prediction for question '{QuestionText}' (document: {DocumentI |
| | 1 | 443 | | bonusQuestion.Text, existingDoc.Id, repredictionIndex); |
| | | 444 | | } |
| | | 445 | | else |
| | | 446 | | { |
| | | 447 | | // Create new document |
| | 1 | 448 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 449 | | docRef = _firestoreDb.Collection(_bonusPredictionsCollection).Document(documentId); |
| | 1 | 450 | | repredictionIndex = 0; // First prediction |
| | | 451 | | |
| | 1 | 452 | | _logger.LogDebug("Creating new bonus prediction for question '{QuestionText}' (document: {DocumentId}, r |
| | 1 | 453 | | bonusQuestion.Text, documentId, repredictionIndex); |
| | | 454 | | } |
| | | 455 | | |
| | | 456 | | // Extract selected option texts for observability |
| | 1 | 457 | | var optionTextsLookup = bonusQuestion.Options.ToDictionary(o => o.Id, o => o.Text); |
| | 1 | 458 | | var selectedOptionTexts = bonusPrediction.SelectedOptionIds |
| | 1 | 459 | | .Select(id => optionTextsLookup.TryGetValue(id, out var text) ? text : $"Unknown option: {id}") |
| | 1 | 460 | | .ToArray(); |
| | | 461 | | |
| | 1 | 462 | | var firestoreBonusPrediction = new FirestoreBonusPrediction |
| | 1 | 463 | | { |
| | 1 | 464 | | Id = docRef.Id, |
| | 1 | 465 | | QuestionText = bonusQuestion.Text, |
| | 1 | 466 | | SelectedOptionIds = bonusPrediction.SelectedOptionIds.ToArray(), |
| | 1 | 467 | | SelectedOptionTexts = selectedOptionTexts, |
| | 1 | 468 | | UpdatedAt = now, |
| | 1 | 469 | | Competition = _competition, |
| | 1 | 470 | | Model = model, |
| | 1 | 471 | | TokenUsage = tokenUsage, |
| | 1 | 472 | | Cost = cost, |
| | 1 | 473 | | CommunityContext = communityContext, |
| | 1 | 474 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 475 | | RepredictionIndex = repredictionIndex |
| | 1 | 476 | | }; |
| | | 477 | | |
| | | 478 | | // Set CreatedAt: preserve existing value for updates unless overrideCreatedAt is explicitly requested |
| | 1 | 479 | | firestoreBonusPrediction.CreatedAt = (overrideCreatedAt || existingCreatedAt == null) ? now : existingCreate |
| | | 480 | | |
| | 1 | 481 | | await docRef.SetAsync(firestoreBonusPrediction, cancellationToken: cancellationToken); |
| | | 482 | | |
| | 1 | 483 | | var action = isUpdate ? "Updated" : "Saved"; |
| | 1 | 484 | | _logger.LogDebug("{Action} bonus prediction for question '{QuestionText}' with selections: {SelectedOptions} |
| | 1 | 485 | | action, bonusQuestion.Text, string.Join(", ", selectedOptionTexts), repredictionIndex); |
| | 1 | 486 | | } |
| | 0 | 487 | | catch (Exception ex) |
| | | 488 | | { |
| | 0 | 489 | | _logger.LogError(ex, "Failed to save bonus prediction for question: {QuestionText}", |
| | 0 | 490 | | bonusQuestion.Text); |
| | 0 | 491 | | throw; |
| | | 492 | | } |
| | 1 | 493 | | } |
| | | 494 | | |
| | | 495 | | public async Task<BonusPrediction?> GetBonusPredictionAsync(string questionId, string model, string communityContext |
| | | 496 | | { |
| | | 497 | | try |
| | | 498 | | { |
| | | 499 | | // Query by questionId, model, community context, and competition instead of using direct document lookup |
| | 1 | 500 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 501 | | .WhereEqualTo("questionId", questionId) |
| | 1 | 502 | | .WhereEqualTo("competition", _competition) |
| | 1 | 503 | | .WhereEqualTo("model", model) |
| | 1 | 504 | | .WhereEqualTo("communityContext", communityContext); |
| | | 505 | | |
| | 1 | 506 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 507 | | |
| | 1 | 508 | | if (snapshot.Documents.Count == 0) |
| | | 509 | | { |
| | 1 | 510 | | return null; |
| | | 511 | | } |
| | | 512 | | |
| | 1 | 513 | | var firestoreBonusPrediction = snapshot.Documents |
| | 1 | 514 | | .Select(document => document.ConvertTo<FirestoreBonusPrediction>()) |
| | 1 | 515 | | .OrderByDescending(prediction => prediction.RepredictionIndex) |
| | 1 | 516 | | .ThenByDescending(prediction => prediction.CreatedAt.ToDateTimeOffset()) |
| | 1 | 517 | | .ThenBy(prediction => prediction.Id, StringComparer.Ordinal) |
| | 1 | 518 | | .First(); |
| | | 519 | | |
| | 1 | 520 | | return new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | | 521 | | } |
| | 0 | 522 | | catch (Exception ex) |
| | | 523 | | { |
| | 0 | 524 | | _logger.LogError(ex, "Failed to get bonus prediction for question {QuestionId} using model {Model} and commu |
| | 0 | 525 | | throw; |
| | | 526 | | } |
| | 1 | 527 | | } |
| | | 528 | | |
| | | 529 | | public async Task<BonusPrediction?> GetBonusPredictionByTextAsync(string questionText, string model, string communit |
| | | 530 | | { |
| | | 531 | | try |
| | | 532 | | { |
| | | 533 | | // Query by questionText, model, and community context |
| | | 534 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 535 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 536 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 537 | | .WhereEqualTo("competition", _competition) |
| | 1 | 538 | | .WhereEqualTo("model", model) |
| | 1 | 539 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 540 | | .OrderByDescending("repredictionIndex") |
| | 1 | 541 | | .Limit(1); |
| | | 542 | | |
| | 1 | 543 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 544 | | |
| | 1 | 545 | | if (snapshot.Documents.Count == 0) |
| | | 546 | | { |
| | 1 | 547 | | _logger.LogDebug("No bonus prediction found for question text: {QuestionText} with model: {Model} and co |
| | 1 | 548 | | return null; |
| | | 549 | | } |
| | | 550 | | |
| | 1 | 551 | | var firestoreBonusPrediction = snapshot.Documents.First().ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 552 | | var bonusPrediction = new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | | 553 | | |
| | 1 | 554 | | _logger.LogDebug("Found bonus prediction for question text: {QuestionText} with model: {Model} and community |
| | 1 | 555 | | questionText, model, communityContext, firestoreBonusPrediction.RepredictionIndex); |
| | | 556 | | |
| | 1 | 557 | | return bonusPrediction; |
| | | 558 | | } |
| | 0 | 559 | | catch (Exception ex) |
| | | 560 | | { |
| | 0 | 561 | | _logger.LogError(ex, "Failed to retrieve bonus prediction by text: {QuestionText} with model: {Model} and co |
| | 0 | 562 | | throw; |
| | | 563 | | } |
| | 1 | 564 | | } |
| | | 565 | | |
| | | 566 | | public async Task<BonusPredictionMetadata?> GetBonusPredictionMetadataByTextAsync(string questionText, string model, |
| | | 567 | | { |
| | | 568 | | try |
| | | 569 | | { |
| | | 570 | | // Query by questionText, model, and community context. |
| | | 571 | | // Order by repredictionIndex descending to align metadata reads with latest bonus prediction retrieval. |
| | 1 | 572 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 573 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 574 | | .WhereEqualTo("competition", _competition) |
| | 1 | 575 | | .WhereEqualTo("model", model) |
| | 1 | 576 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 577 | | .OrderByDescending("repredictionIndex") |
| | 1 | 578 | | .Limit(1); |
| | | 579 | | |
| | 1 | 580 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 581 | | |
| | 1 | 582 | | if (snapshot.Documents.Count == 0) |
| | | 583 | | { |
| | 0 | 584 | | _logger.LogDebug("No bonus prediction metadata found for question text: {QuestionText} with model: {Mode |
| | 0 | 585 | | return null; |
| | | 586 | | } |
| | | 587 | | |
| | 1 | 588 | | var firestoreBonusPrediction = snapshot.Documents.First().ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 589 | | var bonusPrediction = new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | 1 | 590 | | var createdAt = firestoreBonusPrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 591 | | var contextDocumentNames = firestoreBonusPrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 592 | | |
| | 1 | 593 | | _logger.LogDebug("Found bonus prediction metadata for question text: {QuestionText} with model: {Model} and |
| | 1 | 594 | | questionText, model, communityContext); |
| | | 595 | | |
| | 1 | 596 | | return new BonusPredictionMetadata(bonusPrediction, createdAt, contextDocumentNames); |
| | | 597 | | } |
| | 0 | 598 | | catch (Exception ex) |
| | | 599 | | { |
| | 0 | 600 | | _logger.LogError(ex, "Failed to retrieve bonus prediction metadata by text: {QuestionText} with model: {Mode |
| | 0 | 601 | | throw; |
| | | 602 | | } |
| | 1 | 603 | | } |
| | | 604 | | |
| | | 605 | | public async Task<IReadOnlyList<BonusPrediction>> GetAllBonusPredictionsAsync(string model, string communityContext, |
| | | 606 | | { |
| | | 607 | | try |
| | | 608 | | { |
| | 1 | 609 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 610 | | .WhereEqualTo("competition", _competition) |
| | 1 | 611 | | .WhereEqualTo("model", model) |
| | 1 | 612 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 613 | | .OrderBy("createdAt"); |
| | | 614 | | |
| | 1 | 615 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 616 | | |
| | 1 | 617 | | var bonusPredictions = new List<BonusPrediction>(); |
| | 1 | 618 | | foreach (var document in snapshot.Documents) |
| | | 619 | | { |
| | 1 | 620 | | var firestoreBonusPrediction = document.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 621 | | bonusPredictions.Add(new BonusPrediction( |
| | 1 | 622 | | firestoreBonusPrediction.SelectedOptionIds.ToList())); |
| | | 623 | | } |
| | | 624 | | |
| | 1 | 625 | | return bonusPredictions.AsReadOnly(); |
| | | 626 | | } |
| | 0 | 627 | | catch (Exception ex) |
| | | 628 | | { |
| | 0 | 629 | | _logger.LogError(ex, "Failed to get all bonus predictions for model {Model} and community context {Community |
| | 0 | 630 | | throw; |
| | | 631 | | } |
| | 1 | 632 | | } |
| | | 633 | | |
| | | 634 | | public async Task<bool> HasBonusPredictionAsync(string questionId, string model, string communityContext, Cancellati |
| | | 635 | | { |
| | | 636 | | try |
| | | 637 | | { |
| | | 638 | | // Query by questionId, model, and community context instead of using direct document lookup |
| | 1 | 639 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 640 | | .WhereEqualTo("questionId", questionId) |
| | 1 | 641 | | .WhereEqualTo("competition", _competition) |
| | 1 | 642 | | .WhereEqualTo("model", model) |
| | 1 | 643 | | .WhereEqualTo("communityContext", communityContext); |
| | | 644 | | |
| | 1 | 645 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 646 | | return snapshot.Documents.Count > 0; |
| | | 647 | | } |
| | 0 | 648 | | catch (Exception ex) |
| | | 649 | | { |
| | 0 | 650 | | _logger.LogError(ex, "Failed to check if bonus prediction exists for question {QuestionId} using model {Mode |
| | 0 | 651 | | throw; |
| | | 652 | | } |
| | 1 | 653 | | } |
| | | 654 | | |
| | | 655 | | /// <summary> |
| | | 656 | | /// Stores a match in the matches collection for matchday management. |
| | | 657 | | /// This is typically called when importing match schedules. |
| | | 658 | | /// </summary> |
| | | 659 | | public async Task StoreMatchAsync(Match match, CancellationToken cancellationToken = default) |
| | | 660 | | { |
| | | 661 | | try |
| | | 662 | | { |
| | 1 | 663 | | var documentId = Guid.NewGuid().ToString(); |
| | | 664 | | |
| | 1 | 665 | | var firestoreMatch = new FirestoreMatch |
| | 1 | 666 | | { |
| | 1 | 667 | | Id = documentId, |
| | 1 | 668 | | HomeTeam = match.HomeTeam, |
| | 1 | 669 | | AwayTeam = match.AwayTeam, |
| | 1 | 670 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 671 | | Matchday = match.Matchday, |
| | 1 | 672 | | Competition = _competition, |
| | 1 | 673 | | IsCancelled = match.IsCancelled |
| | 1 | 674 | | }; |
| | | 675 | | |
| | 1 | 676 | | await _firestoreDb.Collection(_matchesCollection) |
| | 1 | 677 | | .Document(documentId) |
| | 1 | 678 | | .SetAsync(firestoreMatch, cancellationToken: cancellationToken); |
| | | 679 | | |
| | 1 | 680 | | _logger.LogDebug("Stored match {HomeTeam} vs {AwayTeam} for matchday {Matchday}{Cancelled}", |
| | 1 | 681 | | match.HomeTeam, match.AwayTeam, match.Matchday, match.IsCancelled ? " (CANCELLED)" : ""); |
| | 1 | 682 | | } |
| | 0 | 683 | | catch (Exception ex) |
| | | 684 | | { |
| | 0 | 685 | | _logger.LogError(ex, "Failed to store match {HomeTeam} vs {AwayTeam}", |
| | 0 | 686 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 687 | | throw; |
| | | 688 | | } |
| | 1 | 689 | | } |
| | | 690 | | |
| | | 691 | | private static Timestamp ConvertToTimestamp(ZonedDateTime zonedDateTime) |
| | | 692 | | { |
| | 1 | 693 | | var instant = zonedDateTime.ToInstant(); |
| | 1 | 694 | | return Timestamp.FromDateTimeOffset(instant.ToDateTimeOffset()); |
| | | 695 | | } |
| | | 696 | | |
| | | 697 | | private static ZonedDateTime ConvertFromTimestamp(Timestamp timestamp) |
| | | 698 | | { |
| | 1 | 699 | | var dateTimeOffset = timestamp.ToDateTimeOffset(); |
| | 1 | 700 | | var instant = Instant.FromDateTimeOffset(dateTimeOffset); |
| | 1 | 701 | | return instant.InUtc(); |
| | | 702 | | } |
| | | 703 | | |
| | | 704 | | public async Task<int> GetMatchRepredictionIndexAsync(Match match, string model, string communityContext, Cancellati |
| | | 705 | | { |
| | | 706 | | try |
| | | 707 | | { |
| | | 708 | | // Query by match characteristics, model, community context, and competition |
| | | 709 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 710 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 711 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 712 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 713 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 714 | | .WhereEqualTo("competition", _competition) |
| | 1 | 715 | | .WhereEqualTo("model", model) |
| | 1 | 716 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 717 | | .OrderByDescending("repredictionIndex") |
| | 1 | 718 | | .Limit(1); |
| | | 719 | | |
| | 1 | 720 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 721 | | |
| | 1 | 722 | | if (snapshot.Documents.Count == 0) |
| | | 723 | | { |
| | 1 | 724 | | return -1; // No prediction exists |
| | | 725 | | } |
| | | 726 | | |
| | 1 | 727 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 728 | | return firestorePrediction.RepredictionIndex; |
| | | 729 | | } |
| | 0 | 730 | | catch (Exception ex) |
| | | 731 | | { |
| | 0 | 732 | | _logger.LogError(ex, "Failed to get reprediction index for match {HomeTeam} vs {AwayTeam} using model {Model |
| | 0 | 733 | | match.HomeTeam, match.AwayTeam, model, communityContext); |
| | 0 | 734 | | throw; |
| | | 735 | | } |
| | 1 | 736 | | } |
| | | 737 | | |
| | | 738 | | // See IPredictionRepository.cs for detailed documentation on why these methods exist. |
| | | 739 | | // In short: cancelled matches have inconsistent startsAt values across different Kicktipp pages, |
| | | 740 | | // so we query by team names only to find predictions regardless of which startsAt was used. |
| | | 741 | | |
| | | 742 | | /// <inheritdoc /> |
| | | 743 | | public async Task<Prediction?> GetCancelledMatchPredictionAsync(string homeTeam, string awayTeam, string model, stri |
| | | 744 | | { |
| | | 745 | | try |
| | | 746 | | { |
| | | 747 | | // Query by team names only (no startsAt), ordered by createdAt descending to get the most recent |
| | | 748 | | // We use repredictionIndex descending first to get the latest reprediction, then createdAt for tiebreaking |
| | 1 | 749 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 750 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 751 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 752 | | .WhereEqualTo("competition", _competition) |
| | 1 | 753 | | .WhereEqualTo("model", model) |
| | 1 | 754 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 755 | | .OrderByDescending("createdAt") |
| | 1 | 756 | | .Limit(1); |
| | | 757 | | |
| | 1 | 758 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 759 | | |
| | 1 | 760 | | if (snapshot.Documents.Count == 0) |
| | | 761 | | { |
| | 1 | 762 | | _logger.LogDebug("No prediction found for cancelled match {HomeTeam} vs {AwayTeam} (team-names-only look |
| | 1 | 763 | | return null; |
| | | 764 | | } |
| | | 765 | | |
| | 1 | 766 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 767 | | _logger.LogDebug("Found prediction for cancelled match {HomeTeam} vs {AwayTeam} with startsAt={StartsAt} (te |
| | 1 | 768 | | homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 769 | | |
| | 1 | 770 | | return new Prediction( |
| | 1 | 771 | | firestorePrediction.HomeGoals, |
| | 1 | 772 | | firestorePrediction.AwayGoals, |
| | 1 | 773 | | DeserializeJustification(firestorePrediction.Justification)); |
| | | 774 | | } |
| | 0 | 775 | | catch (Exception ex) |
| | | 776 | | { |
| | 0 | 777 | | _logger.LogError(ex, "Failed to get prediction for cancelled match {HomeTeam} vs {AwayTeam} using model {Mod |
| | 0 | 778 | | homeTeam, awayTeam, model, communityContext); |
| | 0 | 779 | | throw; |
| | | 780 | | } |
| | 1 | 781 | | } |
| | | 782 | | |
| | | 783 | | /// <inheritdoc /> |
| | | 784 | | public async Task<PredictionMetadata?> GetCancelledMatchPredictionMetadataAsync(string homeTeam, string awayTeam, st |
| | | 785 | | { |
| | | 786 | | try |
| | | 787 | | { |
| | | 788 | | // Query by team names only (no startsAt), ordered by repredictionIndex descending to get the latest repredi |
| | 1 | 789 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 790 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 791 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 792 | | .WhereEqualTo("competition", _competition) |
| | 1 | 793 | | .WhereEqualTo("model", model) |
| | 1 | 794 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 795 | | .OrderByDescending("repredictionIndex") |
| | 1 | 796 | | .Limit(1); |
| | | 797 | | |
| | 1 | 798 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 799 | | |
| | 1 | 800 | | if (snapshot.Documents.Count == 0) |
| | | 801 | | { |
| | 1 | 802 | | _logger.LogDebug("No prediction metadata found for cancelled match {HomeTeam} vs {AwayTeam} (team-names- |
| | 1 | 803 | | return null; |
| | | 804 | | } |
| | | 805 | | |
| | 1 | 806 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 807 | | _logger.LogDebug("Found prediction metadata for cancelled match {HomeTeam} vs {AwayTeam} with startsAt={Star |
| | 1 | 808 | | homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 809 | | |
| | 1 | 810 | | var prediction = new Prediction( |
| | 1 | 811 | | firestorePrediction.HomeGoals, |
| | 1 | 812 | | firestorePrediction.AwayGoals, |
| | 1 | 813 | | DeserializeJustification(firestorePrediction.Justification)); |
| | 1 | 814 | | var createdAt = firestorePrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 815 | | var contextDocumentNames = firestorePrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 816 | | |
| | 1 | 817 | | return new PredictionMetadata(prediction, createdAt, contextDocumentNames); |
| | | 818 | | } |
| | 0 | 819 | | catch (Exception ex) |
| | | 820 | | { |
| | 0 | 821 | | _logger.LogError(ex, "Failed to get prediction metadata for cancelled match {HomeTeam} vs {AwayTeam} using m |
| | 0 | 822 | | homeTeam, awayTeam, model, communityContext); |
| | 0 | 823 | | throw; |
| | | 824 | | } |
| | 1 | 825 | | } |
| | | 826 | | |
| | | 827 | | /// <inheritdoc /> |
| | | 828 | | public async Task<int> GetCancelledMatchRepredictionIndexAsync(string homeTeam, string awayTeam, string model, strin |
| | | 829 | | { |
| | | 830 | | try |
| | | 831 | | { |
| | | 832 | | // Query by team names only (no startsAt), ordered by repredictionIndex descending to get the highest |
| | 1 | 833 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 834 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 835 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 836 | | .WhereEqualTo("competition", _competition) |
| | 1 | 837 | | .WhereEqualTo("model", model) |
| | 1 | 838 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 839 | | .OrderByDescending("repredictionIndex") |
| | 1 | 840 | | .Limit(1); |
| | | 841 | | |
| | 1 | 842 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 843 | | |
| | 1 | 844 | | if (snapshot.Documents.Count == 0) |
| | | 845 | | { |
| | 1 | 846 | | _logger.LogDebug("No reprediction index found for cancelled match {HomeTeam} vs {AwayTeam} (team-names-o |
| | 1 | 847 | | return -1; |
| | | 848 | | } |
| | | 849 | | |
| | 1 | 850 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 851 | | _logger.LogDebug("Found reprediction index {Index} for cancelled match {HomeTeam} vs {AwayTeam} with startsA |
| | 1 | 852 | | firestorePrediction.RepredictionIndex, homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 853 | | |
| | 1 | 854 | | return firestorePrediction.RepredictionIndex; |
| | | 855 | | } |
| | 0 | 856 | | catch (Exception ex) |
| | | 857 | | { |
| | 0 | 858 | | _logger.LogError(ex, "Failed to get reprediction index for cancelled match {HomeTeam} vs {AwayTeam} using mo |
| | 0 | 859 | | homeTeam, awayTeam, model, communityContext); |
| | 0 | 860 | | throw; |
| | | 861 | | } |
| | 1 | 862 | | } |
| | | 863 | | |
| | | 864 | | public async Task<int> GetBonusRepredictionIndexAsync(string questionText, string model, string communityContext, Ca |
| | | 865 | | { |
| | | 866 | | try |
| | | 867 | | { |
| | | 868 | | // Query by question text, model, community context, and competition |
| | | 869 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 870 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 871 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 872 | | .WhereEqualTo("competition", _competition) |
| | 1 | 873 | | .WhereEqualTo("model", model) |
| | 1 | 874 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 875 | | .OrderByDescending("repredictionIndex") |
| | 1 | 876 | | .Limit(1); |
| | | 877 | | |
| | 1 | 878 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 879 | | |
| | 1 | 880 | | if (snapshot.Documents.Count == 0) |
| | | 881 | | { |
| | 1 | 882 | | return -1; // No prediction exists |
| | | 883 | | } |
| | | 884 | | |
| | 1 | 885 | | var firestorePrediction = snapshot.Documents.First().ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 886 | | return firestorePrediction.RepredictionIndex; |
| | | 887 | | } |
| | 0 | 888 | | catch (Exception ex) |
| | | 889 | | { |
| | 0 | 890 | | _logger.LogError(ex, "Failed to get reprediction index for bonus question '{QuestionText}' using model {Mode |
| | 0 | 891 | | questionText, model, communityContext); |
| | 0 | 892 | | throw; |
| | | 893 | | } |
| | 1 | 894 | | } |
| | | 895 | | |
| | | 896 | | public async Task SaveRepredictionAsync(Match match, Prediction prediction, string model, string tokenUsage, double |
| | | 897 | | { |
| | | 898 | | try |
| | | 899 | | { |
| | 1 | 900 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 901 | | |
| | | 902 | | // Create new document for this reprediction |
| | 1 | 903 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 904 | | var docRef = _firestoreDb.Collection(_predictionsCollection).Document(documentId); |
| | | 905 | | |
| | 1 | 906 | | _logger.LogDebug("Creating reprediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId}, repredic |
| | 1 | 907 | | match.HomeTeam, match.AwayTeam, documentId, repredictionIndex); |
| | | 908 | | |
| | 1 | 909 | | var firestorePrediction = new FirestoreMatchPrediction |
| | 1 | 910 | | { |
| | 1 | 911 | | Id = docRef.Id, |
| | 1 | 912 | | HomeTeam = match.HomeTeam, |
| | 1 | 913 | | AwayTeam = match.AwayTeam, |
| | 1 | 914 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 915 | | Matchday = match.Matchday, |
| | 1 | 916 | | HomeGoals = prediction.HomeGoals, |
| | 1 | 917 | | AwayGoals = prediction.AwayGoals, |
| | 1 | 918 | | Justification = SerializeJustification(prediction.Justification), |
| | 1 | 919 | | CreatedAt = now, |
| | 1 | 920 | | UpdatedAt = now, |
| | 1 | 921 | | Competition = _competition, |
| | 1 | 922 | | Model = model, |
| | 1 | 923 | | TokenUsage = tokenUsage, |
| | 1 | 924 | | Cost = cost, |
| | 1 | 925 | | CommunityContext = communityContext, |
| | 1 | 926 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 927 | | RepredictionIndex = repredictionIndex |
| | 1 | 928 | | }; |
| | | 929 | | |
| | 1 | 930 | | await docRef.SetAsync(firestorePrediction, cancellationToken: cancellationToken); |
| | | 931 | | |
| | 1 | 932 | | _logger.LogInformation("Saved reprediction for match {HomeTeam} vs {AwayTeam} on matchday {Matchday} (repred |
| | 1 | 933 | | match.HomeTeam, match.AwayTeam, match.Matchday, repredictionIndex); |
| | 1 | 934 | | } |
| | 0 | 935 | | catch (Exception ex) |
| | | 936 | | { |
| | 0 | 937 | | _logger.LogError(ex, "Failed to save reprediction for match {HomeTeam} vs {AwayTeam}", |
| | 0 | 938 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 939 | | throw; |
| | | 940 | | } |
| | 1 | 941 | | } |
| | | 942 | | |
| | | 943 | | public async Task SaveBonusRepredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, string mo |
| | | 944 | | { |
| | | 945 | | try |
| | | 946 | | { |
| | 1 | 947 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 948 | | |
| | | 949 | | // Create new document for this reprediction |
| | 1 | 950 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 951 | | var docRef = _firestoreDb.Collection(_bonusPredictionsCollection).Document(documentId); |
| | | 952 | | |
| | 1 | 953 | | _logger.LogDebug("Creating bonus reprediction for question '{QuestionText}' (document: {DocumentId}, repredi |
| | 1 | 954 | | bonusQuestion.Text, documentId, repredictionIndex); |
| | | 955 | | |
| | | 956 | | // Extract selected option texts for observability |
| | 1 | 957 | | var optionTextsLookup = bonusQuestion.Options.ToDictionary(o => o.Id, o => o.Text); |
| | 1 | 958 | | var selectedOptionTexts = bonusPrediction.SelectedOptionIds |
| | 1 | 959 | | .Select(id => optionTextsLookup.TryGetValue(id, out var text) ? text : $"Unknown option: {id}") |
| | 1 | 960 | | .ToArray(); |
| | | 961 | | |
| | 1 | 962 | | var firestoreBonusPrediction = new FirestoreBonusPrediction |
| | 1 | 963 | | { |
| | 1 | 964 | | Id = docRef.Id, |
| | 1 | 965 | | QuestionText = bonusQuestion.Text, |
| | 1 | 966 | | SelectedOptionIds = bonusPrediction.SelectedOptionIds.ToArray(), |
| | 1 | 967 | | SelectedOptionTexts = selectedOptionTexts, |
| | 1 | 968 | | CreatedAt = now, |
| | 1 | 969 | | UpdatedAt = now, |
| | 1 | 970 | | Competition = _competition, |
| | 1 | 971 | | Model = model, |
| | 1 | 972 | | TokenUsage = tokenUsage, |
| | 1 | 973 | | Cost = cost, |
| | 1 | 974 | | CommunityContext = communityContext, |
| | 1 | 975 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 976 | | RepredictionIndex = repredictionIndex |
| | 1 | 977 | | }; |
| | | 978 | | |
| | 1 | 979 | | await docRef.SetAsync(firestoreBonusPrediction, cancellationToken: cancellationToken); |
| | | 980 | | |
| | 1 | 981 | | _logger.LogInformation("Saved bonus reprediction for question '{QuestionText}' (reprediction index: {Repredi |
| | 1 | 982 | | bonusQuestion.Text, repredictionIndex); |
| | 1 | 983 | | } |
| | 0 | 984 | | catch (Exception ex) |
| | | 985 | | { |
| | 0 | 986 | | _logger.LogError(ex, "Failed to save bonus reprediction for question: {QuestionText}", |
| | 0 | 987 | | bonusQuestion.Text); |
| | 0 | 988 | | throw; |
| | | 989 | | } |
| | 1 | 990 | | } |
| | | 991 | | |
| | | 992 | | /// <summary> |
| | | 993 | | /// Get match prediction costs and counts grouped by reprediction index for cost analysis. |
| | | 994 | | /// Used specifically by the cost command to include all repredictions. |
| | | 995 | | /// </summary> |
| | | 996 | | public async Task<Dictionary<int, (double cost, int count)>> GetMatchPredictionCostsByRepredictionIndexAsync( |
| | | 997 | | string model, |
| | | 998 | | string communityContext, |
| | | 999 | | List<int>? matchdays = null, |
| | | 1000 | | CancellationToken cancellationToken = default) |
| | | 1001 | | { |
| | | 1002 | | try |
| | | 1003 | | { |
| | 1 | 1004 | | var costsByIndex = new Dictionary<int, (double cost, int count)>(); |
| | | 1005 | | |
| | | 1006 | | // Query for match predictions with cost data |
| | 1 | 1007 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1008 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1009 | | .WhereEqualTo("model", model) |
| | 1 | 1010 | | .WhereEqualTo("communityContext", communityContext); |
| | | 1011 | | |
| | | 1012 | | // Add matchday filter if specified |
| | 1 | 1013 | | if (matchdays?.Count > 0) |
| | | 1014 | | { |
| | 1 | 1015 | | query = query.WhereIn("matchday", matchdays.Cast<object>().ToArray()); |
| | | 1016 | | } |
| | | 1017 | | |
| | 1 | 1018 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1019 | | |
| | 1 | 1020 | | foreach (var doc in snapshot.Documents) |
| | | 1021 | | { |
| | 1 | 1022 | | if (doc.Exists) |
| | | 1023 | | { |
| | 1 | 1024 | | var prediction = doc.ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 1025 | | var repredictionIndex = prediction.RepredictionIndex; |
| | | 1026 | | |
| | 1 | 1027 | | if (!costsByIndex.ContainsKey(repredictionIndex)) |
| | | 1028 | | { |
| | 1 | 1029 | | costsByIndex[repredictionIndex] = (0.0, 0); |
| | | 1030 | | } |
| | | 1031 | | |
| | 1 | 1032 | | var (currentCost, currentCount) = costsByIndex[repredictionIndex]; |
| | 1 | 1033 | | costsByIndex[repredictionIndex] = (currentCost + prediction.Cost, currentCount + 1); |
| | | 1034 | | } |
| | | 1035 | | } |
| | | 1036 | | |
| | 1 | 1037 | | return costsByIndex; |
| | | 1038 | | } |
| | 0 | 1039 | | catch (Exception ex) |
| | | 1040 | | { |
| | 0 | 1041 | | _logger.LogError(ex, "Failed to get match prediction costs by reprediction index for model {Model} and commu |
| | 0 | 1042 | | model, communityContext); |
| | 0 | 1043 | | throw; |
| | | 1044 | | } |
| | 1 | 1045 | | } |
| | | 1046 | | |
| | | 1047 | | /// <summary> |
| | | 1048 | | /// Get bonus prediction costs and counts grouped by reprediction index for cost analysis. |
| | | 1049 | | /// Used specifically by the cost command to include all repredictions. |
| | | 1050 | | /// </summary> |
| | | 1051 | | public async Task<Dictionary<int, (double cost, int count)>> GetBonusPredictionCostsByRepredictionIndexAsync( |
| | | 1052 | | string model, |
| | | 1053 | | string communityContext, |
| | | 1054 | | CancellationToken cancellationToken = default) |
| | | 1055 | | { |
| | | 1056 | | try |
| | | 1057 | | { |
| | 1 | 1058 | | var costsByIndex = new Dictionary<int, (double cost, int count)>(); |
| | | 1059 | | |
| | | 1060 | | // Query for bonus predictions with cost data |
| | 1 | 1061 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1062 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1063 | | .WhereEqualTo("model", model) |
| | 1 | 1064 | | .WhereEqualTo("communityContext", communityContext); |
| | | 1065 | | |
| | 1 | 1066 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1067 | | |
| | 1 | 1068 | | foreach (var doc in snapshot.Documents) |
| | | 1069 | | { |
| | 1 | 1070 | | if (doc.Exists) |
| | | 1071 | | { |
| | 1 | 1072 | | var prediction = doc.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 1073 | | var repredictionIndex = prediction.RepredictionIndex; |
| | | 1074 | | |
| | 1 | 1075 | | if (!costsByIndex.ContainsKey(repredictionIndex)) |
| | | 1076 | | { |
| | 1 | 1077 | | costsByIndex[repredictionIndex] = (0.0, 0); |
| | | 1078 | | } |
| | | 1079 | | |
| | 1 | 1080 | | var (currentCost, currentCount) = costsByIndex[repredictionIndex]; |
| | 1 | 1081 | | costsByIndex[repredictionIndex] = (currentCost + prediction.Cost, currentCount + 1); |
| | | 1082 | | } |
| | | 1083 | | } |
| | | 1084 | | |
| | 1 | 1085 | | return costsByIndex; |
| | | 1086 | | } |
| | 0 | 1087 | | catch (Exception ex) |
| | | 1088 | | { |
| | 0 | 1089 | | _logger.LogError(ex, "Failed to get bonus prediction costs by reprediction index for model {Model} and commu |
| | 0 | 1090 | | model, communityContext); |
| | 0 | 1091 | | throw; |
| | | 1092 | | } |
| | 1 | 1093 | | } |
| | | 1094 | | |
| | | 1095 | | /// <inheritdoc /> |
| | | 1096 | | public async Task<List<int>> GetAvailableMatchdaysAsync(CancellationToken cancellationToken = default) |
| | | 1097 | | { |
| | | 1098 | | try |
| | | 1099 | | { |
| | 1 | 1100 | | var matchdays = new HashSet<int>(); |
| | | 1101 | | |
| | | 1102 | | // Query match predictions for unique matchdays |
| | 1 | 1103 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1104 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1105 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1106 | | |
| | 1 | 1107 | | foreach (var doc in snapshot.Documents) |
| | | 1108 | | { |
| | 1 | 1109 | | if (doc.TryGetValue<int>("matchday", out var matchday) && matchday > 0) |
| | | 1110 | | { |
| | 1 | 1111 | | matchdays.Add(matchday); |
| | | 1112 | | } |
| | | 1113 | | } |
| | | 1114 | | |
| | 1 | 1115 | | return matchdays.OrderBy(m => m).ToList(); |
| | | 1116 | | } |
| | 0 | 1117 | | catch (Exception ex) |
| | | 1118 | | { |
| | 0 | 1119 | | _logger.LogError(ex, "Failed to get available matchdays"); |
| | 0 | 1120 | | throw; |
| | | 1121 | | } |
| | 1 | 1122 | | } |
| | | 1123 | | |
| | | 1124 | | /// <inheritdoc /> |
| | | 1125 | | public async Task<List<string>> GetAvailableModelsAsync(CancellationToken cancellationToken = default) |
| | | 1126 | | { |
| | | 1127 | | try |
| | | 1128 | | { |
| | 1 | 1129 | | var models = new HashSet<string>(); |
| | | 1130 | | |
| | | 1131 | | // Query match predictions for unique models |
| | 1 | 1132 | | var matchQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1133 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1134 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 1135 | | |
| | 1 | 1136 | | foreach (var doc in matchSnapshot.Documents) |
| | | 1137 | | { |
| | 1 | 1138 | | if (doc.TryGetValue<string>("model", out var model) && !string.IsNullOrWhiteSpace(model)) |
| | | 1139 | | { |
| | 1 | 1140 | | models.Add(model); |
| | | 1141 | | } |
| | | 1142 | | } |
| | | 1143 | | |
| | | 1144 | | // Query bonus predictions for unique models |
| | 1 | 1145 | | var bonusQuery = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1146 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1147 | | var bonusSnapshot = await bonusQuery.GetSnapshotAsync(cancellationToken); |
| | | 1148 | | |
| | 1 | 1149 | | foreach (var doc in bonusSnapshot.Documents) |
| | | 1150 | | { |
| | 1 | 1151 | | if (doc.TryGetValue<string>("model", out var model) && !string.IsNullOrWhiteSpace(model)) |
| | | 1152 | | { |
| | 1 | 1153 | | models.Add(model); |
| | | 1154 | | } |
| | | 1155 | | } |
| | | 1156 | | |
| | 1 | 1157 | | return models.OrderBy(model => model, StringComparer.Ordinal).ToList(); |
| | | 1158 | | } |
| | 0 | 1159 | | catch (Exception ex) |
| | | 1160 | | { |
| | 0 | 1161 | | _logger.LogError(ex, "Failed to get available models"); |
| | 0 | 1162 | | throw; |
| | | 1163 | | } |
| | 1 | 1164 | | } |
| | | 1165 | | |
| | | 1166 | | /// <inheritdoc /> |
| | | 1167 | | public async Task<List<string>> GetAvailableCommunityContextsAsync(CancellationToken cancellationToken = default) |
| | | 1168 | | { |
| | | 1169 | | try |
| | | 1170 | | { |
| | 1 | 1171 | | var communityContexts = new HashSet<string>(); |
| | | 1172 | | |
| | | 1173 | | // Query match predictions for unique community contexts |
| | 1 | 1174 | | var matchQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1175 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1176 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 1177 | | |
| | 1 | 1178 | | foreach (var doc in matchSnapshot.Documents) |
| | | 1179 | | { |
| | 1 | 1180 | | if (doc.TryGetValue<string>("communityContext", out var context) && !string.IsNullOrWhiteSpace(context)) |
| | | 1181 | | { |
| | 1 | 1182 | | communityContexts.Add(context); |
| | | 1183 | | } |
| | | 1184 | | } |
| | | 1185 | | |
| | | 1186 | | // Query bonus predictions for unique community contexts |
| | 1 | 1187 | | var bonusQuery = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1188 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1189 | | var bonusSnapshot = await bonusQuery.GetSnapshotAsync(cancellationToken); |
| | | 1190 | | |
| | 1 | 1191 | | foreach (var doc in bonusSnapshot.Documents) |
| | | 1192 | | { |
| | 1 | 1193 | | if (doc.TryGetValue<string>("communityContext", out var context) && !string.IsNullOrWhiteSpace(context)) |
| | | 1194 | | { |
| | 1 | 1195 | | communityContexts.Add(context); |
| | | 1196 | | } |
| | | 1197 | | } |
| | | 1198 | | |
| | 1 | 1199 | | return communityContexts.OrderBy(context => context, StringComparer.Ordinal).ToList(); |
| | | 1200 | | } |
| | 0 | 1201 | | catch (Exception ex) |
| | | 1202 | | { |
| | 0 | 1203 | | _logger.LogError(ex, "Failed to get available community contexts"); |
| | 0 | 1204 | | throw; |
| | | 1205 | | } |
| | 1 | 1206 | | } |
| | | 1207 | | |
| | | 1208 | | private string? SerializeJustification(PredictionJustification? justification) |
| | | 1209 | | { |
| | 1 | 1210 | | if (justification == null) |
| | | 1211 | | { |
| | 1 | 1212 | | return null; |
| | | 1213 | | } |
| | | 1214 | | |
| | 1 | 1215 | | if (!HasJustificationContent(justification)) |
| | | 1216 | | { |
| | 1 | 1217 | | return null; |
| | | 1218 | | } |
| | | 1219 | | |
| | 1 | 1220 | | var stored = new StoredJustification |
| | 1 | 1221 | | { |
| | 1 | 1222 | | KeyReasoning = justification.KeyReasoning?.Trim() ?? string.Empty, |
| | 1 | 1223 | | ContextSources = new StoredContextSources |
| | 1 | 1224 | | { |
| | 1 | 1225 | | MostValuable = justification.ContextSources?.MostValuable? |
| | 1 | 1226 | | .Where(entry => entry != null) |
| | 1 | 1227 | | .Select(ToStoredContextSource) |
| | 1 | 1228 | | .ToList() ?? new List<StoredContextSource>(), |
| | 1 | 1229 | | LeastValuable = justification.ContextSources?.LeastValuable? |
| | 1 | 1230 | | .Where(entry => entry != null) |
| | 1 | 1231 | | .Select(ToStoredContextSource) |
| | 1 | 1232 | | .ToList() ?? new List<StoredContextSource>() |
| | 1 | 1233 | | }, |
| | 1 | 1234 | | Uncertainties = justification.Uncertainties? |
| | 1 | 1235 | | .Where(item => !string.IsNullOrWhiteSpace(item)) |
| | 1 | 1236 | | .Select(item => item.Trim()) |
| | 1 | 1237 | | .ToList() ?? new List<string>() |
| | 1 | 1238 | | }; |
| | | 1239 | | |
| | 1 | 1240 | | return JsonSerializer.Serialize(stored, JustificationSerializerOptions); |
| | | 1241 | | } |
| | | 1242 | | |
| | | 1243 | | private static bool HasJustificationContent(PredictionJustification justification) |
| | | 1244 | | { |
| | 1 | 1245 | | if (!string.IsNullOrWhiteSpace(justification.KeyReasoning)) |
| | | 1246 | | { |
| | 1 | 1247 | | return true; |
| | | 1248 | | } |
| | | 1249 | | |
| | 1 | 1250 | | if (justification.ContextSources?.MostValuable != null && |
| | 1 | 1251 | | justification.ContextSources.MostValuable.Any(HasSourceContent)) |
| | | 1252 | | { |
| | 1 | 1253 | | return true; |
| | | 1254 | | } |
| | | 1255 | | |
| | 1 | 1256 | | if (justification.ContextSources?.LeastValuable != null && |
| | 1 | 1257 | | justification.ContextSources.LeastValuable.Any(HasSourceContent)) |
| | | 1258 | | { |
| | 1 | 1259 | | return true; |
| | | 1260 | | } |
| | | 1261 | | |
| | 1 | 1262 | | return justification.Uncertainties != null && |
| | 1 | 1263 | | justification.Uncertainties.Any(item => !string.IsNullOrWhiteSpace(item)); |
| | | 1264 | | } |
| | | 1265 | | |
| | | 1266 | | private static bool HasSourceContent(PredictionJustificationContextSource source) |
| | | 1267 | | { |
| | 1 | 1268 | | return !string.IsNullOrWhiteSpace(source?.DocumentName) || |
| | 1 | 1269 | | !string.IsNullOrWhiteSpace(source?.Details); |
| | | 1270 | | } |
| | | 1271 | | |
| | | 1272 | | private PredictionJustification? DeserializeJustification(string? serialized) |
| | | 1273 | | { |
| | 1 | 1274 | | if (string.IsNullOrWhiteSpace(serialized)) |
| | | 1275 | | { |
| | 1 | 1276 | | return null; |
| | | 1277 | | } |
| | | 1278 | | |
| | 1 | 1279 | | var trimmed = serialized.Trim(); |
| | | 1280 | | |
| | 1 | 1281 | | if (!trimmed.StartsWith("{")) |
| | | 1282 | | { |
| | 0 | 1283 | | return new PredictionJustification( |
| | 0 | 1284 | | trimmed, |
| | 0 | 1285 | | new PredictionJustificationContextSources( |
| | 0 | 1286 | | Array.Empty<PredictionJustificationContextSource>(), |
| | 0 | 1287 | | Array.Empty<PredictionJustificationContextSource>()), |
| | 0 | 1288 | | Array.Empty<string>()); |
| | | 1289 | | } |
| | | 1290 | | |
| | | 1291 | | try |
| | | 1292 | | { |
| | 1 | 1293 | | var stored = JsonSerializer.Deserialize<StoredJustification>(trimmed, JustificationSerializerOptions); |
| | | 1294 | | |
| | 1 | 1295 | | if (stored == null) |
| | | 1296 | | { |
| | 0 | 1297 | | return null; |
| | | 1298 | | } |
| | | 1299 | | |
| | 1 | 1300 | | var contextSources = stored.ContextSources ?? new StoredContextSources(); |
| | | 1301 | | |
| | 1 | 1302 | | var mostValuable = contextSources.MostValuable? |
| | 1 | 1303 | | .Where(entry => entry != null) |
| | 1 | 1304 | | .Select(ToDomainContextSource) |
| | 1 | 1305 | | .ToList() ?? new List<PredictionJustificationContextSource>(); |
| | | 1306 | | |
| | 1 | 1307 | | var leastValuable = contextSources.LeastValuable? |
| | 1 | 1308 | | .Where(entry => entry != null) |
| | 1 | 1309 | | .Select(ToDomainContextSource) |
| | 1 | 1310 | | .ToList() ?? new List<PredictionJustificationContextSource>(); |
| | | 1311 | | |
| | 1 | 1312 | | var uncertainties = stored.Uncertainties? |
| | 1 | 1313 | | .Where(item => !string.IsNullOrWhiteSpace(item)) |
| | 1 | 1314 | | .Select(item => item.Trim()) |
| | 1 | 1315 | | .ToList() ?? new List<string>(); |
| | | 1316 | | |
| | 1 | 1317 | | var justification = new PredictionJustification( |
| | 1 | 1318 | | stored.KeyReasoning?.Trim() ?? string.Empty, |
| | 1 | 1319 | | new PredictionJustificationContextSources(mostValuable, leastValuable), |
| | 1 | 1320 | | uncertainties); |
| | | 1321 | | |
| | 1 | 1322 | | return HasJustificationContent(justification) ? justification : null; |
| | | 1323 | | } |
| | 0 | 1324 | | catch (JsonException ex) |
| | | 1325 | | { |
| | 0 | 1326 | | _logger.LogWarning(ex, "Failed to parse structured justification JSON; falling back to legacy text format"); |
| | | 1327 | | |
| | 0 | 1328 | | var fallbackJustification = new PredictionJustification( |
| | 0 | 1329 | | trimmed, |
| | 0 | 1330 | | new PredictionJustificationContextSources( |
| | 0 | 1331 | | Array.Empty<PredictionJustificationContextSource>(), |
| | 0 | 1332 | | Array.Empty<PredictionJustificationContextSource>()), |
| | 0 | 1333 | | Array.Empty<string>()); |
| | | 1334 | | |
| | 0 | 1335 | | return HasJustificationContent(fallbackJustification) ? fallbackJustification : null; |
| | | 1336 | | } |
| | 1 | 1337 | | } |
| | | 1338 | | |
| | | 1339 | | private static StoredContextSource ToStoredContextSource(PredictionJustificationContextSource source) |
| | | 1340 | | { |
| | 1 | 1341 | | return new StoredContextSource |
| | 1 | 1342 | | { |
| | 1 | 1343 | | DocumentName = source.DocumentName?.Trim() ?? string.Empty, |
| | 1 | 1344 | | Details = source.Details?.Trim() ?? string.Empty |
| | 1 | 1345 | | }; |
| | | 1346 | | } |
| | | 1347 | | |
| | | 1348 | | private static PredictionJustificationContextSource ToDomainContextSource(StoredContextSource source) |
| | | 1349 | | { |
| | 1 | 1350 | | var documentName = source.DocumentName?.Trim() ?? string.Empty; |
| | 1 | 1351 | | var details = source.Details?.Trim() ?? string.Empty; |
| | 1 | 1352 | | return new PredictionJustificationContextSource(documentName, details); |
| | | 1353 | | } |
| | | 1354 | | |
| | | 1355 | | private sealed class StoredJustification |
| | | 1356 | | { |
| | 1 | 1357 | | public string? KeyReasoning { get; set; } |
| | 1 | 1358 | | public StoredContextSources? ContextSources { get; set; } |
| | 1 | 1359 | | public List<string>? Uncertainties { get; set; } |
| | | 1360 | | } |
| | | 1361 | | |
| | | 1362 | | private sealed class StoredContextSources |
| | | 1363 | | { |
| | 1 | 1364 | | public List<StoredContextSource>? MostValuable { get; set; } |
| | 1 | 1365 | | public List<StoredContextSource>? LeastValuable { get; set; } |
| | | 1366 | | } |
| | | 1367 | | |
| | | 1368 | | private sealed class StoredContextSource |
| | | 1369 | | { |
| | 1 | 1370 | | public string? DocumentName { get; set; } |
| | 1 | 1371 | | public string? Details { get; set; } |
| | | 1372 | | } |
| | | 1373 | | } |