| | | 1 | | using EHonda.KicktippAi.Core; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Spectre.Console.Cli; |
| | | 4 | | using Spectre.Console; |
| | | 5 | | using KicktippIntegration; |
| | | 6 | | using Orchestrator.Commands.Shared; |
| | | 7 | | using Orchestrator.Infrastructure; |
| | | 8 | | using Orchestrator.Infrastructure.Factories; |
| | | 9 | | |
| | | 10 | | namespace Orchestrator.Commands.Operations.Verify; |
| | | 11 | | |
| | | 12 | | public class VerifyMatchdayCommand : AsyncCommand<VerifySettings> |
| | | 13 | | { |
| | | 14 | | private readonly IAnsiConsole _console; |
| | | 15 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 16 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 17 | | private readonly ILogger<VerifyMatchdayCommand> _logger; |
| | | 18 | | |
| | 1 | 19 | | public VerifyMatchdayCommand( |
| | 1 | 20 | | IAnsiConsole console, |
| | 1 | 21 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 22 | | IKicktippClientFactory kicktippClientFactory, |
| | 1 | 23 | | ILogger<VerifyMatchdayCommand> logger) |
| | | 24 | | { |
| | 1 | 25 | | _console = console; |
| | 1 | 26 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 27 | | _kicktippClientFactory = kicktippClientFactory; |
| | 1 | 28 | | _logger = logger; |
| | 1 | 29 | | } |
| | | 30 | | |
| | | 31 | | protected override async Task<int> ExecuteAsync(CommandContext context, VerifySettings settings, CancellationToken c |
| | | 32 | | { |
| | | 33 | | |
| | | 34 | | try |
| | | 35 | | { |
| | 1 | 36 | | _console.MarkupLine($"[green]Verify matchday command initialized[/]"); |
| | | 37 | | |
| | 1 | 38 | | if (settings.Verbose) |
| | | 39 | | { |
| | 1 | 40 | | _console.MarkupLine("[dim]Verbose mode enabled[/]"); |
| | | 41 | | } |
| | | 42 | | |
| | 1 | 43 | | if (settings.Agent) |
| | | 44 | | { |
| | 1 | 45 | | _console.MarkupLine("[blue]Agent mode enabled - prediction details will be hidden[/]"); |
| | | 46 | | } |
| | | 47 | | |
| | 1 | 48 | | if (settings.InitMatchday) |
| | | 49 | | { |
| | 1 | 50 | | _console.MarkupLine("[cyan]Init matchday mode enabled - will return error if no predictions exist[/]"); |
| | | 51 | | } |
| | | 52 | | |
| | 1 | 53 | | if (settings.CheckOutdated) |
| | | 54 | | { |
| | 1 | 55 | | _console.MarkupLine("[cyan]Outdated check enabled - predictions will be checked against latest context d |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | // Execute the verification workflow |
| | 1 | 59 | | var hasDiscrepancies = await ExecuteVerificationWorkflow(settings); |
| | | 60 | | |
| | 1 | 61 | | return hasDiscrepancies ? 1 : 0; |
| | | 62 | | } |
| | 1 | 63 | | catch (Exception ex) |
| | | 64 | | { |
| | 1 | 65 | | _logger.LogError(ex, "Error executing verify matchday command"); |
| | 1 | 66 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 1 | 67 | | return 1; |
| | | 68 | | } |
| | 1 | 69 | | } |
| | | 70 | | |
| | | 71 | | private async Task<bool> ExecuteVerificationWorkflow(VerifySettings settings) |
| | | 72 | | { |
| | 1 | 73 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | 1 | 74 | | string communityContext = settings.CommunityContext ?? settings.Community; |
| | 1 | 75 | | var competition = CompetitionResolver.ResolveCompetition(settings.Competition, settings.Community, communityCont |
| | 1 | 76 | | var modelConfig = PredictionServiceCommandSupport.CreateModelConfig(settings.Model, settings.ReasoningEffort); |
| | 1 | 77 | | var repositoryCompetition = CompetitionResolver.ToRepositoryCompetitionArgument(competition); |
| | | 78 | | |
| | | 79 | | // Try to get the prediction repository (may be null if Firebase is not configured) |
| | 1 | 80 | | var predictionRepository = _firebaseServiceFactory.CreatePredictionRepository(repositoryCompetition); |
| | 1 | 81 | | if (predictionRepository == null) |
| | | 82 | | { |
| | 1 | 83 | | _console.MarkupLine("[red]Error: Database not configured. Cannot verify predictions without database access. |
| | 1 | 84 | | _console.MarkupLine("[yellow]Hint: Set FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON environment var |
| | 1 | 85 | | return true; // Consider this a failure |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | // Get context repository for outdated checks (may be null if Firebase is not configured) |
| | 1 | 89 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(repositoryCompetition); |
| | 1 | 90 | | if (settings.CheckOutdated && contextRepository == null) |
| | | 91 | | { |
| | 1 | 92 | | _console.MarkupLine("[red]Error: Database not configured. Cannot check outdated predictions without database |
| | 1 | 93 | | _console.MarkupLine("[yellow]Hint: Set FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON environment var |
| | 1 | 94 | | return true; // Consider this a failure |
| | | 95 | | } |
| | | 96 | | |
| | 1 | 97 | | _console.MarkupLine($"[blue]Using community:[/] [yellow]{settings.Community}[/]"); |
| | 1 | 98 | | _console.MarkupLine($"[blue]Using community context:[/] [yellow]{communityContext}[/]"); |
| | 1 | 99 | | _console.MarkupLine($"[blue]Using competition:[/] [yellow]{competition}[/]"); |
| | 1 | 100 | | _console.MarkupLine($"[blue]Using model config:[/] [yellow]{modelConfig.DisplayName}[/]"); |
| | 1 | 101 | | _console.MarkupLine("[blue]Getting placed predictions from Kicktipp...[/]"); |
| | | 102 | | |
| | | 103 | | // Step 1: Get placed predictions from Kicktipp |
| | 1 | 104 | | var placedPredictions = await kicktippClient.GetPlacedPredictionsAsync(settings.Community); |
| | | 105 | | |
| | 1 | 106 | | if (!placedPredictions.Any()) |
| | | 107 | | { |
| | 1 | 108 | | _console.MarkupLine("[yellow]No matches found on Kicktipp[/]"); |
| | 1 | 109 | | return false; |
| | | 110 | | } |
| | | 111 | | |
| | 1 | 112 | | _console.MarkupLine($"[green]Found {placedPredictions.Count} matches on Kicktipp[/]"); |
| | | 113 | | |
| | 1 | 114 | | _console.MarkupLine("[blue]Retrieving predictions from database...[/]"); |
| | | 115 | | |
| | 1 | 116 | | var hasDiscrepancies = false; |
| | 1 | 117 | | var totalMatches = 0; |
| | 1 | 118 | | var matchesWithPlacedPredictions = 0; |
| | 1 | 119 | | var matchesWithDatabasePredictions = 0; |
| | 1 | 120 | | var matchingPredictions = 0; |
| | | 121 | | |
| | | 122 | | // Step 2: For each match, compare with database predictions |
| | 1 | 123 | | foreach (var (match, kicktippPrediction) in placedPredictions) |
| | | 124 | | { |
| | 1 | 125 | | totalMatches++; |
| | | 126 | | |
| | | 127 | | try |
| | | 128 | | { |
| | | 129 | | Prediction? databasePrediction; |
| | | 130 | | |
| | | 131 | | // For cancelled matches, use team-names-only lookup to handle startsAt inconsistencies |
| | | 132 | | // See IPredictionRepository.cs for detailed documentation on this edge case |
| | 1 | 133 | | if (match.IsCancelled) |
| | | 134 | | { |
| | 1 | 135 | | if (settings.Verbose) |
| | | 136 | | { |
| | 1 | 137 | | _console.MarkupLine($"[dim] Looking up (cancelled match, team-names-only): {match.HomeTeam} vs |
| | | 138 | | } |
| | 1 | 139 | | databasePrediction = await predictionRepository.GetCancelledMatchPredictionAsync( |
| | 1 | 140 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 141 | | } |
| | | 142 | | else |
| | | 143 | | { |
| | 1 | 144 | | if (settings.Verbose) |
| | | 145 | | { |
| | 1 | 146 | | _console.MarkupLine($"[dim] Looking up: {match.HomeTeam} vs {match.AwayTeam} at {match.StartsAt |
| | | 147 | | } |
| | 1 | 148 | | databasePrediction = await predictionRepository.GetPredictionAsync(match, modelConfig, communityCont |
| | | 149 | | } |
| | | 150 | | |
| | 1 | 151 | | if (kicktippPrediction != null) |
| | | 152 | | { |
| | 1 | 153 | | matchesWithPlacedPredictions++; |
| | | 154 | | } |
| | | 155 | | |
| | 1 | 156 | | if (databasePrediction != null) |
| | | 157 | | { |
| | 1 | 158 | | matchesWithDatabasePredictions++; |
| | 1 | 159 | | if (settings.Verbose && !settings.Agent) |
| | | 160 | | { |
| | 1 | 161 | | _console.MarkupLine($"[dim] Found database prediction: {databasePrediction.HomeGoals}:{database |
| | | 162 | | } |
| | | 163 | | } |
| | 1 | 164 | | else if (settings.Verbose && !settings.Agent) |
| | | 165 | | { |
| | 1 | 166 | | _console.MarkupLine($"[dim] No database prediction found[/]"); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | // Check if prediction is outdated (if enabled and context repository is available) |
| | 1 | 170 | | var isOutdated = false; |
| | 1 | 171 | | if (settings.CheckOutdated && contextRepository != null && databasePrediction != null) |
| | | 172 | | { |
| | 1 | 173 | | isOutdated = await CheckPredictionOutdated(predictionRepository, contextRepository, match, modelConf |
| | | 174 | | } |
| | | 175 | | |
| | | 176 | | // Compare predictions |
| | 1 | 177 | | var isMatchingPrediction = ComparePredictions(kicktippPrediction, databasePrediction); |
| | | 178 | | |
| | | 179 | | // Consider prediction invalid if it's outdated or mismatched |
| | 1 | 180 | | var isValidPrediction = isMatchingPrediction && !isOutdated; |
| | | 181 | | |
| | 1 | 182 | | if (isValidPrediction) |
| | | 183 | | { |
| | 1 | 184 | | matchingPredictions++; |
| | | 185 | | |
| | 1 | 186 | | if (settings.Verbose) |
| | | 187 | | { |
| | 1 | 188 | | if (settings.Agent) |
| | | 189 | | { |
| | 1 | 190 | | _console.MarkupLine($"[green]✓ {match.HomeTeam} vs {match.AwayTeam}[/] [dim](valid)[/]"); |
| | | 191 | | } |
| | | 192 | | else |
| | | 193 | | { |
| | 1 | 194 | | var predictionText = kicktippPrediction?.ToString() ?? "no prediction"; |
| | 1 | 195 | | _console.MarkupLine($"[green]✓ {match.HomeTeam} vs {match.AwayTeam}:[/] {predictionText} [di |
| | | 196 | | } |
| | | 197 | | } |
| | | 198 | | } |
| | | 199 | | else |
| | | 200 | | { |
| | 1 | 201 | | hasDiscrepancies = true; |
| | | 202 | | |
| | 1 | 203 | | if (settings.Agent) |
| | | 204 | | { |
| | 1 | 205 | | var reason = isOutdated ? "outdated" : "mismatch"; |
| | 1 | 206 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}[/] [dim]({reason})[/]"); |
| | | 207 | | } |
| | | 208 | | else |
| | | 209 | | { |
| | 1 | 210 | | var kicktippText = kicktippPrediction?.ToString() ?? "no prediction"; |
| | 1 | 211 | | var databaseText = databasePrediction != null ? $"{databasePrediction.HomeGoals}:{databasePredic |
| | | 212 | | |
| | 1 | 213 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}:[/]"); |
| | 1 | 214 | | _console.MarkupLine($" [yellow]Kicktipp:[/] {kicktippText}"); |
| | 1 | 215 | | _console.MarkupLine($" [yellow]Database:[/] {databaseText}"); |
| | | 216 | | |
| | 1 | 217 | | if (isOutdated) |
| | | 218 | | { |
| | 1 | 219 | | _console.MarkupLine($" [yellow]Status:[/] Outdated (context updated after prediction)"); |
| | | 220 | | } |
| | | 221 | | } |
| | | 222 | | } |
| | 1 | 223 | | } |
| | 1 | 224 | | catch (Exception ex) |
| | | 225 | | { |
| | 1 | 226 | | hasDiscrepancies = true; |
| | 1 | 227 | | _logger.LogError(ex, "Error verifying prediction for {Match}", $"{match.HomeTeam} vs {match.AwayTeam}"); |
| | | 228 | | |
| | 1 | 229 | | if (settings.Agent) |
| | | 230 | | { |
| | 1 | 231 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}[/] [dim](error)[/]"); |
| | | 232 | | } |
| | | 233 | | else |
| | | 234 | | { |
| | 1 | 235 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}:[/] Error during verification"); |
| | | 236 | | } |
| | 1 | 237 | | } |
| | 1 | 238 | | } |
| | | 239 | | |
| | | 240 | | // Step 3: Display summary |
| | 1 | 241 | | _console.WriteLine(); |
| | 1 | 242 | | _console.MarkupLine("[bold]Verification Summary:[/]"); |
| | 1 | 243 | | _console.MarkupLine($" Total matches: {totalMatches}"); |
| | 1 | 244 | | _console.MarkupLine($" Matches with Kicktipp predictions: {matchesWithPlacedPredictions}"); |
| | 1 | 245 | | _console.MarkupLine($" Matches with database predictions: {matchesWithDatabasePredictions}"); |
| | 1 | 246 | | _console.MarkupLine($" Matching predictions: {matchingPredictions}"); |
| | | 247 | | |
| | | 248 | | // Check for init-matchday mode first |
| | 1 | 249 | | if (settings.InitMatchday && matchesWithDatabasePredictions == 0) |
| | | 250 | | { |
| | 1 | 251 | | _console.MarkupLine("[yellow] Init matchday detected - no database predictions exist[/]"); |
| | 1 | 252 | | _console.MarkupLine("[red]Returning error to trigger initial prediction workflow[/]"); |
| | 1 | 253 | | return true; // Return error to trigger workflow |
| | | 254 | | } |
| | | 255 | | |
| | 1 | 256 | | if (hasDiscrepancies) |
| | | 257 | | { |
| | 1 | 258 | | _console.MarkupLine($"[red] Discrepancies found: {totalMatches - matchingPredictions}[/]"); |
| | 1 | 259 | | _console.MarkupLine("[red]Verification failed - predictions do not match[/]"); |
| | | 260 | | } |
| | | 261 | | else |
| | | 262 | | { |
| | 1 | 263 | | _console.MarkupLine("[green] All predictions match - verification successful[/]"); |
| | | 264 | | } |
| | | 265 | | |
| | 1 | 266 | | return hasDiscrepancies; |
| | 1 | 267 | | } |
| | | 268 | | |
| | | 269 | | private static bool ComparePredictions(BetPrediction? kicktippPrediction, Prediction? databasePrediction) |
| | | 270 | | { |
| | | 271 | | // Both null - match |
| | 1 | 272 | | if (kicktippPrediction == null && databasePrediction == null) |
| | | 273 | | { |
| | 1 | 274 | | return true; |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | // One null, other not - mismatch |
| | 1 | 278 | | if (kicktippPrediction == null || databasePrediction == null) |
| | | 279 | | { |
| | 1 | 280 | | return false; |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | // Both have values - compare |
| | 1 | 284 | | return kicktippPrediction.HomeGoals == databasePrediction.HomeGoals && |
| | 1 | 285 | | kicktippPrediction.AwayGoals == databasePrediction.AwayGoals; |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | private async Task<bool> CheckPredictionOutdated(IPredictionRepository predictionRepository, IContextRepository cont |
| | | 289 | | { |
| | | 290 | | try |
| | | 291 | | { |
| | | 292 | | // Get prediction metadata with context document names and timestamps |
| | | 293 | | // For cancelled matches, use team-names-only lookup to handle startsAt inconsistencies |
| | | 294 | | PredictionMetadata? predictionMetadata; |
| | 1 | 295 | | if (match.IsCancelled) |
| | | 296 | | { |
| | 1 | 297 | | predictionMetadata = await predictionRepository.GetCancelledMatchPredictionMetadataAsync( |
| | 1 | 298 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 299 | | } |
| | | 300 | | else |
| | | 301 | | { |
| | 1 | 302 | | predictionMetadata = await predictionRepository.GetPredictionMetadataAsync(match, modelConfig, community |
| | | 303 | | } |
| | | 304 | | |
| | 1 | 305 | | if (predictionMetadata == null || !predictionMetadata.ContextDocumentNames.Any()) |
| | | 306 | | { |
| | | 307 | | // If no context documents were used, prediction can't be outdated based on context changes |
| | 1 | 308 | | return false; |
| | | 309 | | } |
| | | 310 | | |
| | 1 | 311 | | if (verbose) |
| | | 312 | | { |
| | 1 | 313 | | _console.MarkupLine($"[dim] Checking {predictionMetadata.ContextDocumentNames.Count} context documents |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | // Check if any context document has been updated after the prediction was created |
| | 1 | 317 | | foreach (var documentName in predictionMetadata.ContextDocumentNames) |
| | | 318 | | { |
| | | 319 | | // Strip any display suffix (e.g., " (kpi-context)") from the context document name |
| | | 320 | | // to get the actual document name stored in the repository |
| | 1 | 321 | | var actualDocumentName = StripDisplaySuffix(documentName); |
| | | 322 | | |
| | 1 | 323 | | var standingsDocumentName = MatchContextDocumentCatalog.GetStandingsDocumentName(competition); |
| | 1 | 324 | | if (actualDocumentName.Equals(standingsDocumentName, StringComparison.OrdinalIgnoreCase)) |
| | | 325 | | { |
| | 1 | 326 | | if (verbose) |
| | | 327 | | { |
| | 1 | 328 | | _console.MarkupLine($"[dim] Skipping outdated check for '{actualDocumentName}' (excluded from c |
| | | 329 | | } |
| | 1 | 330 | | continue; |
| | | 331 | | } |
| | | 332 | | |
| | 1 | 333 | | var latestContextDocument = await contextRepository.GetLatestContextDocumentAsync(actualDocumentName, co |
| | | 334 | | |
| | 1 | 335 | | if (latestContextDocument != null && latestContextDocument.CreatedAt > predictionMetadata.CreatedAt) |
| | | 336 | | { |
| | 1 | 337 | | var predictionTimeContextDocument = await contextRepository.GetContextDocumentByTimestampAsync( |
| | 1 | 338 | | actualDocumentName, |
| | 1 | 339 | | predictionMetadata.CreatedAt, |
| | 1 | 340 | | communityContext); |
| | | 341 | | |
| | 1 | 342 | | if (predictionTimeContextDocument != null && |
| | 1 | 343 | | string.Equals( |
| | 1 | 344 | | predictionTimeContextDocument.Content, |
| | 1 | 345 | | latestContextDocument.Content, |
| | 1 | 346 | | StringComparison.Ordinal)) |
| | | 347 | | { |
| | 1 | 348 | | if (verbose) |
| | | 349 | | { |
| | 1 | 350 | | _console.MarkupLine( |
| | 1 | 351 | | $"[dim] Context document '{actualDocumentName}' has newer versions after the prediction |
| | | 352 | | } |
| | | 353 | | |
| | 1 | 354 | | continue; |
| | | 355 | | } |
| | | 356 | | |
| | 1 | 357 | | if (verbose) |
| | | 358 | | { |
| | 1 | 359 | | _console.MarkupLine($"[dim] Context document '{actualDocumentName}' (stored as '{documentName}' |
| | | 360 | | } |
| | 1 | 361 | | return true; // Prediction is outdated |
| | | 362 | | } |
| | 1 | 363 | | else if (verbose && latestContextDocument == null) |
| | | 364 | | { |
| | 1 | 365 | | _console.MarkupLine($"[yellow] Warning: Context document '{actualDocumentName}' not found in reposi |
| | | 366 | | } |
| | 1 | 367 | | } |
| | | 368 | | |
| | 1 | 369 | | return false; // Prediction is up-to-date |
| | | 370 | | } |
| | 1 | 371 | | catch (Exception ex) |
| | | 372 | | { |
| | | 373 | | // Log error but don't fail verification due to outdated check issues |
| | 1 | 374 | | if (verbose) |
| | | 375 | | { |
| | 1 | 376 | | _console.MarkupLine($"[yellow] Warning: Failed to check outdated status: {ex.Message}[/]"); |
| | | 377 | | } |
| | 1 | 378 | | return false; |
| | | 379 | | } |
| | 1 | 380 | | } |
| | | 381 | | |
| | | 382 | | /// <summary> |
| | | 383 | | /// Strips display suffixes like " (kpi-context)" from context document names |
| | | 384 | | /// to get the actual document name used in the repository. |
| | | 385 | | /// </summary> |
| | | 386 | | /// <param name="displayName">The display name that may contain a suffix</param> |
| | | 387 | | /// <returns>The actual document name without any display suffix</returns> |
| | | 388 | | private static string StripDisplaySuffix(string displayName) |
| | | 389 | | { |
| | | 390 | | // Look for patterns like " (some-text)" at the end and remove them |
| | 1 | 391 | | var lastParenIndex = displayName.LastIndexOf(" ("); |
| | 1 | 392 | | if (lastParenIndex > 0 && displayName.EndsWith(")")) |
| | | 393 | | { |
| | 1 | 394 | | return displayName.Substring(0, lastParenIndex); |
| | | 395 | | } |
| | 1 | 396 | | return displayName; |
| | | 397 | | } |
| | | 398 | | } |