| | | 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 | | // Log warning for cancelled matches - they have inherited times which may affect database lookup reliabilit |
| | 1 | 123 | | if (match.IsCancelled) |
| | | 124 | | { |
| | 1 | 125 | | _console.MarkupLine($"[yellow] ⚠ {match.HomeTeam} vs {match.AwayTeam} is cancelled (Abgesagt). " + |
| | 1 | 126 | | $"Database lookup uses inherited time which may not match original prediction time.[/]"); |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | try |
| | | 130 | | { |
| | | 131 | | // Get prediction from database |
| | 1 | 132 | | if (settings.Verbose) |
| | | 133 | | { |
| | 1 | 134 | | _console.MarkupLine($"[dim] Looking up: {match.HomeTeam} vs {match.AwayTeam} at {match.StartsAt}{(m |
| | | 135 | | } |
| | | 136 | | |
| | 1 | 137 | | var databasePrediction = await predictionRepository.GetPredictionAsync(match, settings.Model, communityC |
| | | 138 | | |
| | 1 | 139 | | if (kicktippPrediction != null) |
| | | 140 | | { |
| | 1 | 141 | | matchesWithPlacedPredictions++; |
| | | 142 | | } |
| | | 143 | | |
| | 1 | 144 | | if (databasePrediction != null) |
| | | 145 | | { |
| | 1 | 146 | | matchesWithDatabasePredictions++; |
| | 1 | 147 | | if (settings.Verbose && !settings.Agent) |
| | | 148 | | { |
| | 1 | 149 | | _console.MarkupLine($"[dim] Found database prediction: {databasePrediction.HomeGoals}:{database |
| | | 150 | | } |
| | | 151 | | } |
| | 1 | 152 | | else if (settings.Verbose && !settings.Agent) |
| | | 153 | | { |
| | 1 | 154 | | _console.MarkupLine($"[dim] No database prediction found[/]"); |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | // Check if prediction is outdated (if enabled and context repository is available) |
| | 1 | 158 | | var isOutdated = false; |
| | 1 | 159 | | if (settings.CheckOutdated && contextRepository != null && databasePrediction != null) |
| | | 160 | | { |
| | 1 | 161 | | isOutdated = await CheckPredictionOutdated(predictionRepository, contextRepository, match, settings. |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | // Compare predictions |
| | 1 | 165 | | var isMatchingPrediction = ComparePredictions(kicktippPrediction, databasePrediction); |
| | | 166 | | |
| | | 167 | | // Consider prediction invalid if it's outdated or mismatched |
| | 1 | 168 | | var isValidPrediction = isMatchingPrediction && !isOutdated; |
| | | 169 | | |
| | 1 | 170 | | if (isValidPrediction) |
| | | 171 | | { |
| | 1 | 172 | | matchingPredictions++; |
| | | 173 | | |
| | 1 | 174 | | if (settings.Verbose) |
| | | 175 | | { |
| | 1 | 176 | | if (settings.Agent) |
| | | 177 | | { |
| | 1 | 178 | | _console.MarkupLine($"[green]✓ {match.HomeTeam} vs {match.AwayTeam}[/] [dim](valid)[/]"); |
| | | 179 | | } |
| | | 180 | | else |
| | | 181 | | { |
| | 1 | 182 | | var predictionText = kicktippPrediction?.ToString() ?? "no prediction"; |
| | 1 | 183 | | _console.MarkupLine($"[green]✓ {match.HomeTeam} vs {match.AwayTeam}:[/] {predictionText} [di |
| | | 184 | | } |
| | | 185 | | } |
| | | 186 | | } |
| | | 187 | | else |
| | | 188 | | { |
| | 1 | 189 | | hasDiscrepancies = true; |
| | | 190 | | |
| | 1 | 191 | | if (settings.Agent) |
| | | 192 | | { |
| | 1 | 193 | | var reason = isOutdated ? "outdated" : "mismatch"; |
| | 1 | 194 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}[/] [dim]({reason})[/]"); |
| | | 195 | | } |
| | | 196 | | else |
| | | 197 | | { |
| | 1 | 198 | | var kicktippText = kicktippPrediction?.ToString() ?? "no prediction"; |
| | 1 | 199 | | var databaseText = databasePrediction != null ? $"{databasePrediction.HomeGoals}:{databasePredic |
| | | 200 | | |
| | 1 | 201 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}:[/]"); |
| | 1 | 202 | | _console.MarkupLine($" [yellow]Kicktipp:[/] {kicktippText}"); |
| | 1 | 203 | | _console.MarkupLine($" [yellow]Database:[/] {databaseText}"); |
| | | 204 | | |
| | 1 | 205 | | if (isOutdated) |
| | | 206 | | { |
| | 1 | 207 | | _console.MarkupLine($" [yellow]Status:[/] Outdated (context updated after prediction)"); |
| | | 208 | | } |
| | | 209 | | } |
| | | 210 | | } |
| | 1 | 211 | | } |
| | 1 | 212 | | catch (Exception ex) |
| | | 213 | | { |
| | 1 | 214 | | hasDiscrepancies = true; |
| | 1 | 215 | | _logger.LogError(ex, "Error verifying prediction for {Match}", $"{match.HomeTeam} vs {match.AwayTeam}"); |
| | | 216 | | |
| | 1 | 217 | | if (settings.Agent) |
| | | 218 | | { |
| | 1 | 219 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}[/] [dim](error)[/]"); |
| | | 220 | | } |
| | | 221 | | else |
| | | 222 | | { |
| | 1 | 223 | | _console.MarkupLine($"[red]✗ {match.HomeTeam} vs {match.AwayTeam}:[/] Error during verification"); |
| | | 224 | | } |
| | 1 | 225 | | } |
| | 1 | 226 | | } |
| | | 227 | | |
| | | 228 | | // Step 3: Display summary |
| | 1 | 229 | | _console.WriteLine(); |
| | 1 | 230 | | _console.MarkupLine("[bold]Verification Summary:[/]"); |
| | 1 | 231 | | _console.MarkupLine($" Total matches: {totalMatches}"); |
| | 1 | 232 | | _console.MarkupLine($" Matches with Kicktipp predictions: {matchesWithPlacedPredictions}"); |
| | 1 | 233 | | _console.MarkupLine($" Matches with database predictions: {matchesWithDatabasePredictions}"); |
| | 1 | 234 | | _console.MarkupLine($" Matching predictions: {matchingPredictions}"); |
| | | 235 | | |
| | | 236 | | // Check for init-matchday mode first |
| | 1 | 237 | | if (settings.InitMatchday && matchesWithDatabasePredictions == 0) |
| | | 238 | | { |
| | 1 | 239 | | _console.MarkupLine("[yellow] Init matchday detected - no database predictions exist[/]"); |
| | 1 | 240 | | _console.MarkupLine("[red]Returning error to trigger initial prediction workflow[/]"); |
| | 1 | 241 | | return true; // Return error to trigger workflow |
| | | 242 | | } |
| | | 243 | | |
| | 1 | 244 | | if (hasDiscrepancies) |
| | | 245 | | { |
| | 1 | 246 | | _console.MarkupLine($"[red] Discrepancies found: {totalMatches - matchingPredictions}[/]"); |
| | 1 | 247 | | _console.MarkupLine("[red]Verification failed - predictions do not match[/]"); |
| | | 248 | | } |
| | | 249 | | else |
| | | 250 | | { |
| | 1 | 251 | | _console.MarkupLine("[green] All predictions match - verification successful[/]"); |
| | | 252 | | } |
| | | 253 | | |
| | 1 | 254 | | return hasDiscrepancies; |
| | 1 | 255 | | } |
| | | 256 | | |
| | | 257 | | private static bool ComparePredictions(BetPrediction? kicktippPrediction, Prediction? databasePrediction) |
| | | 258 | | { |
| | | 259 | | // Both null - match |
| | 1 | 260 | | if (kicktippPrediction == null && databasePrediction == null) |
| | | 261 | | { |
| | 1 | 262 | | return true; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | // One null, other not - mismatch |
| | 1 | 266 | | if (kicktippPrediction == null || databasePrediction == null) |
| | | 267 | | { |
| | 1 | 268 | | return false; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | // Both have values - compare |
| | 1 | 272 | | return kicktippPrediction.HomeGoals == databasePrediction.HomeGoals && |
| | 1 | 273 | | kicktippPrediction.AwayGoals == databasePrediction.AwayGoals; |
| | | 274 | | } |
| | | 275 | | |
| | | 276 | | private async Task<bool> CheckPredictionOutdated(IPredictionRepository predictionRepository, IContextRepository cont |
| | | 277 | | { |
| | | 278 | | try |
| | | 279 | | { |
| | | 280 | | // Get prediction metadata with context document names and timestamps |
| | 1 | 281 | | var predictionMetadata = await predictionRepository.GetPredictionMetadataAsync(match, model, communityContex |
| | | 282 | | |
| | 1 | 283 | | if (predictionMetadata == null || !predictionMetadata.ContextDocumentNames.Any()) |
| | | 284 | | { |
| | | 285 | | // If no context documents were used, prediction can't be outdated based on context changes |
| | 1 | 286 | | return false; |
| | | 287 | | } |
| | | 288 | | |
| | 1 | 289 | | if (verbose) |
| | | 290 | | { |
| | 1 | 291 | | _console.MarkupLine($"[dim] Checking {predictionMetadata.ContextDocumentNames.Count} context documents |
| | | 292 | | } |
| | | 293 | | |
| | | 294 | | // Check if any context document has been updated after the prediction was created |
| | 1 | 295 | | foreach (var documentName in predictionMetadata.ContextDocumentNames) |
| | | 296 | | { |
| | | 297 | | // Strip any display suffix (e.g., " (kpi-context)") from the context document name |
| | | 298 | | // to get the actual document name stored in the repository |
| | 1 | 299 | | var actualDocumentName = StripDisplaySuffix(documentName); |
| | | 300 | | |
| | | 301 | | // Skip bundesliga-standings.csv from outdated check to reduce unnecessary repredictions |
| | 1 | 302 | | if (actualDocumentName.Equals("bundesliga-standings.csv", StringComparison.OrdinalIgnoreCase)) |
| | | 303 | | { |
| | 1 | 304 | | if (verbose) |
| | | 305 | | { |
| | 1 | 306 | | _console.MarkupLine($"[dim] Skipping outdated check for '{actualDocumentName}' (excluded from c |
| | | 307 | | } |
| | 1 | 308 | | continue; |
| | | 309 | | } |
| | | 310 | | |
| | 1 | 311 | | var latestContextDocument = await contextRepository.GetLatestContextDocumentAsync(actualDocumentName, co |
| | | 312 | | |
| | 1 | 313 | | if (latestContextDocument != null && latestContextDocument.CreatedAt > predictionMetadata.CreatedAt) |
| | | 314 | | { |
| | 1 | 315 | | if (verbose) |
| | | 316 | | { |
| | 1 | 317 | | _console.MarkupLine($"[dim] Context document '{actualDocumentName}' (stored as '{documentName}' |
| | | 318 | | } |
| | 1 | 319 | | return true; // Prediction is outdated |
| | | 320 | | } |
| | 1 | 321 | | else if (verbose && latestContextDocument == null) |
| | | 322 | | { |
| | 1 | 323 | | _console.MarkupLine($"[yellow] Warning: Context document '{actualDocumentName}' not found in reposi |
| | | 324 | | } |
| | 1 | 325 | | } |
| | | 326 | | |
| | 1 | 327 | | return false; // Prediction is up-to-date |
| | | 328 | | } |
| | 1 | 329 | | catch (Exception ex) |
| | | 330 | | { |
| | | 331 | | // Log error but don't fail verification due to outdated check issues |
| | 1 | 332 | | if (verbose) |
| | | 333 | | { |
| | 1 | 334 | | _console.MarkupLine($"[yellow] Warning: Failed to check outdated status: {ex.Message}[/]"); |
| | | 335 | | } |
| | 1 | 336 | | return false; |
| | | 337 | | } |
| | 1 | 338 | | } |
| | | 339 | | |
| | | 340 | | /// <summary> |
| | | 341 | | /// Strips display suffixes like " (kpi-context)" from context document names |
| | | 342 | | /// to get the actual document name used in the repository. |
| | | 343 | | /// </summary> |
| | | 344 | | /// <param name="displayName">The display name that may contain a suffix</param> |
| | | 345 | | /// <returns>The actual document name without any display suffix</returns> |
| | | 346 | | private static string StripDisplaySuffix(string displayName) |
| | | 347 | | { |
| | | 348 | | // Look for patterns like " (some-text)" at the end and remove them |
| | 1 | 349 | | var lastParenIndex = displayName.LastIndexOf(" ("); |
| | 1 | 350 | | if (lastParenIndex > 0 && displayName.EndsWith(")")) |
| | | 351 | | { |
| | 1 | 352 | | return displayName.Substring(0, lastParenIndex); |
| | | 353 | | } |
| | 1 | 354 | | return displayName; |
| | | 355 | | } |
| | | 356 | | } |