| | | 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 | | |
| | | 31 | | private enum PredictionConfigMatchKind |
| | | 32 | | { |
| | | 33 | | None = 0, |
| | | 34 | | LegacyModelOnly = 1, |
| | | 35 | | Exact = 2 |
| | | 36 | | } |
| | | 37 | | |
| | 1 | 38 | | public FirebasePredictionRepository( |
| | 1 | 39 | | FirestoreDb firestoreDb, |
| | 1 | 40 | | ILogger<FirebasePredictionRepository> logger, |
| | 1 | 41 | | string? competition = null) |
| | | 42 | | { |
| | 1 | 43 | | _firestoreDb = firestoreDb ?? throw new ArgumentNullException(nameof(firestoreDb)); |
| | 1 | 44 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | | 45 | | |
| | | 46 | | // Use unified collection names (no longer community-specific) |
| | 1 | 47 | | _predictionsCollection = "match-predictions"; |
| | 1 | 48 | | _matchesCollection = "matches"; |
| | 1 | 49 | | _bonusPredictionsCollection = "bonus-predictions"; |
| | 1 | 50 | | _competition = string.IsNullOrWhiteSpace(competition) |
| | 1 | 51 | | ? CompetitionIds.Bundesliga2025_26 |
| | 1 | 52 | | : competition.Trim(); |
| | | 53 | | |
| | 1 | 54 | | _logger.LogInformation("Firebase repository initialized"); |
| | 1 | 55 | | } |
| | | 56 | | |
| | | 57 | | private static PredictionConfigMatchKind GetConfigMatchKind(FirestoreMatchPrediction prediction, PredictionModelConf |
| | | 58 | | { |
| | 1 | 59 | | return GetConfigMatchKind(prediction.ModelConfigKey, prediction.ReasoningEffort, modelConfig); |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | private static PredictionConfigMatchKind GetConfigMatchKind(FirestoreBonusPrediction prediction, PredictionModelConf |
| | | 63 | | { |
| | 1 | 64 | | return GetConfigMatchKind(prediction.ModelConfigKey, prediction.ReasoningEffort, modelConfig); |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | private static PredictionConfigMatchKind GetConfigMatchKind( |
| | | 68 | | string? storedModelConfigKey, |
| | | 69 | | string? storedReasoningEffort, |
| | | 70 | | PredictionModelConfig modelConfig) |
| | | 71 | | { |
| | 1 | 72 | | if (!string.IsNullOrWhiteSpace(storedModelConfigKey)) |
| | | 73 | | { |
| | 1 | 74 | | return string.Equals(storedModelConfigKey.Trim(), modelConfig.IdentityKey, StringComparison.Ordinal) |
| | 1 | 75 | | ? PredictionConfigMatchKind.Exact |
| | 1 | 76 | | : PredictionConfigMatchKind.None; |
| | | 77 | | } |
| | | 78 | | |
| | 1 | 79 | | if (!string.IsNullOrWhiteSpace(storedReasoningEffort)) |
| | | 80 | | { |
| | 0 | 81 | | if (!PredictionModelConfig.IsValidReasoningEffort(storedReasoningEffort)) |
| | | 82 | | { |
| | 0 | 83 | | return PredictionConfigMatchKind.None; |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | var normalizedReasoningEffort = PredictionModelConfig.NormalizeReasoningEffort(storedReasoningEffort); |
| | 0 | 87 | | return string.Equals(normalizedReasoningEffort, modelConfig.ReasoningEffort, StringComparison.Ordinal) |
| | 0 | 88 | | ? PredictionConfigMatchKind.Exact |
| | 0 | 89 | | : PredictionConfigMatchKind.None; |
| | | 90 | | } |
| | | 91 | | |
| | 1 | 92 | | return modelConfig.AllowsLegacyModelOnlyLookup |
| | 1 | 93 | | ? PredictionConfigMatchKind.LegacyModelOnly |
| | 1 | 94 | | : PredictionConfigMatchKind.None; |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | private static FirestoreMatchPrediction? SelectLatestForModelConfig( |
| | | 98 | | IEnumerable<FirestoreMatchPrediction> predictions, |
| | | 99 | | PredictionModelConfig modelConfig) |
| | | 100 | | { |
| | 1 | 101 | | return predictions |
| | 1 | 102 | | .Select(prediction => new |
| | 1 | 103 | | { |
| | 1 | 104 | | Prediction = prediction, |
| | 1 | 105 | | MatchKind = GetConfigMatchKind(prediction, modelConfig) |
| | 1 | 106 | | }) |
| | 1 | 107 | | .Where(candidate => candidate.MatchKind != PredictionConfigMatchKind.None) |
| | 1 | 108 | | .OrderByDescending(candidate => candidate.MatchKind) |
| | 1 | 109 | | .ThenByDescending(candidate => candidate.Prediction.RepredictionIndex) |
| | 1 | 110 | | .ThenByDescending(candidate => candidate.Prediction.CreatedAt.ToDateTimeOffset()) |
| | 1 | 111 | | .ThenBy(candidate => candidate.Prediction.Id, StringComparer.Ordinal) |
| | 1 | 112 | | .Select(candidate => candidate.Prediction) |
| | 1 | 113 | | .FirstOrDefault(); |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | private static FirestoreBonusPrediction? SelectLatestForModelConfig( |
| | | 117 | | IEnumerable<FirestoreBonusPrediction> predictions, |
| | | 118 | | PredictionModelConfig modelConfig) |
| | | 119 | | { |
| | 1 | 120 | | return predictions |
| | 1 | 121 | | .Select(prediction => new |
| | 1 | 122 | | { |
| | 1 | 123 | | Prediction = prediction, |
| | 1 | 124 | | MatchKind = GetConfigMatchKind(prediction, modelConfig) |
| | 1 | 125 | | }) |
| | 1 | 126 | | .Where(candidate => candidate.MatchKind != PredictionConfigMatchKind.None) |
| | 1 | 127 | | .OrderByDescending(candidate => candidate.MatchKind) |
| | 1 | 128 | | .ThenByDescending(candidate => candidate.Prediction.RepredictionIndex) |
| | 1 | 129 | | .ThenByDescending(candidate => candidate.Prediction.CreatedAt.ToDateTimeOffset()) |
| | 1 | 130 | | .ThenBy(candidate => candidate.Prediction.Id, StringComparer.Ordinal) |
| | 1 | 131 | | .Select(candidate => candidate.Prediction) |
| | 1 | 132 | | .FirstOrDefault(); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | public Task SavePredictionAsync(Match match, Prediction prediction, string model, string tokenUsage, double cost, st |
| | | 136 | | { |
| | 1 | 137 | | return SavePredictionAsync( |
| | 1 | 138 | | match, |
| | 1 | 139 | | prediction, |
| | 1 | 140 | | PredictionModelConfig.Create(model), |
| | 1 | 141 | | tokenUsage, |
| | 1 | 142 | | cost, |
| | 1 | 143 | | communityContext, |
| | 1 | 144 | | contextDocumentNames, |
| | 1 | 145 | | overrideCreatedAt, |
| | 1 | 146 | | cancellationToken); |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | public async Task SavePredictionAsync(Match match, Prediction prediction, PredictionModelConfig modelConfig, string |
| | | 150 | | { |
| | | 151 | | try |
| | | 152 | | { |
| | 1 | 153 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 154 | | |
| | | 155 | | // Check if a prediction already exists for this match, model, and community context |
| | | 156 | | // Order by repredictionIndex descending to get the latest version for updating |
| | 1 | 157 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 158 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 159 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 160 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 161 | | .WhereEqualTo("competition", _competition) |
| | 1 | 162 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 163 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 164 | | .OrderByDescending("repredictionIndex"); |
| | | 165 | | |
| | 1 | 166 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 167 | | |
| | | 168 | | DocumentReference docRef; |
| | 1 | 169 | | bool isUpdate = false; |
| | 1 | 170 | | Timestamp? existingCreatedAt = null; |
| | 1 | 171 | | int repredictionIndex = 0; |
| | | 172 | | |
| | 1 | 173 | | var existingDoc = snapshot.Documents |
| | 1 | 174 | | .FirstOrDefault(document => |
| | 1 | 175 | | GetConfigMatchKind(document.ConvertTo<FirestoreMatchPrediction>(), modelConfig) == PredictionConfigM |
| | | 176 | | |
| | 1 | 177 | | if (existingDoc is not null) |
| | | 178 | | { |
| | | 179 | | // Update existing document (latest reprediction) |
| | 1 | 180 | | docRef = existingDoc.Reference; |
| | 1 | 181 | | isUpdate = true; |
| | | 182 | | |
| | | 183 | | // Preserve the original values |
| | 1 | 184 | | var existingData = existingDoc.ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 185 | | existingCreatedAt = existingData.CreatedAt; |
| | 1 | 186 | | repredictionIndex = existingData.RepredictionIndex; // Keep same reprediction index for override |
| | | 187 | | |
| | 1 | 188 | | _logger.LogDebug("Updating existing prediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId |
| | 1 | 189 | | match.HomeTeam, match.AwayTeam, existingDoc.Id, repredictionIndex); |
| | | 190 | | } |
| | | 191 | | else |
| | | 192 | | { |
| | | 193 | | // Create new document |
| | 1 | 194 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 195 | | docRef = _firestoreDb.Collection(_predictionsCollection).Document(documentId); |
| | 1 | 196 | | repredictionIndex = 0; // First prediction |
| | | 197 | | |
| | 1 | 198 | | _logger.LogDebug("Creating new prediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId}, re |
| | 1 | 199 | | match.HomeTeam, match.AwayTeam, documentId, repredictionIndex); |
| | | 200 | | } |
| | | 201 | | |
| | 1 | 202 | | var firestorePrediction = new FirestoreMatchPrediction |
| | 1 | 203 | | { |
| | 1 | 204 | | Id = docRef.Id, |
| | 1 | 205 | | HomeTeam = match.HomeTeam, |
| | 1 | 206 | | AwayTeam = match.AwayTeam, |
| | 1 | 207 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 208 | | Matchday = match.Matchday, |
| | 1 | 209 | | HomeGoals = prediction.HomeGoals, |
| | 1 | 210 | | AwayGoals = prediction.AwayGoals, |
| | 1 | 211 | | Justification = SerializeJustification(prediction.Justification), |
| | 1 | 212 | | UpdatedAt = now, |
| | 1 | 213 | | Competition = _competition, |
| | 1 | 214 | | Model = modelConfig.Model, |
| | 1 | 215 | | ModelConfigKey = modelConfig.IdentityKey, |
| | 1 | 216 | | ReasoningEffort = modelConfig.ReasoningEffort, |
| | 1 | 217 | | TokenUsage = tokenUsage, |
| | 1 | 218 | | Cost = cost, |
| | 1 | 219 | | CommunityContext = communityContext, |
| | 1 | 220 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 221 | | RepredictionIndex = repredictionIndex |
| | 1 | 222 | | }; |
| | | 223 | | |
| | | 224 | | // Set CreatedAt: preserve existing value for updates unless overrideCreatedAt is explicitly requested |
| | 1 | 225 | | firestorePrediction.CreatedAt = (overrideCreatedAt || existingCreatedAt == null) ? now : existingCreatedAt.V |
| | | 226 | | |
| | 1 | 227 | | await docRef.SetAsync(firestorePrediction, cancellationToken: cancellationToken); |
| | | 228 | | |
| | 1 | 229 | | var action = isUpdate ? "Updated" : "Saved"; |
| | 1 | 230 | | _logger.LogInformation("{Action} prediction for match {HomeTeam} vs {AwayTeam} on matchday {Matchday} (repre |
| | 1 | 231 | | action, match.HomeTeam, match.AwayTeam, match.Matchday, repredictionIndex); |
| | 1 | 232 | | } |
| | 0 | 233 | | catch (Exception ex) |
| | | 234 | | { |
| | 0 | 235 | | _logger.LogError(ex, "Failed to save prediction for match {HomeTeam} vs {AwayTeam}", |
| | 0 | 236 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 237 | | throw; |
| | | 238 | | } |
| | 1 | 239 | | } |
| | | 240 | | |
| | | 241 | | public Task<Prediction?> GetPredictionAsync(Match match, string model, string communityContext, CancellationToken ca |
| | | 242 | | { |
| | 1 | 243 | | return GetPredictionAsync(match, PredictionModelConfig.Create(model), communityContext, cancellationToken); |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | public async Task<Prediction?> GetPredictionAsync(Match match, PredictionModelConfig modelConfig, string communityCo |
| | | 247 | | { |
| | 1 | 248 | | return await GetPredictionAsync(match.HomeTeam, match.AwayTeam, match.StartsAt, modelConfig, communityContext, c |
| | 1 | 249 | | } |
| | | 250 | | |
| | | 251 | | public Task<Prediction?> GetPredictionAsync(string homeTeam, string awayTeam, ZonedDateTime startsAt, string model, |
| | | 252 | | { |
| | 0 | 253 | | return GetPredictionAsync(homeTeam, awayTeam, startsAt, PredictionModelConfig.Create(model), communityContext, c |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | public async Task<Prediction?> GetPredictionAsync(string homeTeam, string awayTeam, ZonedDateTime startsAt, Predicti |
| | | 257 | | { |
| | | 258 | | try |
| | | 259 | | { |
| | | 260 | | // Query by match characteristics, model, community context, and competition |
| | | 261 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 262 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 263 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 264 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 265 | | .WhereEqualTo("startsAt", ConvertToTimestamp(startsAt)) |
| | 1 | 266 | | .WhereEqualTo("competition", _competition) |
| | 1 | 267 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 268 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 269 | | .OrderByDescending("repredictionIndex"); |
| | | 270 | | |
| | 1 | 271 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 272 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 273 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 274 | | modelConfig); |
| | | 275 | | |
| | 1 | 276 | | if (firestorePrediction is null) |
| | | 277 | | { |
| | 1 | 278 | | return null; |
| | | 279 | | } |
| | | 280 | | |
| | 1 | 281 | | return new Prediction( |
| | 1 | 282 | | firestorePrediction.HomeGoals, |
| | 1 | 283 | | firestorePrediction.AwayGoals, |
| | 1 | 284 | | DeserializeJustification(firestorePrediction.Justification)); |
| | | 285 | | } |
| | 0 | 286 | | catch (Exception ex) |
| | | 287 | | { |
| | 0 | 288 | | _logger.LogError(ex, "Failed to get prediction for match {HomeTeam} vs {AwayTeam} using model {Model} and co |
| | 0 | 289 | | homeTeam, awayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 290 | | throw; |
| | | 291 | | } |
| | 1 | 292 | | } |
| | | 293 | | |
| | | 294 | | public async Task<Match?> GetLatestPredictedMatchByTeamsAsync( |
| | | 295 | | string homeTeam, |
| | | 296 | | string awayTeam, |
| | | 297 | | string communityContext, |
| | | 298 | | CancellationToken cancellationToken = default) |
| | | 299 | | { |
| | | 300 | | try |
| | | 301 | | { |
| | 1 | 302 | | var normalizedHomeTeam = homeTeam.Trim(); |
| | 1 | 303 | | var normalizedAwayTeam = awayTeam.Trim(); |
| | 1 | 304 | | var normalizedCommunityContext = communityContext.Trim(); |
| | | 305 | | |
| | 1 | 306 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 307 | | .WhereEqualTo("competition", _competition) |
| | 1 | 308 | | .WhereEqualTo("communityContext", normalizedCommunityContext) |
| | 1 | 309 | | .WhereEqualTo("homeTeam", normalizedHomeTeam) |
| | 1 | 310 | | .WhereEqualTo("awayTeam", normalizedAwayTeam) |
| | 1 | 311 | | .OrderByDescending("startsAt") |
| | 1 | 312 | | .Limit(1); |
| | | 313 | | |
| | 1 | 314 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 315 | | var firestorePrediction = snapshot.Documents |
| | 1 | 316 | | .FirstOrDefault() |
| | 1 | 317 | | ?.ConvertTo<FirestoreMatchPrediction>(); |
| | | 318 | | |
| | 1 | 319 | | if (firestorePrediction is null) |
| | | 320 | | { |
| | 0 | 321 | | _logger.LogDebug( |
| | 0 | 322 | | "No predicted match found for {HomeTeam} vs {AwayTeam} in community context {CommunityContext}", |
| | 0 | 323 | | normalizedHomeTeam, |
| | 0 | 324 | | normalizedAwayTeam, |
| | 0 | 325 | | normalizedCommunityContext); |
| | 0 | 326 | | return null; |
| | | 327 | | } |
| | | 328 | | |
| | 1 | 329 | | return new Match( |
| | 1 | 330 | | firestorePrediction.HomeTeam, |
| | 1 | 331 | | firestorePrediction.AwayTeam, |
| | 1 | 332 | | ConvertFromTimestamp(firestorePrediction.StartsAt), |
| | 1 | 333 | | firestorePrediction.Matchday); |
| | | 334 | | } |
| | 0 | 335 | | catch (Exception ex) |
| | | 336 | | { |
| | 0 | 337 | | _logger.LogError( |
| | 0 | 338 | | ex, |
| | 0 | 339 | | "Failed to get latest predicted match for {HomeTeam} vs {AwayTeam} in community context {CommunityContex |
| | 0 | 340 | | homeTeam, |
| | 0 | 341 | | awayTeam, |
| | 0 | 342 | | communityContext); |
| | 0 | 343 | | throw; |
| | | 344 | | } |
| | 1 | 345 | | } |
| | | 346 | | |
| | | 347 | | public Task<PredictionMetadata?> GetPredictionMetadataAsync(Match match, string model, string communityContext, Canc |
| | | 348 | | { |
| | 1 | 349 | | return GetPredictionMetadataAsync(match, PredictionModelConfig.Create(model), communityContext, cancellationToke |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | public async Task<PredictionMetadata?> GetPredictionMetadataAsync(Match match, PredictionModelConfig modelConfig, st |
| | | 353 | | { |
| | | 354 | | try |
| | | 355 | | { |
| | | 356 | | // Query by match characteristics, model, community context, and competition. |
| | | 357 | | // Order by repredictionIndex descending to keep metadata reads aligned with latest prediction retrieval. |
| | 1 | 358 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 359 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 360 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 361 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 362 | | .WhereEqualTo("competition", _competition) |
| | 1 | 363 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 364 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 365 | | .OrderByDescending("repredictionIndex"); |
| | | 366 | | |
| | 1 | 367 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 368 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 369 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 370 | | modelConfig); |
| | | 371 | | |
| | 1 | 372 | | if (firestorePrediction is null) |
| | | 373 | | { |
| | 0 | 374 | | return null; |
| | | 375 | | } |
| | | 376 | | |
| | 1 | 377 | | var prediction = new Prediction( |
| | 1 | 378 | | firestorePrediction.HomeGoals, |
| | 1 | 379 | | firestorePrediction.AwayGoals, |
| | 1 | 380 | | DeserializeJustification(firestorePrediction.Justification)); |
| | 1 | 381 | | var createdAt = firestorePrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 382 | | var contextDocumentNames = firestorePrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 383 | | |
| | 1 | 384 | | return new PredictionMetadata(prediction, createdAt, contextDocumentNames); |
| | | 385 | | } |
| | 0 | 386 | | catch (Exception ex) |
| | | 387 | | { |
| | 0 | 388 | | _logger.LogError(ex, "Failed to get prediction metadata for match {HomeTeam} vs {AwayTeam} using model {Mode |
| | 0 | 389 | | match.HomeTeam, match.AwayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 390 | | throw; |
| | | 391 | | } |
| | 1 | 392 | | } |
| | | 393 | | |
| | | 394 | | public async Task<IReadOnlyList<Match>> GetMatchDayAsync(int matchDay, CancellationToken cancellationToken = default |
| | | 395 | | { |
| | | 396 | | try |
| | | 397 | | { |
| | 1 | 398 | | var query = _firestoreDb.Collection(_matchesCollection) |
| | 1 | 399 | | .WhereEqualTo("competition", _competition) |
| | 1 | 400 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 401 | | .OrderBy("startsAt"); |
| | | 402 | | |
| | 1 | 403 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 404 | | |
| | 1 | 405 | | var matches = snapshot.Documents |
| | 1 | 406 | | .Select(doc => doc.ConvertTo<FirestoreMatch>()) |
| | 1 | 407 | | .Select(fm => new Match( |
| | 1 | 408 | | fm.HomeTeam, |
| | 1 | 409 | | fm.AwayTeam, |
| | 1 | 410 | | ConvertFromTimestamp(fm.StartsAt), |
| | 1 | 411 | | fm.Matchday, |
| | 1 | 412 | | fm.IsCancelled)) |
| | 1 | 413 | | .ToList(); |
| | | 414 | | |
| | 1 | 415 | | return matches.AsReadOnly(); |
| | | 416 | | } |
| | 0 | 417 | | catch (Exception ex) |
| | | 418 | | { |
| | 0 | 419 | | _logger.LogError(ex, "Failed to get matches for matchday {Matchday}", matchDay); |
| | 0 | 420 | | throw; |
| | | 421 | | } |
| | 1 | 422 | | } |
| | | 423 | | |
| | | 424 | | public Task<Match?> GetStoredMatchAsync(string homeTeam, string awayTeam, int matchDay, string? model = null, string |
| | | 425 | | { |
| | 1 | 426 | | var modelConfig = string.IsNullOrWhiteSpace(model) |
| | 1 | 427 | | ? null |
| | 1 | 428 | | : PredictionModelConfig.Create(model); |
| | 1 | 429 | | return GetStoredMatchAsync(homeTeam, awayTeam, matchDay, modelConfig, communityContext, cancellationToken); |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | public async Task<Match?> GetStoredMatchAsync(string homeTeam, string awayTeam, int matchDay, PredictionModelConfig? |
| | | 433 | | { |
| | | 434 | | try |
| | | 435 | | { |
| | 1 | 436 | | var matchQuery = _firestoreDb.Collection(_matchesCollection) |
| | 1 | 437 | | .WhereEqualTo("competition", _competition) |
| | 1 | 438 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 439 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 440 | | .WhereEqualTo("awayTeam", awayTeam); |
| | | 441 | | |
| | 1 | 442 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 443 | | |
| | 1 | 444 | | if (matchSnapshot.Documents.Count > 0) |
| | | 445 | | { |
| | 1 | 446 | | if (matchSnapshot.Documents.Count > 1) |
| | | 447 | | { |
| | 1 | 448 | | _logger.LogWarning("Found {Count} stored match documents for {HomeTeam} vs {AwayTeam} on matchday {M |
| | | 449 | | } |
| | | 450 | | |
| | 1 | 451 | | return matchSnapshot.Documents |
| | 1 | 452 | | .Select(document => document.ConvertTo<FirestoreMatch>()) |
| | 1 | 453 | | .Select(firestoreMatch => new Match( |
| | 1 | 454 | | firestoreMatch.HomeTeam, |
| | 1 | 455 | | firestoreMatch.AwayTeam, |
| | 1 | 456 | | ConvertFromTimestamp(firestoreMatch.StartsAt), |
| | 1 | 457 | | firestoreMatch.Matchday, |
| | 1 | 458 | | firestoreMatch.IsCancelled)) |
| | 1 | 459 | | .OrderBy(match => match.StartsAt.ToInstant()) |
| | 1 | 460 | | .ThenBy(match => match.IsCancelled) |
| | 1 | 461 | | .First(); |
| | | 462 | | } |
| | | 463 | | |
| | 1 | 464 | | Query predictionQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 465 | | .WhereEqualTo("competition", _competition) |
| | 1 | 466 | | .WhereEqualTo("matchday", matchDay) |
| | 1 | 467 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 468 | | .WhereEqualTo("awayTeam", awayTeam); |
| | | 469 | | |
| | 1 | 470 | | if (modelConfig is not null) |
| | | 471 | | { |
| | 1 | 472 | | predictionQuery = predictionQuery.WhereEqualTo("model", modelConfig.Model); |
| | | 473 | | } |
| | | 474 | | |
| | 1 | 475 | | if (!string.IsNullOrWhiteSpace(communityContext)) |
| | | 476 | | { |
| | 1 | 477 | | predictionQuery = predictionQuery.WhereEqualTo("communityContext", communityContext); |
| | | 478 | | } |
| | | 479 | | |
| | 1 | 480 | | var predictionSnapshot = await predictionQuery.GetSnapshotAsync(cancellationToken); |
| | | 481 | | |
| | 1 | 482 | | if (predictionSnapshot.Documents.Count == 0) |
| | | 483 | | { |
| | 0 | 484 | | return null; |
| | | 485 | | } |
| | | 486 | | |
| | 1 | 487 | | if (predictionSnapshot.Documents.Count > 1) |
| | | 488 | | { |
| | 1 | 489 | | _logger.LogWarning("Found {Count} stored prediction documents for {HomeTeam} vs {AwayTeam} on matchday { |
| | | 490 | | } |
| | | 491 | | |
| | 1 | 492 | | var predictions = predictionSnapshot.Documents |
| | 1 | 493 | | .Select(document => document.ConvertTo<FirestoreMatchPrediction>()) |
| | 1 | 494 | | .Select(prediction => new |
| | 1 | 495 | | { |
| | 1 | 496 | | Prediction = prediction, |
| | 1 | 497 | | MatchKind = modelConfig is null |
| | 1 | 498 | | ? PredictionConfigMatchKind.Exact |
| | 1 | 499 | | : GetConfigMatchKind(prediction, modelConfig) |
| | 1 | 500 | | }) |
| | 1 | 501 | | .Where(candidate => candidate.MatchKind != PredictionConfigMatchKind.None) |
| | 1 | 502 | | .ToList(); |
| | | 503 | | |
| | 1 | 504 | | if (predictions.Count == 0) |
| | | 505 | | { |
| | 0 | 506 | | return null; |
| | | 507 | | } |
| | | 508 | | |
| | 1 | 509 | | var firestorePrediction = predictions |
| | 1 | 510 | | .OrderByDescending(candidate => candidate.MatchKind) |
| | 1 | 511 | | .ThenByDescending(candidate => candidate.Prediction.RepredictionIndex) |
| | 1 | 512 | | .ThenByDescending(candidate => candidate.Prediction.CreatedAt.ToDateTimeOffset()) |
| | 1 | 513 | | .ThenBy(candidate => candidate.Prediction.StartsAt.ToDateTimeOffset()) |
| | 1 | 514 | | .ThenBy(candidate => candidate.Prediction.Id, StringComparer.Ordinal) |
| | 1 | 515 | | .Select(candidate => candidate.Prediction) |
| | 1 | 516 | | .First(); |
| | | 517 | | |
| | 1 | 518 | | return new Match( |
| | 1 | 519 | | firestorePrediction.HomeTeam, |
| | 1 | 520 | | firestorePrediction.AwayTeam, |
| | 1 | 521 | | ConvertFromTimestamp(firestorePrediction.StartsAt), |
| | 1 | 522 | | firestorePrediction.Matchday); |
| | | 523 | | } |
| | 0 | 524 | | catch (Exception ex) |
| | | 525 | | { |
| | 0 | 526 | | _logger.LogError(ex, "Failed to get stored match {HomeTeam} vs {AwayTeam} for matchday {Matchday}", homeTeam |
| | 0 | 527 | | throw; |
| | | 528 | | } |
| | 1 | 529 | | } |
| | | 530 | | |
| | | 531 | | public Task<IReadOnlyList<MatchPrediction>> GetMatchDayWithPredictionsAsync(int matchDay, string model, string commu |
| | | 532 | | { |
| | 1 | 533 | | return GetMatchDayWithPredictionsAsync(matchDay, PredictionModelConfig.Create(model), communityContext, cancella |
| | | 534 | | } |
| | | 535 | | |
| | | 536 | | public async Task<IReadOnlyList<MatchPrediction>> GetMatchDayWithPredictionsAsync(int matchDay, PredictionModelConfi |
| | | 537 | | { |
| | | 538 | | try |
| | | 539 | | { |
| | | 540 | | // Get all matches for the matchday |
| | 1 | 541 | | var matches = await GetMatchDayAsync(matchDay, cancellationToken); |
| | | 542 | | |
| | | 543 | | // Get predictions for all matches using the specified model and community context |
| | 1 | 544 | | var matchPredictions = new List<MatchPrediction>(); |
| | | 545 | | |
| | 1 | 546 | | foreach (var match in matches) |
| | | 547 | | { |
| | 1 | 548 | | var prediction = await GetPredictionAsync(match, modelConfig, communityContext, cancellationToken); |
| | 1 | 549 | | matchPredictions.Add(new MatchPrediction(match, prediction)); |
| | 1 | 550 | | } |
| | | 551 | | |
| | 1 | 552 | | return matchPredictions.AsReadOnly(); |
| | | 553 | | } |
| | 0 | 554 | | catch (Exception ex) |
| | | 555 | | { |
| | 0 | 556 | | _logger.LogError(ex, "Failed to get matches with predictions for matchday {Matchday} using model {Model} and |
| | 0 | 557 | | throw; |
| | | 558 | | } |
| | 1 | 559 | | } |
| | | 560 | | |
| | | 561 | | public Task<IReadOnlyList<MatchPrediction>> GetAllPredictionsAsync(string model, string communityContext, Cancellati |
| | | 562 | | { |
| | 1 | 563 | | return GetAllPredictionsAsync(PredictionModelConfig.Create(model), communityContext, cancellationToken); |
| | | 564 | | } |
| | | 565 | | |
| | | 566 | | public async Task<IReadOnlyList<MatchPrediction>> GetAllPredictionsAsync(PredictionModelConfig modelConfig, string c |
| | | 567 | | { |
| | | 568 | | try |
| | | 569 | | { |
| | 1 | 570 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 571 | | .WhereEqualTo("competition", _competition) |
| | 1 | 572 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 573 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 574 | | .OrderBy("matchday"); |
| | | 575 | | |
| | 1 | 576 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 577 | | |
| | 1 | 578 | | var matchPredictions = snapshot.Documents |
| | 1 | 579 | | .Select(doc => doc.ConvertTo<FirestoreMatchPrediction>()) |
| | 1 | 580 | | .Where(fp => GetConfigMatchKind(fp, modelConfig) != PredictionConfigMatchKind.None) |
| | 1 | 581 | | .Select(fp => new MatchPrediction( |
| | 1 | 582 | | new Match(fp.HomeTeam, fp.AwayTeam, ConvertFromTimestamp(fp.StartsAt), fp.Matchday), |
| | 1 | 583 | | new Prediction( |
| | 1 | 584 | | fp.HomeGoals, |
| | 1 | 585 | | fp.AwayGoals, |
| | 1 | 586 | | DeserializeJustification(fp.Justification)))) |
| | 1 | 587 | | .ToList(); |
| | | 588 | | |
| | 1 | 589 | | return matchPredictions.AsReadOnly(); |
| | | 590 | | } |
| | 0 | 591 | | catch (Exception ex) |
| | | 592 | | { |
| | 0 | 593 | | _logger.LogError(ex, "Failed to get all predictions for model {Model} and community context {CommunityContex |
| | 0 | 594 | | throw; |
| | | 595 | | } |
| | 1 | 596 | | } |
| | | 597 | | |
| | | 598 | | public Task<bool> HasPredictionAsync(Match match, string model, string communityContext, CancellationToken cancellat |
| | | 599 | | { |
| | 1 | 600 | | return HasPredictionAsync(match, PredictionModelConfig.Create(model), communityContext, cancellationToken); |
| | | 601 | | } |
| | | 602 | | |
| | | 603 | | public async Task<bool> HasPredictionAsync(Match match, PredictionModelConfig modelConfig, string communityContext, |
| | | 604 | | { |
| | | 605 | | try |
| | | 606 | | { |
| | | 607 | | // Query by match characteristics, model, and community context instead of using deterministic ID |
| | 1 | 608 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 609 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 610 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 611 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 612 | | .WhereEqualTo("competition", _competition) |
| | 1 | 613 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 614 | | .WhereEqualTo("communityContext", communityContext); |
| | | 615 | | |
| | 1 | 616 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 617 | | return snapshot.Documents |
| | 1 | 618 | | .Select(document => document.ConvertTo<FirestoreMatchPrediction>()) |
| | 1 | 619 | | .Any(prediction => GetConfigMatchKind(prediction, modelConfig) != PredictionConfigMatchKind.None); |
| | | 620 | | } |
| | 0 | 621 | | catch (Exception ex) |
| | | 622 | | { |
| | 0 | 623 | | _logger.LogError(ex, "Failed to check if prediction exists for match {HomeTeam} vs {AwayTeam} using model {M |
| | 0 | 624 | | match.HomeTeam, match.AwayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 625 | | throw; |
| | | 626 | | } |
| | 1 | 627 | | } |
| | | 628 | | |
| | | 629 | | public Task SaveBonusPredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, string model, str |
| | | 630 | | { |
| | 1 | 631 | | return SaveBonusPredictionAsync( |
| | 1 | 632 | | bonusQuestion, |
| | 1 | 633 | | bonusPrediction, |
| | 1 | 634 | | PredictionModelConfig.Create(model), |
| | 1 | 635 | | tokenUsage, |
| | 1 | 636 | | cost, |
| | 1 | 637 | | communityContext, |
| | 1 | 638 | | contextDocumentNames, |
| | 1 | 639 | | overrideCreatedAt, |
| | 1 | 640 | | cancellationToken); |
| | | 641 | | } |
| | | 642 | | |
| | | 643 | | public async Task SaveBonusPredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, PredictionM |
| | | 644 | | { |
| | | 645 | | try |
| | | 646 | | { |
| | 1 | 647 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 648 | | |
| | | 649 | | // Check if a prediction already exists for this question, model, and community context |
| | | 650 | | // Order by repredictionIndex descending to get the latest version for updating |
| | 1 | 651 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 652 | | .WhereEqualTo("questionText", bonusQuestion.Text) |
| | 1 | 653 | | .WhereEqualTo("competition", _competition) |
| | 1 | 654 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 655 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 656 | | .OrderByDescending("repredictionIndex"); |
| | | 657 | | |
| | 1 | 658 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 659 | | |
| | | 660 | | DocumentReference docRef; |
| | 1 | 661 | | bool isUpdate = false; |
| | 1 | 662 | | Timestamp? existingCreatedAt = null; |
| | 1 | 663 | | int repredictionIndex = 0; |
| | | 664 | | |
| | 1 | 665 | | var existingDoc = snapshot.Documents |
| | 1 | 666 | | .FirstOrDefault(document => |
| | 1 | 667 | | GetConfigMatchKind(document.ConvertTo<FirestoreBonusPrediction>(), modelConfig) == PredictionConfigM |
| | | 668 | | |
| | 1 | 669 | | if (existingDoc is not null) |
| | | 670 | | { |
| | | 671 | | // Update existing document (latest reprediction) |
| | 1 | 672 | | docRef = existingDoc.Reference; |
| | 1 | 673 | | isUpdate = true; |
| | | 674 | | |
| | | 675 | | // Preserve the original values |
| | 1 | 676 | | var existingData = existingDoc.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 677 | | existingCreatedAt = existingData.CreatedAt; |
| | 1 | 678 | | repredictionIndex = existingData.RepredictionIndex; // Keep same reprediction index for override |
| | | 679 | | |
| | 1 | 680 | | _logger.LogDebug("Updating existing bonus prediction for question '{QuestionText}' (document: {DocumentI |
| | 1 | 681 | | bonusQuestion.Text, existingDoc.Id, repredictionIndex); |
| | | 682 | | } |
| | | 683 | | else |
| | | 684 | | { |
| | | 685 | | // Create new document |
| | 1 | 686 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 687 | | docRef = _firestoreDb.Collection(_bonusPredictionsCollection).Document(documentId); |
| | 1 | 688 | | repredictionIndex = 0; // First prediction |
| | | 689 | | |
| | 1 | 690 | | _logger.LogDebug("Creating new bonus prediction for question '{QuestionText}' (document: {DocumentId}, r |
| | 1 | 691 | | bonusQuestion.Text, documentId, repredictionIndex); |
| | | 692 | | } |
| | | 693 | | |
| | | 694 | | // Extract selected option texts for observability |
| | 1 | 695 | | var optionTextsLookup = bonusQuestion.Options.ToDictionary(o => o.Id, o => o.Text); |
| | 1 | 696 | | var selectedOptionTexts = bonusPrediction.SelectedOptionIds |
| | 1 | 697 | | .Select(id => optionTextsLookup.TryGetValue(id, out var text) ? text : $"Unknown option: {id}") |
| | 1 | 698 | | .ToArray(); |
| | | 699 | | |
| | 1 | 700 | | var firestoreBonusPrediction = new FirestoreBonusPrediction |
| | 1 | 701 | | { |
| | 1 | 702 | | Id = docRef.Id, |
| | 1 | 703 | | QuestionText = bonusQuestion.Text, |
| | 1 | 704 | | SelectedOptionIds = bonusPrediction.SelectedOptionIds.ToArray(), |
| | 1 | 705 | | SelectedOptionTexts = selectedOptionTexts, |
| | 1 | 706 | | UpdatedAt = now, |
| | 1 | 707 | | Competition = _competition, |
| | 1 | 708 | | Model = modelConfig.Model, |
| | 1 | 709 | | ModelConfigKey = modelConfig.IdentityKey, |
| | 1 | 710 | | ReasoningEffort = modelConfig.ReasoningEffort, |
| | 1 | 711 | | TokenUsage = tokenUsage, |
| | 1 | 712 | | Cost = cost, |
| | 1 | 713 | | CommunityContext = communityContext, |
| | 1 | 714 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 715 | | RepredictionIndex = repredictionIndex |
| | 1 | 716 | | }; |
| | | 717 | | |
| | | 718 | | // Set CreatedAt: preserve existing value for updates unless overrideCreatedAt is explicitly requested |
| | 1 | 719 | | firestoreBonusPrediction.CreatedAt = (overrideCreatedAt || existingCreatedAt == null) ? now : existingCreate |
| | | 720 | | |
| | 1 | 721 | | await docRef.SetAsync(firestoreBonusPrediction, cancellationToken: cancellationToken); |
| | | 722 | | |
| | 1 | 723 | | var action = isUpdate ? "Updated" : "Saved"; |
| | 1 | 724 | | _logger.LogDebug("{Action} bonus prediction for question '{QuestionText}' with selections: {SelectedOptions} |
| | 1 | 725 | | action, bonusQuestion.Text, string.Join(", ", selectedOptionTexts), repredictionIndex); |
| | 1 | 726 | | } |
| | 0 | 727 | | catch (Exception ex) |
| | | 728 | | { |
| | 0 | 729 | | _logger.LogError(ex, "Failed to save bonus prediction for question: {QuestionText}", |
| | 0 | 730 | | bonusQuestion.Text); |
| | 0 | 731 | | throw; |
| | | 732 | | } |
| | 1 | 733 | | } |
| | | 734 | | |
| | | 735 | | public Task<BonusPrediction?> GetBonusPredictionAsync(string questionId, string model, string communityContext, Canc |
| | | 736 | | { |
| | 1 | 737 | | return GetBonusPredictionAsync(questionId, PredictionModelConfig.Create(model), communityContext, cancellationTo |
| | | 738 | | } |
| | | 739 | | |
| | | 740 | | public async Task<BonusPrediction?> GetBonusPredictionAsync(string questionId, PredictionModelConfig modelConfig, st |
| | | 741 | | { |
| | | 742 | | try |
| | | 743 | | { |
| | | 744 | | // Query by questionId, model, community context, and competition instead of using direct document lookup |
| | 1 | 745 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 746 | | .WhereEqualTo("questionId", questionId) |
| | 1 | 747 | | .WhereEqualTo("competition", _competition) |
| | 1 | 748 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 749 | | .WhereEqualTo("communityContext", communityContext); |
| | | 750 | | |
| | 1 | 751 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 752 | | |
| | 1 | 753 | | if (snapshot.Documents.Count == 0) |
| | | 754 | | { |
| | 1 | 755 | | return null; |
| | | 756 | | } |
| | | 757 | | |
| | 1 | 758 | | var firestoreBonusPrediction = SelectLatestForModelConfig( |
| | 1 | 759 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreBonusPrediction>()), |
| | 1 | 760 | | modelConfig); |
| | | 761 | | |
| | 1 | 762 | | if (firestoreBonusPrediction is null) |
| | | 763 | | { |
| | 0 | 764 | | return null; |
| | | 765 | | } |
| | | 766 | | |
| | 1 | 767 | | return new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | | 768 | | } |
| | 0 | 769 | | catch (Exception ex) |
| | | 770 | | { |
| | 0 | 771 | | _logger.LogError(ex, "Failed to get bonus prediction for question {QuestionId} using model {Model} and commu |
| | 0 | 772 | | throw; |
| | | 773 | | } |
| | 1 | 774 | | } |
| | | 775 | | |
| | | 776 | | public Task<BonusPrediction?> GetBonusPredictionByTextAsync(string questionText, string model, string communityConte |
| | | 777 | | { |
| | 1 | 778 | | return GetBonusPredictionByTextAsync(questionText, PredictionModelConfig.Create(model), communityContext, cancel |
| | | 779 | | } |
| | | 780 | | |
| | | 781 | | public async Task<BonusPrediction?> GetBonusPredictionByTextAsync(string questionText, PredictionModelConfig modelCo |
| | | 782 | | { |
| | | 783 | | try |
| | | 784 | | { |
| | | 785 | | // Query by questionText, model, and community context |
| | | 786 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 787 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 788 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 789 | | .WhereEqualTo("competition", _competition) |
| | 1 | 790 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 791 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 792 | | .OrderByDescending("repredictionIndex"); |
| | | 793 | | |
| | 1 | 794 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 795 | | var firestoreBonusPrediction = SelectLatestForModelConfig( |
| | 1 | 796 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreBonusPrediction>()), |
| | 1 | 797 | | modelConfig); |
| | | 798 | | |
| | 1 | 799 | | if (firestoreBonusPrediction is null) |
| | | 800 | | { |
| | 1 | 801 | | _logger.LogDebug("No bonus prediction found for question text: {QuestionText} with model: {Model} and co |
| | 1 | 802 | | return null; |
| | | 803 | | } |
| | | 804 | | |
| | 1 | 805 | | var bonusPrediction = new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | | 806 | | |
| | 1 | 807 | | _logger.LogDebug("Found bonus prediction for question text: {QuestionText} with model: {Model} and community |
| | 1 | 808 | | questionText, modelConfig.DisplayName, communityContext, firestoreBonusPrediction.RepredictionIndex); |
| | | 809 | | |
| | 1 | 810 | | return bonusPrediction; |
| | | 811 | | } |
| | 0 | 812 | | catch (Exception ex) |
| | | 813 | | { |
| | 0 | 814 | | _logger.LogError(ex, "Failed to retrieve bonus prediction by text: {QuestionText} with model: {Model} and co |
| | 0 | 815 | | throw; |
| | | 816 | | } |
| | 1 | 817 | | } |
| | | 818 | | |
| | | 819 | | public Task<BonusPredictionMetadata?> GetBonusPredictionMetadataByTextAsync(string questionText, string model, strin |
| | | 820 | | { |
| | 1 | 821 | | return GetBonusPredictionMetadataByTextAsync(questionText, PredictionModelConfig.Create(model), communityContext |
| | | 822 | | } |
| | | 823 | | |
| | | 824 | | public async Task<BonusPredictionMetadata?> GetBonusPredictionMetadataByTextAsync(string questionText, PredictionMod |
| | | 825 | | { |
| | | 826 | | try |
| | | 827 | | { |
| | | 828 | | // Query by questionText, model, and community context. |
| | | 829 | | // Order by repredictionIndex descending to align metadata reads with latest bonus prediction retrieval. |
| | 1 | 830 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 831 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 832 | | .WhereEqualTo("competition", _competition) |
| | 1 | 833 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 834 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 835 | | .OrderByDescending("repredictionIndex"); |
| | | 836 | | |
| | 1 | 837 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 838 | | var firestoreBonusPrediction = SelectLatestForModelConfig( |
| | 1 | 839 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreBonusPrediction>()), |
| | 1 | 840 | | modelConfig); |
| | | 841 | | |
| | 1 | 842 | | if (firestoreBonusPrediction is null) |
| | | 843 | | { |
| | 0 | 844 | | _logger.LogDebug("No bonus prediction metadata found for question text: {QuestionText} with model: {Mode |
| | 0 | 845 | | return null; |
| | | 846 | | } |
| | | 847 | | |
| | 1 | 848 | | var bonusPrediction = new BonusPrediction(firestoreBonusPrediction.SelectedOptionIds.ToList()); |
| | 1 | 849 | | var createdAt = firestoreBonusPrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 850 | | var contextDocumentNames = firestoreBonusPrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 851 | | |
| | 1 | 852 | | _logger.LogDebug("Found bonus prediction metadata for question text: {QuestionText} with model: {Model} and |
| | 1 | 853 | | questionText, modelConfig.DisplayName, communityContext); |
| | | 854 | | |
| | 1 | 855 | | return new BonusPredictionMetadata(bonusPrediction, createdAt, contextDocumentNames); |
| | | 856 | | } |
| | 0 | 857 | | catch (Exception ex) |
| | | 858 | | { |
| | 0 | 859 | | _logger.LogError(ex, "Failed to retrieve bonus prediction metadata by text: {QuestionText} with model: {Mode |
| | 0 | 860 | | throw; |
| | | 861 | | } |
| | 1 | 862 | | } |
| | | 863 | | |
| | | 864 | | public Task<IReadOnlyList<BonusPrediction>> GetAllBonusPredictionsAsync(string model, string communityContext, Cance |
| | | 865 | | { |
| | 1 | 866 | | return GetAllBonusPredictionsAsync(PredictionModelConfig.Create(model), communityContext, cancellationToken); |
| | | 867 | | } |
| | | 868 | | |
| | | 869 | | public async Task<IReadOnlyList<BonusPrediction>> GetAllBonusPredictionsAsync(PredictionModelConfig modelConfig, str |
| | | 870 | | { |
| | | 871 | | try |
| | | 872 | | { |
| | 1 | 873 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 874 | | .WhereEqualTo("competition", _competition) |
| | 1 | 875 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 876 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 877 | | .OrderBy("createdAt"); |
| | | 878 | | |
| | 1 | 879 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 880 | | |
| | 1 | 881 | | var bonusPredictions = new List<BonusPrediction>(); |
| | 1 | 882 | | foreach (var document in snapshot.Documents) |
| | | 883 | | { |
| | 1 | 884 | | var firestoreBonusPrediction = document.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 885 | | if (GetConfigMatchKind(firestoreBonusPrediction, modelConfig) == PredictionConfigMatchKind.None) |
| | | 886 | | { |
| | | 887 | | continue; |
| | | 888 | | } |
| | | 889 | | |
| | 1 | 890 | | bonusPredictions.Add(new BonusPrediction( |
| | 1 | 891 | | firestoreBonusPrediction.SelectedOptionIds.ToList())); |
| | | 892 | | } |
| | | 893 | | |
| | 1 | 894 | | return bonusPredictions.AsReadOnly(); |
| | | 895 | | } |
| | 0 | 896 | | catch (Exception ex) |
| | | 897 | | { |
| | 0 | 898 | | _logger.LogError(ex, "Failed to get all bonus predictions for model {Model} and community context {Community |
| | 0 | 899 | | throw; |
| | | 900 | | } |
| | 1 | 901 | | } |
| | | 902 | | |
| | | 903 | | public Task<bool> HasBonusPredictionAsync(string questionId, string model, string communityContext, CancellationToke |
| | | 904 | | { |
| | 1 | 905 | | return HasBonusPredictionAsync(questionId, PredictionModelConfig.Create(model), communityContext, cancellationTo |
| | | 906 | | } |
| | | 907 | | |
| | | 908 | | public async Task<bool> HasBonusPredictionAsync(string questionId, PredictionModelConfig modelConfig, string communi |
| | | 909 | | { |
| | | 910 | | try |
| | | 911 | | { |
| | | 912 | | // Query by questionId, model, and community context instead of using direct document lookup |
| | 1 | 913 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 914 | | .WhereEqualTo("questionId", questionId) |
| | 1 | 915 | | .WhereEqualTo("competition", _competition) |
| | 1 | 916 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 917 | | .WhereEqualTo("communityContext", communityContext); |
| | | 918 | | |
| | 1 | 919 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 920 | | return snapshot.Documents |
| | 0 | 921 | | .Select(document => document.ConvertTo<FirestoreBonusPrediction>()) |
| | 0 | 922 | | .Any(prediction => GetConfigMatchKind(prediction, modelConfig) != PredictionConfigMatchKind.None); |
| | | 923 | | } |
| | 0 | 924 | | catch (Exception ex) |
| | | 925 | | { |
| | 0 | 926 | | _logger.LogError(ex, "Failed to check if bonus prediction exists for question {QuestionId} using model {Mode |
| | 0 | 927 | | throw; |
| | | 928 | | } |
| | 1 | 929 | | } |
| | | 930 | | |
| | | 931 | | /// <summary> |
| | | 932 | | /// Stores a match in the matches collection for matchday management. |
| | | 933 | | /// This is typically called when importing match schedules. |
| | | 934 | | /// </summary> |
| | | 935 | | public async Task StoreMatchAsync(Match match, CancellationToken cancellationToken = default) |
| | | 936 | | { |
| | | 937 | | try |
| | | 938 | | { |
| | 1 | 939 | | var documentId = Guid.NewGuid().ToString(); |
| | | 940 | | |
| | 1 | 941 | | var firestoreMatch = new FirestoreMatch |
| | 1 | 942 | | { |
| | 1 | 943 | | Id = documentId, |
| | 1 | 944 | | HomeTeam = match.HomeTeam, |
| | 1 | 945 | | AwayTeam = match.AwayTeam, |
| | 1 | 946 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 947 | | Matchday = match.Matchday, |
| | 1 | 948 | | Competition = _competition, |
| | 1 | 949 | | IsCancelled = match.IsCancelled |
| | 1 | 950 | | }; |
| | | 951 | | |
| | 1 | 952 | | await _firestoreDb.Collection(_matchesCollection) |
| | 1 | 953 | | .Document(documentId) |
| | 1 | 954 | | .SetAsync(firestoreMatch, cancellationToken: cancellationToken); |
| | | 955 | | |
| | 1 | 956 | | _logger.LogDebug("Stored match {HomeTeam} vs {AwayTeam} for matchday {Matchday}{Cancelled}", |
| | 1 | 957 | | match.HomeTeam, match.AwayTeam, match.Matchday, match.IsCancelled ? " (CANCELLED)" : ""); |
| | 1 | 958 | | } |
| | 0 | 959 | | catch (Exception ex) |
| | | 960 | | { |
| | 0 | 961 | | _logger.LogError(ex, "Failed to store match {HomeTeam} vs {AwayTeam}", |
| | 0 | 962 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 963 | | throw; |
| | | 964 | | } |
| | 1 | 965 | | } |
| | | 966 | | |
| | | 967 | | private static Timestamp ConvertToTimestamp(ZonedDateTime zonedDateTime) |
| | | 968 | | { |
| | 1 | 969 | | var instant = zonedDateTime.ToInstant(); |
| | 1 | 970 | | return Timestamp.FromDateTimeOffset(instant.ToDateTimeOffset()); |
| | | 971 | | } |
| | | 972 | | |
| | | 973 | | private static ZonedDateTime ConvertFromTimestamp(Timestamp timestamp) |
| | | 974 | | { |
| | 1 | 975 | | var dateTimeOffset = timestamp.ToDateTimeOffset(); |
| | 1 | 976 | | var instant = Instant.FromDateTimeOffset(dateTimeOffset); |
| | 1 | 977 | | return instant.InUtc(); |
| | | 978 | | } |
| | | 979 | | |
| | | 980 | | public Task<int> GetMatchRepredictionIndexAsync(Match match, string model, string communityContext, CancellationToke |
| | | 981 | | { |
| | 1 | 982 | | return GetMatchRepredictionIndexAsync(match, PredictionModelConfig.Create(model), communityContext, cancellation |
| | | 983 | | } |
| | | 984 | | |
| | | 985 | | public async Task<int> GetMatchRepredictionIndexAsync(Match match, PredictionModelConfig modelConfig, string communi |
| | | 986 | | { |
| | | 987 | | try |
| | | 988 | | { |
| | | 989 | | // Query by match characteristics, model, community context, and competition |
| | | 990 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 991 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 992 | | .WhereEqualTo("homeTeam", match.HomeTeam) |
| | 1 | 993 | | .WhereEqualTo("awayTeam", match.AwayTeam) |
| | 1 | 994 | | .WhereEqualTo("startsAt", ConvertToTimestamp(match.StartsAt)) |
| | 1 | 995 | | .WhereEqualTo("competition", _competition) |
| | 1 | 996 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 997 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 998 | | .OrderByDescending("repredictionIndex"); |
| | | 999 | | |
| | 1 | 1000 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 1001 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 1002 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 1003 | | modelConfig); |
| | | 1004 | | |
| | 1 | 1005 | | if (firestorePrediction is null) |
| | | 1006 | | { |
| | 1 | 1007 | | return -1; // No prediction exists |
| | | 1008 | | } |
| | | 1009 | | |
| | 1 | 1010 | | return firestorePrediction.RepredictionIndex; |
| | | 1011 | | } |
| | 0 | 1012 | | catch (Exception ex) |
| | | 1013 | | { |
| | 0 | 1014 | | _logger.LogError(ex, "Failed to get reprediction index for match {HomeTeam} vs {AwayTeam} using model {Model |
| | 0 | 1015 | | match.HomeTeam, match.AwayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 1016 | | throw; |
| | | 1017 | | } |
| | 1 | 1018 | | } |
| | | 1019 | | |
| | | 1020 | | // See IPredictionRepository.cs for detailed documentation on why these methods exist. |
| | | 1021 | | // In short: cancelled matches have inconsistent startsAt values across different Kicktipp pages, |
| | | 1022 | | // so we query by team names only to find predictions regardless of which startsAt was used. |
| | | 1023 | | |
| | | 1024 | | /// <inheritdoc /> |
| | | 1025 | | public Task<Prediction?> GetCancelledMatchPredictionAsync(string homeTeam, string awayTeam, string model, string com |
| | | 1026 | | { |
| | 1 | 1027 | | return GetCancelledMatchPredictionAsync(homeTeam, awayTeam, PredictionModelConfig.Create(model), communityContex |
| | | 1028 | | } |
| | | 1029 | | |
| | | 1030 | | public async Task<Prediction?> GetCancelledMatchPredictionAsync(string homeTeam, string awayTeam, PredictionModelCon |
| | | 1031 | | { |
| | | 1032 | | try |
| | | 1033 | | { |
| | | 1034 | | // Query by team names only (no startsAt), ordered by createdAt descending to get the most recent |
| | | 1035 | | // We use repredictionIndex descending first to get the latest reprediction, then createdAt for tiebreaking |
| | 1 | 1036 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1037 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 1038 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 1039 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1040 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1041 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 1042 | | .OrderByDescending("createdAt"); |
| | | 1043 | | |
| | 1 | 1044 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 1045 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 1046 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 1047 | | modelConfig); |
| | | 1048 | | |
| | 1 | 1049 | | if (firestorePrediction is null) |
| | | 1050 | | { |
| | 1 | 1051 | | _logger.LogDebug("No prediction found for cancelled match {HomeTeam} vs {AwayTeam} (team-names-only look |
| | 1 | 1052 | | return null; |
| | | 1053 | | } |
| | | 1054 | | |
| | 1 | 1055 | | _logger.LogDebug("Found prediction for cancelled match {HomeTeam} vs {AwayTeam} with startsAt={StartsAt} (te |
| | 1 | 1056 | | homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 1057 | | |
| | 1 | 1058 | | return new Prediction( |
| | 1 | 1059 | | firestorePrediction.HomeGoals, |
| | 1 | 1060 | | firestorePrediction.AwayGoals, |
| | 1 | 1061 | | DeserializeJustification(firestorePrediction.Justification)); |
| | | 1062 | | } |
| | 0 | 1063 | | catch (Exception ex) |
| | | 1064 | | { |
| | 0 | 1065 | | _logger.LogError(ex, "Failed to get prediction for cancelled match {HomeTeam} vs {AwayTeam} using model {Mod |
| | 0 | 1066 | | homeTeam, awayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 1067 | | throw; |
| | | 1068 | | } |
| | 1 | 1069 | | } |
| | | 1070 | | |
| | | 1071 | | /// <inheritdoc /> |
| | | 1072 | | public Task<PredictionMetadata?> GetCancelledMatchPredictionMetadataAsync(string homeTeam, string awayTeam, string m |
| | | 1073 | | { |
| | 1 | 1074 | | return GetCancelledMatchPredictionMetadataAsync(homeTeam, awayTeam, PredictionModelConfig.Create(model), communi |
| | | 1075 | | } |
| | | 1076 | | |
| | | 1077 | | public async Task<PredictionMetadata?> GetCancelledMatchPredictionMetadataAsync(string homeTeam, string awayTeam, Pr |
| | | 1078 | | { |
| | | 1079 | | try |
| | | 1080 | | { |
| | | 1081 | | // Query by team names only (no startsAt), ordered by repredictionIndex descending to get the latest repredi |
| | 1 | 1082 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1083 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 1084 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 1085 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1086 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1087 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 1088 | | .OrderByDescending("repredictionIndex"); |
| | | 1089 | | |
| | 1 | 1090 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 1091 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 1092 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 1093 | | modelConfig); |
| | | 1094 | | |
| | 1 | 1095 | | if (firestorePrediction is null) |
| | | 1096 | | { |
| | 1 | 1097 | | _logger.LogDebug("No prediction metadata found for cancelled match {HomeTeam} vs {AwayTeam} (team-names- |
| | 1 | 1098 | | return null; |
| | | 1099 | | } |
| | | 1100 | | |
| | 1 | 1101 | | _logger.LogDebug("Found prediction metadata for cancelled match {HomeTeam} vs {AwayTeam} with startsAt={Star |
| | 1 | 1102 | | homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 1103 | | |
| | 1 | 1104 | | var prediction = new Prediction( |
| | 1 | 1105 | | firestorePrediction.HomeGoals, |
| | 1 | 1106 | | firestorePrediction.AwayGoals, |
| | 1 | 1107 | | DeserializeJustification(firestorePrediction.Justification)); |
| | 1 | 1108 | | var createdAt = firestorePrediction.CreatedAt.ToDateTimeOffset(); |
| | 1 | 1109 | | var contextDocumentNames = firestorePrediction.ContextDocumentNames?.ToList() ?? new List<string>(); |
| | | 1110 | | |
| | 1 | 1111 | | return new PredictionMetadata(prediction, createdAt, contextDocumentNames); |
| | | 1112 | | } |
| | 0 | 1113 | | catch (Exception ex) |
| | | 1114 | | { |
| | 0 | 1115 | | _logger.LogError(ex, "Failed to get prediction metadata for cancelled match {HomeTeam} vs {AwayTeam} using m |
| | 0 | 1116 | | homeTeam, awayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 1117 | | throw; |
| | | 1118 | | } |
| | 1 | 1119 | | } |
| | | 1120 | | |
| | | 1121 | | /// <inheritdoc /> |
| | | 1122 | | public Task<int> GetCancelledMatchRepredictionIndexAsync(string homeTeam, string awayTeam, string model, string comm |
| | | 1123 | | { |
| | 1 | 1124 | | return GetCancelledMatchRepredictionIndexAsync(homeTeam, awayTeam, PredictionModelConfig.Create(model), communit |
| | | 1125 | | } |
| | | 1126 | | |
| | | 1127 | | public async Task<int> GetCancelledMatchRepredictionIndexAsync(string homeTeam, string awayTeam, PredictionModelConf |
| | | 1128 | | { |
| | | 1129 | | try |
| | | 1130 | | { |
| | | 1131 | | // Query by team names only (no startsAt), ordered by repredictionIndex descending to get the highest |
| | 1 | 1132 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1133 | | .WhereEqualTo("homeTeam", homeTeam) |
| | 1 | 1134 | | .WhereEqualTo("awayTeam", awayTeam) |
| | 1 | 1135 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1136 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1137 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 1138 | | .OrderByDescending("repredictionIndex"); |
| | | 1139 | | |
| | 1 | 1140 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 1141 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 1142 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreMatchPrediction>()), |
| | 1 | 1143 | | modelConfig); |
| | | 1144 | | |
| | 1 | 1145 | | if (firestorePrediction is null) |
| | | 1146 | | { |
| | 1 | 1147 | | _logger.LogDebug("No reprediction index found for cancelled match {HomeTeam} vs {AwayTeam} (team-names-o |
| | 1 | 1148 | | return -1; |
| | | 1149 | | } |
| | | 1150 | | |
| | 1 | 1151 | | _logger.LogDebug("Found reprediction index {Index} for cancelled match {HomeTeam} vs {AwayTeam} with startsA |
| | 1 | 1152 | | firestorePrediction.RepredictionIndex, homeTeam, awayTeam, firestorePrediction.StartsAt); |
| | | 1153 | | |
| | 1 | 1154 | | return firestorePrediction.RepredictionIndex; |
| | | 1155 | | } |
| | 0 | 1156 | | catch (Exception ex) |
| | | 1157 | | { |
| | 0 | 1158 | | _logger.LogError(ex, "Failed to get reprediction index for cancelled match {HomeTeam} vs {AwayTeam} using mo |
| | 0 | 1159 | | homeTeam, awayTeam, modelConfig.DisplayName, communityContext); |
| | 0 | 1160 | | throw; |
| | | 1161 | | } |
| | 1 | 1162 | | } |
| | | 1163 | | |
| | | 1164 | | public Task<int> GetBonusRepredictionIndexAsync(string questionText, string model, string communityContext, Cancella |
| | | 1165 | | { |
| | 1 | 1166 | | return GetBonusRepredictionIndexAsync(questionText, PredictionModelConfig.Create(model), communityContext, cance |
| | | 1167 | | } |
| | | 1168 | | |
| | | 1169 | | public async Task<int> GetBonusRepredictionIndexAsync(string questionText, PredictionModelConfig modelConfig, string |
| | | 1170 | | { |
| | | 1171 | | try |
| | | 1172 | | { |
| | | 1173 | | // Query by question text, model, community context, and competition |
| | | 1174 | | // Order by repredictionIndex descending to get the latest version |
| | 1 | 1175 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1176 | | .WhereEqualTo("questionText", questionText) |
| | 1 | 1177 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1178 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1179 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 1180 | | .OrderByDescending("repredictionIndex"); |
| | | 1181 | | |
| | 1 | 1182 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | 1 | 1183 | | var firestorePrediction = SelectLatestForModelConfig( |
| | 1 | 1184 | | snapshot.Documents.Select(document => document.ConvertTo<FirestoreBonusPrediction>()), |
| | 1 | 1185 | | modelConfig); |
| | | 1186 | | |
| | 1 | 1187 | | if (firestorePrediction is null) |
| | | 1188 | | { |
| | 1 | 1189 | | return -1; // No prediction exists |
| | | 1190 | | } |
| | | 1191 | | |
| | 1 | 1192 | | return firestorePrediction.RepredictionIndex; |
| | | 1193 | | } |
| | 0 | 1194 | | catch (Exception ex) |
| | | 1195 | | { |
| | 0 | 1196 | | _logger.LogError(ex, "Failed to get reprediction index for bonus question '{QuestionText}' using model {Mode |
| | 0 | 1197 | | questionText, modelConfig.DisplayName, communityContext); |
| | 0 | 1198 | | throw; |
| | | 1199 | | } |
| | 1 | 1200 | | } |
| | | 1201 | | |
| | | 1202 | | public Task SaveRepredictionAsync(Match match, Prediction prediction, string model, string tokenUsage, double cost, |
| | | 1203 | | { |
| | 1 | 1204 | | return SaveRepredictionAsync( |
| | 1 | 1205 | | match, |
| | 1 | 1206 | | prediction, |
| | 1 | 1207 | | PredictionModelConfig.Create(model), |
| | 1 | 1208 | | tokenUsage, |
| | 1 | 1209 | | cost, |
| | 1 | 1210 | | communityContext, |
| | 1 | 1211 | | contextDocumentNames, |
| | 1 | 1212 | | repredictionIndex, |
| | 1 | 1213 | | cancellationToken); |
| | | 1214 | | } |
| | | 1215 | | |
| | | 1216 | | public async Task SaveRepredictionAsync(Match match, Prediction prediction, PredictionModelConfig modelConfig, strin |
| | | 1217 | | { |
| | | 1218 | | try |
| | | 1219 | | { |
| | 1 | 1220 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 1221 | | |
| | | 1222 | | // Create new document for this reprediction |
| | 1 | 1223 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 1224 | | var docRef = _firestoreDb.Collection(_predictionsCollection).Document(documentId); |
| | | 1225 | | |
| | 1 | 1226 | | _logger.LogDebug("Creating reprediction for match {HomeTeam} vs {AwayTeam} (document: {DocumentId}, repredic |
| | 1 | 1227 | | match.HomeTeam, match.AwayTeam, documentId, repredictionIndex); |
| | | 1228 | | |
| | 1 | 1229 | | var firestorePrediction = new FirestoreMatchPrediction |
| | 1 | 1230 | | { |
| | 1 | 1231 | | Id = docRef.Id, |
| | 1 | 1232 | | HomeTeam = match.HomeTeam, |
| | 1 | 1233 | | AwayTeam = match.AwayTeam, |
| | 1 | 1234 | | StartsAt = ConvertToTimestamp(match.StartsAt), |
| | 1 | 1235 | | Matchday = match.Matchday, |
| | 1 | 1236 | | HomeGoals = prediction.HomeGoals, |
| | 1 | 1237 | | AwayGoals = prediction.AwayGoals, |
| | 1 | 1238 | | Justification = SerializeJustification(prediction.Justification), |
| | 1 | 1239 | | CreatedAt = now, |
| | 1 | 1240 | | UpdatedAt = now, |
| | 1 | 1241 | | Competition = _competition, |
| | 1 | 1242 | | Model = modelConfig.Model, |
| | 1 | 1243 | | ModelConfigKey = modelConfig.IdentityKey, |
| | 1 | 1244 | | ReasoningEffort = modelConfig.ReasoningEffort, |
| | 1 | 1245 | | TokenUsage = tokenUsage, |
| | 1 | 1246 | | Cost = cost, |
| | 1 | 1247 | | CommunityContext = communityContext, |
| | 1 | 1248 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 1249 | | RepredictionIndex = repredictionIndex |
| | 1 | 1250 | | }; |
| | | 1251 | | |
| | 1 | 1252 | | await docRef.SetAsync(firestorePrediction, cancellationToken: cancellationToken); |
| | | 1253 | | |
| | 1 | 1254 | | _logger.LogInformation("Saved reprediction for match {HomeTeam} vs {AwayTeam} on matchday {Matchday} (repred |
| | 1 | 1255 | | match.HomeTeam, match.AwayTeam, match.Matchday, repredictionIndex); |
| | 1 | 1256 | | } |
| | 0 | 1257 | | catch (Exception ex) |
| | | 1258 | | { |
| | 0 | 1259 | | _logger.LogError(ex, "Failed to save reprediction for match {HomeTeam} vs {AwayTeam}", |
| | 0 | 1260 | | match.HomeTeam, match.AwayTeam); |
| | 0 | 1261 | | throw; |
| | | 1262 | | } |
| | 1 | 1263 | | } |
| | | 1264 | | |
| | | 1265 | | public Task SaveBonusRepredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, string model, s |
| | | 1266 | | { |
| | 1 | 1267 | | return SaveBonusRepredictionAsync( |
| | 1 | 1268 | | bonusQuestion, |
| | 1 | 1269 | | bonusPrediction, |
| | 1 | 1270 | | PredictionModelConfig.Create(model), |
| | 1 | 1271 | | tokenUsage, |
| | 1 | 1272 | | cost, |
| | 1 | 1273 | | communityContext, |
| | 1 | 1274 | | contextDocumentNames, |
| | 1 | 1275 | | repredictionIndex, |
| | 1 | 1276 | | cancellationToken); |
| | | 1277 | | } |
| | | 1278 | | |
| | | 1279 | | public async Task SaveBonusRepredictionAsync(BonusQuestion bonusQuestion, BonusPrediction bonusPrediction, Predictio |
| | | 1280 | | { |
| | | 1281 | | try |
| | | 1282 | | { |
| | 1 | 1283 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 1284 | | |
| | | 1285 | | // Create new document for this reprediction |
| | 1 | 1286 | | var documentId = Guid.NewGuid().ToString(); |
| | 1 | 1287 | | var docRef = _firestoreDb.Collection(_bonusPredictionsCollection).Document(documentId); |
| | | 1288 | | |
| | 1 | 1289 | | _logger.LogDebug("Creating bonus reprediction for question '{QuestionText}' (document: {DocumentId}, repredi |
| | 1 | 1290 | | bonusQuestion.Text, documentId, repredictionIndex); |
| | | 1291 | | |
| | | 1292 | | // Extract selected option texts for observability |
| | 1 | 1293 | | var optionTextsLookup = bonusQuestion.Options.ToDictionary(o => o.Id, o => o.Text); |
| | 1 | 1294 | | var selectedOptionTexts = bonusPrediction.SelectedOptionIds |
| | 1 | 1295 | | .Select(id => optionTextsLookup.TryGetValue(id, out var text) ? text : $"Unknown option: {id}") |
| | 1 | 1296 | | .ToArray(); |
| | | 1297 | | |
| | 1 | 1298 | | var firestoreBonusPrediction = new FirestoreBonusPrediction |
| | 1 | 1299 | | { |
| | 1 | 1300 | | Id = docRef.Id, |
| | 1 | 1301 | | QuestionText = bonusQuestion.Text, |
| | 1 | 1302 | | SelectedOptionIds = bonusPrediction.SelectedOptionIds.ToArray(), |
| | 1 | 1303 | | SelectedOptionTexts = selectedOptionTexts, |
| | 1 | 1304 | | CreatedAt = now, |
| | 1 | 1305 | | UpdatedAt = now, |
| | 1 | 1306 | | Competition = _competition, |
| | 1 | 1307 | | Model = modelConfig.Model, |
| | 1 | 1308 | | ModelConfigKey = modelConfig.IdentityKey, |
| | 1 | 1309 | | ReasoningEffort = modelConfig.ReasoningEffort, |
| | 1 | 1310 | | TokenUsage = tokenUsage, |
| | 1 | 1311 | | Cost = cost, |
| | 1 | 1312 | | CommunityContext = communityContext, |
| | 1 | 1313 | | ContextDocumentNames = contextDocumentNames.ToArray(), |
| | 1 | 1314 | | RepredictionIndex = repredictionIndex |
| | 1 | 1315 | | }; |
| | | 1316 | | |
| | 1 | 1317 | | await docRef.SetAsync(firestoreBonusPrediction, cancellationToken: cancellationToken); |
| | | 1318 | | |
| | 1 | 1319 | | _logger.LogInformation("Saved bonus reprediction for question '{QuestionText}' (reprediction index: {Repredi |
| | 1 | 1320 | | bonusQuestion.Text, repredictionIndex); |
| | 1 | 1321 | | } |
| | 0 | 1322 | | catch (Exception ex) |
| | | 1323 | | { |
| | 0 | 1324 | | _logger.LogError(ex, "Failed to save bonus reprediction for question: {QuestionText}", |
| | 0 | 1325 | | bonusQuestion.Text); |
| | 0 | 1326 | | throw; |
| | | 1327 | | } |
| | 1 | 1328 | | } |
| | | 1329 | | |
| | | 1330 | | /// <summary> |
| | | 1331 | | /// Get match prediction costs and counts grouped by reprediction index for cost analysis. |
| | | 1332 | | /// Used specifically by the cost command to include all repredictions. |
| | | 1333 | | /// </summary> |
| | | 1334 | | public Task<Dictionary<int, (double cost, int count)>> GetMatchPredictionCostsByRepredictionIndexAsync( |
| | | 1335 | | string model, |
| | | 1336 | | string communityContext, |
| | | 1337 | | List<int>? matchdays = null, |
| | | 1338 | | CancellationToken cancellationToken = default) |
| | | 1339 | | { |
| | 1 | 1340 | | return GetMatchPredictionCostsByRepredictionIndexAsync( |
| | 1 | 1341 | | PredictionModelConfig.Create(model), |
| | 1 | 1342 | | communityContext, |
| | 1 | 1343 | | matchdays, |
| | 1 | 1344 | | cancellationToken); |
| | | 1345 | | } |
| | | 1346 | | |
| | | 1347 | | public async Task<Dictionary<int, (double cost, int count)>> GetMatchPredictionCostsByRepredictionIndexAsync( |
| | | 1348 | | PredictionModelConfig modelConfig, |
| | | 1349 | | string communityContext, |
| | | 1350 | | List<int>? matchdays = null, |
| | | 1351 | | CancellationToken cancellationToken = default) |
| | | 1352 | | { |
| | | 1353 | | try |
| | | 1354 | | { |
| | 1 | 1355 | | var costsByIndex = new Dictionary<int, (double cost, int count)>(); |
| | | 1356 | | |
| | | 1357 | | // Query for match predictions with cost data |
| | 1 | 1358 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1359 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1360 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1361 | | .WhereEqualTo("communityContext", communityContext); |
| | | 1362 | | |
| | | 1363 | | // Add matchday filter if specified |
| | 1 | 1364 | | if (matchdays?.Count > 0) |
| | | 1365 | | { |
| | 1 | 1366 | | query = query.WhereIn("matchday", matchdays.Cast<object>().ToArray()); |
| | | 1367 | | } |
| | | 1368 | | |
| | 1 | 1369 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1370 | | |
| | 1 | 1371 | | foreach (var doc in snapshot.Documents) |
| | | 1372 | | { |
| | 1 | 1373 | | if (doc.Exists) |
| | | 1374 | | { |
| | 1 | 1375 | | var prediction = doc.ConvertTo<FirestoreMatchPrediction>(); |
| | 1 | 1376 | | if (GetConfigMatchKind(prediction, modelConfig) == PredictionConfigMatchKind.None) |
| | | 1377 | | { |
| | | 1378 | | continue; |
| | | 1379 | | } |
| | | 1380 | | |
| | 1 | 1381 | | var repredictionIndex = prediction.RepredictionIndex; |
| | | 1382 | | |
| | 1 | 1383 | | if (!costsByIndex.ContainsKey(repredictionIndex)) |
| | | 1384 | | { |
| | 1 | 1385 | | costsByIndex[repredictionIndex] = (0.0, 0); |
| | | 1386 | | } |
| | | 1387 | | |
| | 1 | 1388 | | var (currentCost, currentCount) = costsByIndex[repredictionIndex]; |
| | 1 | 1389 | | costsByIndex[repredictionIndex] = (currentCost + prediction.Cost, currentCount + 1); |
| | | 1390 | | } |
| | | 1391 | | } |
| | | 1392 | | |
| | 1 | 1393 | | return costsByIndex; |
| | | 1394 | | } |
| | 0 | 1395 | | catch (Exception ex) |
| | | 1396 | | { |
| | 0 | 1397 | | _logger.LogError(ex, "Failed to get match prediction costs by reprediction index for model {Model} and commu |
| | 0 | 1398 | | modelConfig.DisplayName, communityContext); |
| | 0 | 1399 | | throw; |
| | | 1400 | | } |
| | 1 | 1401 | | } |
| | | 1402 | | |
| | | 1403 | | /// <summary> |
| | | 1404 | | /// Get bonus prediction costs and counts grouped by reprediction index for cost analysis. |
| | | 1405 | | /// Used specifically by the cost command to include all repredictions. |
| | | 1406 | | /// </summary> |
| | | 1407 | | public Task<Dictionary<int, (double cost, int count)>> GetBonusPredictionCostsByRepredictionIndexAsync( |
| | | 1408 | | string model, |
| | | 1409 | | string communityContext, |
| | | 1410 | | CancellationToken cancellationToken = default) |
| | | 1411 | | { |
| | 1 | 1412 | | return GetBonusPredictionCostsByRepredictionIndexAsync( |
| | 1 | 1413 | | PredictionModelConfig.Create(model), |
| | 1 | 1414 | | communityContext, |
| | 1 | 1415 | | cancellationToken); |
| | | 1416 | | } |
| | | 1417 | | |
| | | 1418 | | public async Task<Dictionary<int, (double cost, int count)>> GetBonusPredictionCostsByRepredictionIndexAsync( |
| | | 1419 | | PredictionModelConfig modelConfig, |
| | | 1420 | | string communityContext, |
| | | 1421 | | CancellationToken cancellationToken = default) |
| | | 1422 | | { |
| | | 1423 | | try |
| | | 1424 | | { |
| | 1 | 1425 | | var costsByIndex = new Dictionary<int, (double cost, int count)>(); |
| | | 1426 | | |
| | | 1427 | | // Query for bonus predictions with cost data |
| | 1 | 1428 | | var query = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1429 | | .WhereEqualTo("competition", _competition) |
| | 1 | 1430 | | .WhereEqualTo("model", modelConfig.Model) |
| | 1 | 1431 | | .WhereEqualTo("communityContext", communityContext); |
| | | 1432 | | |
| | 1 | 1433 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1434 | | |
| | 1 | 1435 | | foreach (var doc in snapshot.Documents) |
| | | 1436 | | { |
| | 1 | 1437 | | if (doc.Exists) |
| | | 1438 | | { |
| | 1 | 1439 | | var prediction = doc.ConvertTo<FirestoreBonusPrediction>(); |
| | 1 | 1440 | | if (GetConfigMatchKind(prediction, modelConfig) == PredictionConfigMatchKind.None) |
| | | 1441 | | { |
| | | 1442 | | continue; |
| | | 1443 | | } |
| | | 1444 | | |
| | 1 | 1445 | | var repredictionIndex = prediction.RepredictionIndex; |
| | | 1446 | | |
| | 1 | 1447 | | if (!costsByIndex.ContainsKey(repredictionIndex)) |
| | | 1448 | | { |
| | 1 | 1449 | | costsByIndex[repredictionIndex] = (0.0, 0); |
| | | 1450 | | } |
| | | 1451 | | |
| | 1 | 1452 | | var (currentCost, currentCount) = costsByIndex[repredictionIndex]; |
| | 1 | 1453 | | costsByIndex[repredictionIndex] = (currentCost + prediction.Cost, currentCount + 1); |
| | | 1454 | | } |
| | | 1455 | | } |
| | | 1456 | | |
| | 1 | 1457 | | return costsByIndex; |
| | | 1458 | | } |
| | 0 | 1459 | | catch (Exception ex) |
| | | 1460 | | { |
| | 0 | 1461 | | _logger.LogError(ex, "Failed to get bonus prediction costs by reprediction index for model {Model} and commu |
| | 0 | 1462 | | modelConfig.DisplayName, communityContext); |
| | 0 | 1463 | | throw; |
| | | 1464 | | } |
| | 1 | 1465 | | } |
| | | 1466 | | |
| | | 1467 | | /// <inheritdoc /> |
| | | 1468 | | public async Task<List<int>> GetAvailableMatchdaysAsync(CancellationToken cancellationToken = default) |
| | | 1469 | | { |
| | | 1470 | | try |
| | | 1471 | | { |
| | 1 | 1472 | | var matchdays = new HashSet<int>(); |
| | | 1473 | | |
| | | 1474 | | // Query match predictions for unique matchdays |
| | 1 | 1475 | | var query = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1476 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1477 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 1478 | | |
| | 1 | 1479 | | foreach (var doc in snapshot.Documents) |
| | | 1480 | | { |
| | 1 | 1481 | | if (doc.TryGetValue<int>("matchday", out var matchday) && matchday > 0) |
| | | 1482 | | { |
| | 1 | 1483 | | matchdays.Add(matchday); |
| | | 1484 | | } |
| | | 1485 | | } |
| | | 1486 | | |
| | 1 | 1487 | | return matchdays.OrderBy(m => m).ToList(); |
| | | 1488 | | } |
| | 0 | 1489 | | catch (Exception ex) |
| | | 1490 | | { |
| | 0 | 1491 | | _logger.LogError(ex, "Failed to get available matchdays"); |
| | 0 | 1492 | | throw; |
| | | 1493 | | } |
| | 1 | 1494 | | } |
| | | 1495 | | |
| | | 1496 | | /// <inheritdoc /> |
| | | 1497 | | public async Task<List<string>> GetAvailableModelsAsync(CancellationToken cancellationToken = default) |
| | | 1498 | | { |
| | | 1499 | | try |
| | | 1500 | | { |
| | 1 | 1501 | | var models = new HashSet<string>(); |
| | | 1502 | | |
| | | 1503 | | // Query match predictions for unique models |
| | 1 | 1504 | | var matchQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1505 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1506 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 1507 | | |
| | 1 | 1508 | | foreach (var doc in matchSnapshot.Documents) |
| | | 1509 | | { |
| | 1 | 1510 | | if (doc.TryGetValue<string>("model", out var model) && !string.IsNullOrWhiteSpace(model)) |
| | | 1511 | | { |
| | 1 | 1512 | | models.Add(model); |
| | | 1513 | | } |
| | | 1514 | | } |
| | | 1515 | | |
| | | 1516 | | // Query bonus predictions for unique models |
| | 1 | 1517 | | var bonusQuery = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1518 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1519 | | var bonusSnapshot = await bonusQuery.GetSnapshotAsync(cancellationToken); |
| | | 1520 | | |
| | 1 | 1521 | | foreach (var doc in bonusSnapshot.Documents) |
| | | 1522 | | { |
| | 1 | 1523 | | if (doc.TryGetValue<string>("model", out var model) && !string.IsNullOrWhiteSpace(model)) |
| | | 1524 | | { |
| | 1 | 1525 | | models.Add(model); |
| | | 1526 | | } |
| | | 1527 | | } |
| | | 1528 | | |
| | 1 | 1529 | | return models.OrderBy(model => model, StringComparer.Ordinal).ToList(); |
| | | 1530 | | } |
| | 0 | 1531 | | catch (Exception ex) |
| | | 1532 | | { |
| | 0 | 1533 | | _logger.LogError(ex, "Failed to get available models"); |
| | 0 | 1534 | | throw; |
| | | 1535 | | } |
| | 1 | 1536 | | } |
| | | 1537 | | |
| | | 1538 | | /// <inheritdoc /> |
| | | 1539 | | public async Task<List<PredictionModelConfig>> GetAvailableModelConfigsAsync(CancellationToken cancellationToken = d |
| | | 1540 | | { |
| | | 1541 | | try |
| | | 1542 | | { |
| | 1 | 1543 | | var modelConfigs = new Dictionary<string, PredictionModelConfig>(StringComparer.Ordinal); |
| | | 1544 | | |
| | 1 | 1545 | | var matchQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1546 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1547 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 1548 | | |
| | 1 | 1549 | | foreach (var doc in matchSnapshot.Documents) |
| | | 1550 | | { |
| | 1 | 1551 | | AddModelConfigIfValid(modelConfigs, doc.ConvertTo<FirestoreMatchPrediction>()); |
| | | 1552 | | } |
| | | 1553 | | |
| | 1 | 1554 | | var bonusQuery = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1555 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1556 | | var bonusSnapshot = await bonusQuery.GetSnapshotAsync(cancellationToken); |
| | | 1557 | | |
| | 1 | 1558 | | foreach (var doc in bonusSnapshot.Documents) |
| | | 1559 | | { |
| | 1 | 1560 | | AddModelConfigIfValid(modelConfigs, doc.ConvertTo<FirestoreBonusPrediction>()); |
| | | 1561 | | } |
| | | 1562 | | |
| | 1 | 1563 | | return modelConfigs.Values |
| | 1 | 1564 | | .OrderBy(config => config.Model, StringComparer.Ordinal) |
| | 1 | 1565 | | .ThenBy(config => config.ReasoningEffort is null ? string.Empty : config.ReasoningEffort, StringComparer |
| | 1 | 1566 | | .ToList(); |
| | | 1567 | | } |
| | 0 | 1568 | | catch (Exception ex) |
| | | 1569 | | { |
| | 0 | 1570 | | _logger.LogError(ex, "Failed to get available model configs"); |
| | 0 | 1571 | | throw; |
| | | 1572 | | } |
| | 1 | 1573 | | } |
| | | 1574 | | |
| | | 1575 | | private static void AddModelConfigIfValid(Dictionary<string, PredictionModelConfig> modelConfigs, FirestoreMatchPred |
| | | 1576 | | { |
| | 1 | 1577 | | AddModelConfigIfValid(modelConfigs, prediction.Model, prediction.ReasoningEffort); |
| | 1 | 1578 | | } |
| | | 1579 | | |
| | | 1580 | | private static void AddModelConfigIfValid(Dictionary<string, PredictionModelConfig> modelConfigs, FirestoreBonusPred |
| | | 1581 | | { |
| | 1 | 1582 | | AddModelConfigIfValid(modelConfigs, prediction.Model, prediction.ReasoningEffort); |
| | 1 | 1583 | | } |
| | | 1584 | | |
| | | 1585 | | private static void AddModelConfigIfValid(Dictionary<string, PredictionModelConfig> modelConfigs, string model, stri |
| | | 1586 | | { |
| | 1 | 1587 | | if (string.IsNullOrWhiteSpace(model)) |
| | | 1588 | | { |
| | 0 | 1589 | | return; |
| | | 1590 | | } |
| | | 1591 | | |
| | 1 | 1592 | | if (!PredictionModelConfig.IsValidReasoningEffort(reasoningEffort)) |
| | | 1593 | | { |
| | 0 | 1594 | | return; |
| | | 1595 | | } |
| | | 1596 | | |
| | 1 | 1597 | | var modelConfig = PredictionModelConfig.Create(model, reasoningEffort); |
| | 1 | 1598 | | modelConfigs.TryAdd(modelConfig.IdentityKey, modelConfig); |
| | 1 | 1599 | | } |
| | | 1600 | | |
| | | 1601 | | /// <inheritdoc /> |
| | | 1602 | | public async Task<List<string>> GetAvailableCommunityContextsAsync(CancellationToken cancellationToken = default) |
| | | 1603 | | { |
| | | 1604 | | try |
| | | 1605 | | { |
| | 1 | 1606 | | var communityContexts = new HashSet<string>(); |
| | | 1607 | | |
| | | 1608 | | // Query match predictions for unique community contexts |
| | 1 | 1609 | | var matchQuery = _firestoreDb.Collection(_predictionsCollection) |
| | 1 | 1610 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1611 | | var matchSnapshot = await matchQuery.GetSnapshotAsync(cancellationToken); |
| | | 1612 | | |
| | 1 | 1613 | | foreach (var doc in matchSnapshot.Documents) |
| | | 1614 | | { |
| | 1 | 1615 | | if (doc.TryGetValue<string>("communityContext", out var context) && !string.IsNullOrWhiteSpace(context)) |
| | | 1616 | | { |
| | 1 | 1617 | | communityContexts.Add(context); |
| | | 1618 | | } |
| | | 1619 | | } |
| | | 1620 | | |
| | | 1621 | | // Query bonus predictions for unique community contexts |
| | 1 | 1622 | | var bonusQuery = _firestoreDb.Collection(_bonusPredictionsCollection) |
| | 1 | 1623 | | .WhereEqualTo("competition", _competition); |
| | 1 | 1624 | | var bonusSnapshot = await bonusQuery.GetSnapshotAsync(cancellationToken); |
| | | 1625 | | |
| | 1 | 1626 | | foreach (var doc in bonusSnapshot.Documents) |
| | | 1627 | | { |
| | 1 | 1628 | | if (doc.TryGetValue<string>("communityContext", out var context) && !string.IsNullOrWhiteSpace(context)) |
| | | 1629 | | { |
| | 1 | 1630 | | communityContexts.Add(context); |
| | | 1631 | | } |
| | | 1632 | | } |
| | | 1633 | | |
| | 1 | 1634 | | return communityContexts.OrderBy(context => context, StringComparer.Ordinal).ToList(); |
| | | 1635 | | } |
| | 0 | 1636 | | catch (Exception ex) |
| | | 1637 | | { |
| | 0 | 1638 | | _logger.LogError(ex, "Failed to get available community contexts"); |
| | 0 | 1639 | | throw; |
| | | 1640 | | } |
| | 1 | 1641 | | } |
| | | 1642 | | |
| | | 1643 | | private string? SerializeJustification(PredictionJustification? justification) |
| | | 1644 | | { |
| | 1 | 1645 | | if (justification == null) |
| | | 1646 | | { |
| | 1 | 1647 | | return null; |
| | | 1648 | | } |
| | | 1649 | | |
| | 1 | 1650 | | if (!HasJustificationContent(justification)) |
| | | 1651 | | { |
| | 1 | 1652 | | return null; |
| | | 1653 | | } |
| | | 1654 | | |
| | 1 | 1655 | | var stored = new StoredJustification |
| | 1 | 1656 | | { |
| | 1 | 1657 | | KeyReasoning = justification.KeyReasoning?.Trim() ?? string.Empty, |
| | 1 | 1658 | | ContextSources = new StoredContextSources |
| | 1 | 1659 | | { |
| | 1 | 1660 | | MostValuable = justification.ContextSources?.MostValuable? |
| | 1 | 1661 | | .Where(entry => entry != null) |
| | 1 | 1662 | | .Select(ToStoredContextSource) |
| | 1 | 1663 | | .ToList() ?? new List<StoredContextSource>(), |
| | 1 | 1664 | | LeastValuable = justification.ContextSources?.LeastValuable? |
| | 1 | 1665 | | .Where(entry => entry != null) |
| | 1 | 1666 | | .Select(ToStoredContextSource) |
| | 1 | 1667 | | .ToList() ?? new List<StoredContextSource>() |
| | 1 | 1668 | | }, |
| | 1 | 1669 | | Uncertainties = justification.Uncertainties? |
| | 1 | 1670 | | .Where(item => !string.IsNullOrWhiteSpace(item)) |
| | 1 | 1671 | | .Select(item => item.Trim()) |
| | 1 | 1672 | | .ToList() ?? new List<string>() |
| | 1 | 1673 | | }; |
| | | 1674 | | |
| | 1 | 1675 | | return JsonSerializer.Serialize(stored, JustificationSerializerOptions); |
| | | 1676 | | } |
| | | 1677 | | |
| | | 1678 | | private static bool HasJustificationContent(PredictionJustification justification) |
| | | 1679 | | { |
| | 1 | 1680 | | if (!string.IsNullOrWhiteSpace(justification.KeyReasoning)) |
| | | 1681 | | { |
| | 1 | 1682 | | return true; |
| | | 1683 | | } |
| | | 1684 | | |
| | 1 | 1685 | | if (justification.ContextSources?.MostValuable != null && |
| | 1 | 1686 | | justification.ContextSources.MostValuable.Any(HasSourceContent)) |
| | | 1687 | | { |
| | 1 | 1688 | | return true; |
| | | 1689 | | } |
| | | 1690 | | |
| | 1 | 1691 | | if (justification.ContextSources?.LeastValuable != null && |
| | 1 | 1692 | | justification.ContextSources.LeastValuable.Any(HasSourceContent)) |
| | | 1693 | | { |
| | 1 | 1694 | | return true; |
| | | 1695 | | } |
| | | 1696 | | |
| | 1 | 1697 | | return justification.Uncertainties != null && |
| | 1 | 1698 | | justification.Uncertainties.Any(item => !string.IsNullOrWhiteSpace(item)); |
| | | 1699 | | } |
| | | 1700 | | |
| | | 1701 | | private static bool HasSourceContent(PredictionJustificationContextSource source) |
| | | 1702 | | { |
| | 1 | 1703 | | return !string.IsNullOrWhiteSpace(source?.DocumentName) || |
| | 1 | 1704 | | !string.IsNullOrWhiteSpace(source?.Details); |
| | | 1705 | | } |
| | | 1706 | | |
| | | 1707 | | private PredictionJustification? DeserializeJustification(string? serialized) |
| | | 1708 | | { |
| | 1 | 1709 | | if (string.IsNullOrWhiteSpace(serialized)) |
| | | 1710 | | { |
| | 1 | 1711 | | return null; |
| | | 1712 | | } |
| | | 1713 | | |
| | 1 | 1714 | | var trimmed = serialized.Trim(); |
| | | 1715 | | |
| | 1 | 1716 | | if (!trimmed.StartsWith("{")) |
| | | 1717 | | { |
| | 1 | 1718 | | return new PredictionJustification( |
| | 1 | 1719 | | trimmed, |
| | 1 | 1720 | | new PredictionJustificationContextSources( |
| | 1 | 1721 | | Array.Empty<PredictionJustificationContextSource>(), |
| | 1 | 1722 | | Array.Empty<PredictionJustificationContextSource>()), |
| | 1 | 1723 | | Array.Empty<string>()); |
| | | 1724 | | } |
| | | 1725 | | |
| | | 1726 | | try |
| | | 1727 | | { |
| | 1 | 1728 | | var stored = JsonSerializer.Deserialize<StoredJustification>(trimmed, JustificationSerializerOptions); |
| | | 1729 | | |
| | 1 | 1730 | | if (stored == null) |
| | | 1731 | | { |
| | 0 | 1732 | | return null; |
| | | 1733 | | } |
| | | 1734 | | |
| | 1 | 1735 | | var contextSources = stored.ContextSources ?? new StoredContextSources(); |
| | | 1736 | | |
| | 1 | 1737 | | var mostValuable = contextSources.MostValuable? |
| | 1 | 1738 | | .Where(entry => entry != null) |
| | 1 | 1739 | | .Select(ToDomainContextSource) |
| | 1 | 1740 | | .ToList() ?? new List<PredictionJustificationContextSource>(); |
| | | 1741 | | |
| | 1 | 1742 | | var leastValuable = contextSources.LeastValuable? |
| | 1 | 1743 | | .Where(entry => entry != null) |
| | 1 | 1744 | | .Select(ToDomainContextSource) |
| | 1 | 1745 | | .ToList() ?? new List<PredictionJustificationContextSource>(); |
| | | 1746 | | |
| | 1 | 1747 | | var uncertainties = stored.Uncertainties? |
| | 1 | 1748 | | .Where(item => !string.IsNullOrWhiteSpace(item)) |
| | 1 | 1749 | | .Select(item => item.Trim()) |
| | 1 | 1750 | | .ToList() ?? new List<string>(); |
| | | 1751 | | |
| | 1 | 1752 | | var justification = new PredictionJustification( |
| | 1 | 1753 | | stored.KeyReasoning?.Trim() ?? string.Empty, |
| | 1 | 1754 | | new PredictionJustificationContextSources(mostValuable, leastValuable), |
| | 1 | 1755 | | uncertainties); |
| | | 1756 | | |
| | 1 | 1757 | | return HasJustificationContent(justification) ? justification : null; |
| | | 1758 | | } |
| | 1 | 1759 | | catch (JsonException ex) |
| | | 1760 | | { |
| | 1 | 1761 | | _logger.LogWarning(ex, "Failed to parse structured justification JSON; falling back to legacy text format"); |
| | | 1762 | | |
| | 1 | 1763 | | var fallbackJustification = new PredictionJustification( |
| | 1 | 1764 | | trimmed, |
| | 1 | 1765 | | new PredictionJustificationContextSources( |
| | 1 | 1766 | | Array.Empty<PredictionJustificationContextSource>(), |
| | 1 | 1767 | | Array.Empty<PredictionJustificationContextSource>()), |
| | 1 | 1768 | | Array.Empty<string>()); |
| | | 1769 | | |
| | 1 | 1770 | | return HasJustificationContent(fallbackJustification) ? fallbackJustification : null; |
| | | 1771 | | } |
| | 1 | 1772 | | } |
| | | 1773 | | |
| | | 1774 | | private static StoredContextSource ToStoredContextSource(PredictionJustificationContextSource source) |
| | | 1775 | | { |
| | 1 | 1776 | | return new StoredContextSource |
| | 1 | 1777 | | { |
| | 1 | 1778 | | DocumentName = source.DocumentName?.Trim() ?? string.Empty, |
| | 1 | 1779 | | Details = source.Details?.Trim() ?? string.Empty |
| | 1 | 1780 | | }; |
| | | 1781 | | } |
| | | 1782 | | |
| | | 1783 | | private static PredictionJustificationContextSource ToDomainContextSource(StoredContextSource source) |
| | | 1784 | | { |
| | 1 | 1785 | | var documentName = source.DocumentName?.Trim() ?? string.Empty; |
| | 1 | 1786 | | var details = source.Details?.Trim() ?? string.Empty; |
| | 1 | 1787 | | return new PredictionJustificationContextSource(documentName, details); |
| | | 1788 | | } |
| | | 1789 | | |
| | | 1790 | | private sealed class StoredJustification |
| | | 1791 | | { |
| | | 1792 | | public string? KeyReasoning { get; set; } |
| | | 1793 | | public StoredContextSources? ContextSources { get; set; } |
| | | 1794 | | public List<string>? Uncertainties { get; set; } |
| | | 1795 | | } |
| | | 1796 | | |
| | | 1797 | | private sealed class StoredContextSources |
| | | 1798 | | { |
| | | 1799 | | public List<StoredContextSource>? MostValuable { get; set; } |
| | | 1800 | | public List<StoredContextSource>? LeastValuable { get; set; } |
| | | 1801 | | } |
| | | 1802 | | |
| | | 1803 | | private sealed class StoredContextSource |
| | | 1804 | | { |
| | | 1805 | | public string? DocumentName { get; set; } |
| | | 1806 | | public string? Details { get; set; } |
| | | 1807 | | } |
| | | 1808 | | } |