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