| | | 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 VerifyBonusCommand : AsyncCommand<VerifySettings> |
| | | 11 | | { |
| | | 12 | | private readonly IAnsiConsole _console; |
| | | 13 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 14 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 15 | | private readonly ILogger<VerifyBonusCommand> _logger; |
| | | 16 | | |
| | 0 | 17 | | public VerifyBonusCommand( |
| | 0 | 18 | | IAnsiConsole console, |
| | 0 | 19 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 0 | 20 | | IKicktippClientFactory kicktippClientFactory, |
| | 0 | 21 | | ILogger<VerifyBonusCommand> logger) |
| | | 22 | | { |
| | 0 | 23 | | _console = console; |
| | 0 | 24 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 0 | 25 | | _kicktippClientFactory = kicktippClientFactory; |
| | 0 | 26 | | _logger = logger; |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | public override async Task<int> ExecuteAsync(CommandContext context, VerifySettings settings) |
| | | 30 | | { |
| | | 31 | | |
| | | 32 | | try |
| | | 33 | | { |
| | 0 | 34 | | _console.MarkupLine($"[green]Verify bonus command initialized[/]"); |
| | | 35 | | |
| | 0 | 36 | | if (settings.Verbose) |
| | | 37 | | { |
| | 0 | 38 | | _console.MarkupLine("[dim]Verbose mode enabled[/]"); |
| | | 39 | | } |
| | | 40 | | |
| | 0 | 41 | | if (settings.Agent) |
| | | 42 | | { |
| | 0 | 43 | | _console.MarkupLine("[blue]Agent mode enabled - prediction details will be hidden[/]"); |
| | | 44 | | } |
| | | 45 | | |
| | 0 | 46 | | if (settings.InitMatchday) |
| | | 47 | | { |
| | 0 | 48 | | _console.MarkupLine("[cyan]Init bonus mode enabled - will return error if no predictions exist[/]"); |
| | | 49 | | } |
| | | 50 | | |
| | 0 | 51 | | if (settings.CheckOutdated) |
| | | 52 | | { |
| | 0 | 53 | | _console.MarkupLine("[cyan]Outdated check enabled - predictions will be checked against latest context d |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | // Execute the verification workflow |
| | 0 | 57 | | var hasDiscrepancies = await ExecuteVerificationWorkflow(settings); |
| | | 58 | | |
| | 0 | 59 | | return hasDiscrepancies ? 1 : 0; |
| | | 60 | | } |
| | 0 | 61 | | catch (Exception ex) |
| | | 62 | | { |
| | 0 | 63 | | _logger.LogError(ex, "Error executing verify bonus command"); |
| | 0 | 64 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 0 | 65 | | return 1; |
| | | 66 | | } |
| | 0 | 67 | | } |
| | | 68 | | |
| | | 69 | | private async Task<bool> ExecuteVerificationWorkflow(VerifySettings settings) |
| | | 70 | | { |
| | 0 | 71 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | | 72 | | |
| | | 73 | | // Try to get the prediction repository (may be null if Firebase is not configured) |
| | 0 | 74 | | var predictionRepository = _firebaseServiceFactory.CreatePredictionRepository(); |
| | 0 | 75 | | if (predictionRepository == null) |
| | | 76 | | { |
| | 0 | 77 | | _console.MarkupLine("[red]Error: Database not configured. Cannot verify predictions without database access. |
| | 0 | 78 | | _console.MarkupLine("[yellow]Hint: Set FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON environment var |
| | 0 | 79 | | return true; // Consider this a failure |
| | | 80 | | } |
| | | 81 | | |
| | | 82 | | // Get KPI repository for outdated checks (required for bonus predictions) |
| | 0 | 83 | | var kpiRepository = _firebaseServiceFactory.CreateKpiRepository(); |
| | | 84 | | |
| | | 85 | | // Determine community context (use explicit setting or fall back to community name) |
| | 0 | 86 | | string communityContext = settings.CommunityContext ?? settings.Community; |
| | | 87 | | |
| | 0 | 88 | | _console.MarkupLine($"[blue]Using community:[/] [yellow]{settings.Community}[/]"); |
| | 0 | 89 | | _console.MarkupLine($"[blue]Using community context:[/] [yellow]{communityContext}[/]"); |
| | 0 | 90 | | _console.MarkupLine("[blue]Getting open bonus questions from Kicktipp...[/]"); |
| | | 91 | | |
| | | 92 | | // Step 1: Get open bonus questions from Kicktipp |
| | 0 | 93 | | var bonusQuestions = await kicktippClient.GetOpenBonusQuestionsAsync(settings.Community); |
| | | 94 | | |
| | 0 | 95 | | if (!bonusQuestions.Any()) |
| | | 96 | | { |
| | 0 | 97 | | _console.MarkupLine("[yellow]No bonus questions found on Kicktipp[/]"); |
| | 0 | 98 | | return false; |
| | | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | _console.MarkupLine($"[green]Found {bonusQuestions.Count} bonus questions on Kicktipp[/]"); |
| | | 102 | | |
| | 0 | 103 | | _console.MarkupLine("[blue]Getting placed bonus predictions from Kicktipp...[/]"); |
| | | 104 | | |
| | | 105 | | // Step 1.5: Get currently placed predictions from Kicktipp |
| | 0 | 106 | | var placedPredictions = await kicktippClient.GetPlacedBonusPredictionsAsync(settings.Community); |
| | | 107 | | |
| | 0 | 108 | | _console.MarkupLine("[blue]Retrieving predictions from database...[/]"); |
| | | 109 | | |
| | 0 | 110 | | var hasDiscrepancies = false; |
| | 0 | 111 | | var totalQuestions = 0; |
| | 0 | 112 | | var questionsWithDatabasePredictions = 0; |
| | 0 | 113 | | var validPredictions = 0; |
| | | 114 | | |
| | | 115 | | // Step 2: For each bonus question, check if we have a prediction in database |
| | 0 | 116 | | foreach (var question in bonusQuestions) |
| | | 117 | | { |
| | 0 | 118 | | totalQuestions++; |
| | | 119 | | |
| | | 120 | | try |
| | | 121 | | { |
| | | 122 | | // Get prediction from database |
| | 0 | 123 | | if (settings.Verbose) |
| | | 124 | | { |
| | 0 | 125 | | _console.MarkupLine($"[dim] Looking up: {Markup.Escape(question.Text)}[/]"); |
| | | 126 | | } |
| | | 127 | | |
| | 0 | 128 | | var databasePrediction = await predictionRepository.GetBonusPredictionByTextAsync(question.Text, setting |
| | 0 | 129 | | var kicktippPrediction = placedPredictions.GetValueOrDefault(question.FormFieldName ?? question.Text); |
| | | 130 | | |
| | 0 | 131 | | if (databasePrediction != null) |
| | | 132 | | { |
| | 0 | 133 | | questionsWithDatabasePredictions++; |
| | | 134 | | |
| | | 135 | | // Validate the prediction against the question |
| | 0 | 136 | | var isValidPrediction = ValidateBonusPrediction(question, databasePrediction); |
| | | 137 | | |
| | | 138 | | // Compare database prediction with Kicktipp placed prediction |
| | 0 | 139 | | var predictionsMatch = CompareBonusPredictions(databasePrediction, kicktippPrediction); |
| | | 140 | | |
| | | 141 | | // Check if prediction is outdated (if enabled) |
| | 0 | 142 | | var isOutdated = false; |
| | 0 | 143 | | if (settings.CheckOutdated) |
| | | 144 | | { |
| | 0 | 145 | | isOutdated = await CheckBonusPredictionOutdated(predictionRepository, kpiRepository, question.Te |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | // Consider prediction valid if it passes validation, matches Kicktipp, and is not outdated |
| | 0 | 149 | | var isPredictionValid = isValidPrediction && predictionsMatch && !isOutdated; |
| | | 150 | | |
| | 0 | 151 | | if (isPredictionValid) |
| | | 152 | | { |
| | 0 | 153 | | validPredictions++; |
| | | 154 | | |
| | 0 | 155 | | if (settings.Verbose) |
| | | 156 | | { |
| | 0 | 157 | | if (settings.Agent) |
| | | 158 | | { |
| | 0 | 159 | | _console.MarkupLine($"[green]✓ {Markup.Escape(question.Text)}[/] [dim](valid)[/]"); |
| | | 160 | | } |
| | | 161 | | else |
| | | 162 | | { |
| | 0 | 163 | | var optionTexts = question.Options |
| | 0 | 164 | | .Where(o => databasePrediction.SelectedOptionIds.Contains(o.Id)) |
| | 0 | 165 | | .Select(o => o.Text); |
| | 0 | 166 | | _console.MarkupLine($"[green]✓ {Markup.Escape(question.Text)}:[/] {string.Join(", ", opt |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | } |
| | | 170 | | else |
| | | 171 | | { |
| | 0 | 172 | | hasDiscrepancies = true; |
| | | 173 | | |
| | 0 | 174 | | if (settings.Agent) |
| | | 175 | | { |
| | 0 | 176 | | var status = !isValidPrediction ? "invalid prediction" : |
| | 0 | 177 | | !predictionsMatch ? "mismatch with Kicktipp" : "outdated"; |
| | 0 | 178 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}[/] [dim]({status})[/]"); |
| | | 179 | | } |
| | | 180 | | else |
| | | 181 | | { |
| | 0 | 182 | | if (!isValidPrediction) |
| | | 183 | | { |
| | 0 | 184 | | var optionTexts = question.Options |
| | 0 | 185 | | .Where(o => databasePrediction.SelectedOptionIds.Contains(o.Id)) |
| | 0 | 186 | | .Select(o => o.Text); |
| | 0 | 187 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}:[/] {string.Join(", ", optio |
| | | 188 | | } |
| | 0 | 189 | | else if (!predictionsMatch) |
| | | 190 | | { |
| | | 191 | | // Show mismatch details |
| | 0 | 192 | | var databaseTexts = question.Options |
| | 0 | 193 | | .Where(o => databasePrediction.SelectedOptionIds.Contains(o.Id)) |
| | 0 | 194 | | .Select(o => o.Text); |
| | 0 | 195 | | var kicktippTexts = kicktippPrediction != null |
| | 0 | 196 | | ? question.Options |
| | 0 | 197 | | .Where(o => kicktippPrediction.SelectedOptionIds.Contains(o.Id)) |
| | 0 | 198 | | .Select(o => o.Text) |
| | 0 | 199 | | : new List<string>(); |
| | | 200 | | |
| | 0 | 201 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}:[/]"); |
| | 0 | 202 | | _console.MarkupLine($" [yellow]Database:[/] {string.Join(", ", databaseTexts)}"); |
| | 0 | 203 | | _console.MarkupLine($" [yellow]Kicktipp:[/] {(kicktippTexts.Any() ? string.Join(", ", k |
| | | 204 | | } |
| | 0 | 205 | | else if (isOutdated) |
| | | 206 | | { |
| | 0 | 207 | | var optionTexts = question.Options |
| | 0 | 208 | | .Where(o => databasePrediction.SelectedOptionIds.Contains(o.Id)) |
| | 0 | 209 | | .Select(o => o.Text); |
| | 0 | 210 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}:[/] {string.Join(", ", optio |
| | 0 | 211 | | _console.MarkupLine($" [yellow]Status:[/] Outdated (context updated after prediction)") |
| | | 212 | | } |
| | | 213 | | } |
| | | 214 | | } |
| | | 215 | | } |
| | | 216 | | else |
| | | 217 | | { |
| | 0 | 218 | | hasDiscrepancies = true; |
| | | 219 | | |
| | 0 | 220 | | if (settings.Verbose) |
| | | 221 | | { |
| | 0 | 222 | | if (settings.Agent) |
| | | 223 | | { |
| | 0 | 224 | | _console.MarkupLine($"[yellow]○ {Markup.Escape(question.Text)}[/] [dim](no prediction)[/]"); |
| | | 225 | | } |
| | | 226 | | else |
| | | 227 | | { |
| | 0 | 228 | | _console.MarkupLine($"[yellow]○ {Markup.Escape(question.Text)}:[/] [dim](no prediction)[/]") |
| | | 229 | | } |
| | | 230 | | } |
| | | 231 | | } |
| | 0 | 232 | | } |
| | 0 | 233 | | catch (Exception ex) |
| | | 234 | | { |
| | 0 | 235 | | hasDiscrepancies = true; |
| | 0 | 236 | | _logger.LogError(ex, "Error verifying bonus prediction for question '{QuestionText}'", question.Text); |
| | | 237 | | |
| | 0 | 238 | | if (settings.Agent) |
| | | 239 | | { |
| | 0 | 240 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}[/] [dim](error)[/]"); |
| | | 241 | | } |
| | | 242 | | else |
| | | 243 | | { |
| | 0 | 244 | | _console.MarkupLine($"[red]✗ {Markup.Escape(question.Text)}:[/] Error during verification"); |
| | | 245 | | } |
| | 0 | 246 | | } |
| | 0 | 247 | | } |
| | | 248 | | |
| | | 249 | | // Step 3: Display summary |
| | 0 | 250 | | _console.WriteLine(); |
| | 0 | 251 | | _console.MarkupLine("[bold]Verification Summary:[/]"); |
| | 0 | 252 | | _console.MarkupLine($" Total bonus questions: {totalQuestions}"); |
| | 0 | 253 | | _console.MarkupLine($" Questions with database predictions: {questionsWithDatabasePredictions}"); |
| | 0 | 254 | | _console.MarkupLine($" Valid predictions: {validPredictions}"); |
| | | 255 | | |
| | | 256 | | // Check for init-bonus mode first |
| | 0 | 257 | | if (settings.InitMatchday && questionsWithDatabasePredictions == 0) |
| | | 258 | | { |
| | 0 | 259 | | _console.MarkupLine("[yellow] Init bonus detected - no database predictions exist[/]"); |
| | 0 | 260 | | _console.MarkupLine("[red]Returning error to trigger initial prediction workflow[/]"); |
| | 0 | 261 | | return true; // Return error to trigger workflow |
| | | 262 | | } |
| | | 263 | | |
| | 0 | 264 | | if (hasDiscrepancies) |
| | | 265 | | { |
| | 0 | 266 | | _console.MarkupLine($"[red] Missing or invalid predictions: {totalQuestions - validPredictions}[/]"); |
| | 0 | 267 | | _console.MarkupLine("[red]Verification failed - some predictions are missing or invalid[/]"); |
| | | 268 | | } |
| | | 269 | | else |
| | | 270 | | { |
| | 0 | 271 | | _console.MarkupLine("[green] All predictions are valid - verification successful[/]"); |
| | | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | return hasDiscrepancies; |
| | 0 | 275 | | } |
| | | 276 | | |
| | | 277 | | private static bool ValidateBonusPrediction(BonusQuestion question, BonusPrediction prediction) |
| | | 278 | | { |
| | | 279 | | // Check if all selected option IDs exist in the question |
| | 0 | 280 | | var validOptionIds = question.Options.Select(o => o.Id).ToHashSet(); |
| | 0 | 281 | | var allOptionsValid = prediction.SelectedOptionIds.All(id => validOptionIds.Contains(id)); |
| | | 282 | | |
| | 0 | 283 | | if (!allOptionsValid) |
| | | 284 | | { |
| | 0 | 285 | | return false; |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | // Check if the number of selections is valid |
| | 0 | 289 | | var selectionCount = prediction.SelectedOptionIds.Count; |
| | 0 | 290 | | if (selectionCount < 1 || selectionCount > question.MaxSelections) |
| | | 291 | | { |
| | 0 | 292 | | return false; |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | // Check for duplicates |
| | 0 | 296 | | var uniqueSelections = prediction.SelectedOptionIds.Distinct().Count(); |
| | 0 | 297 | | if (uniqueSelections != selectionCount) |
| | | 298 | | { |
| | 0 | 299 | | return false; |
| | | 300 | | } |
| | | 301 | | |
| | 0 | 302 | | return true; |
| | | 303 | | } |
| | | 304 | | |
| | | 305 | | private async Task<bool> CheckBonusPredictionOutdated( |
| | | 306 | | IPredictionRepository predictionRepository, |
| | | 307 | | IKpiRepository kpiRepository, |
| | | 308 | | string questionText, |
| | | 309 | | string model, |
| | | 310 | | string communityContext, |
| | | 311 | | bool verbose) |
| | | 312 | | { |
| | | 313 | | try |
| | | 314 | | { |
| | | 315 | | // Get prediction metadata (includes creation timestamp and context document names) |
| | 0 | 316 | | var predictionMetadata = await predictionRepository.GetBonusPredictionMetadataByTextAsync( |
| | 0 | 317 | | questionText, model, communityContext); |
| | | 318 | | |
| | 0 | 319 | | if (predictionMetadata == null) |
| | | 320 | | { |
| | | 321 | | // No metadata found, assume not outdated |
| | 0 | 322 | | return false; |
| | | 323 | | } |
| | | 324 | | |
| | | 325 | | // Check if any KPI document has been updated after the prediction was created |
| | 0 | 326 | | foreach (var contextDocumentName in predictionMetadata.ContextDocumentNames) |
| | | 327 | | { |
| | 0 | 328 | | var kpiDocument = await kpiRepository.GetKpiDocumentAsync(contextDocumentName, communityContext); |
| | 0 | 329 | | if (kpiDocument != null) |
| | | 330 | | { |
| | | 331 | | // Compare the creation timestamps |
| | | 332 | | // Note: We need to be careful about timezone handling here |
| | | 333 | | // Both timestamps should be in UTC for proper comparison |
| | 0 | 334 | | if (kpiDocument.CreatedAt > predictionMetadata.CreatedAt) |
| | | 335 | | { |
| | 0 | 336 | | if (verbose) |
| | | 337 | | { |
| | 0 | 338 | | _console.MarkupLine($"[yellow]KPI document '{contextDocumentName}' updated after prediction |
| | 0 | 339 | | _console.MarkupLine($" [dim]Prediction created:[/] {predictionMetadata.CreatedAt:yyyy-MM-dd |
| | 0 | 340 | | _console.MarkupLine($" [dim]KPI document created:[/] {kpiDocument.CreatedAt:yyyy-MM-dd HH:m |
| | | 341 | | } |
| | 0 | 342 | | return true; // Prediction is outdated |
| | | 343 | | } |
| | | 344 | | |
| | 0 | 345 | | if (verbose) |
| | | 346 | | { |
| | 0 | 347 | | _console.MarkupLine($"[dim]KPI document '{contextDocumentName}' found, version {kpiDocument.Vers |
| | | 348 | | } |
| | | 349 | | } |
| | 0 | 350 | | else if (verbose) |
| | | 351 | | { |
| | 0 | 352 | | _console.MarkupLine($"[yellow]Warning: KPI document '{contextDocumentName}' not found[/]"); |
| | | 353 | | } |
| | 0 | 354 | | } |
| | | 355 | | |
| | 0 | 356 | | return false; // No KPI documents are newer than the prediction |
| | | 357 | | } |
| | 0 | 358 | | catch (Exception ex) |
| | | 359 | | { |
| | 0 | 360 | | if (verbose) |
| | | 361 | | { |
| | 0 | 362 | | _console.MarkupLine($"[yellow]Warning: Could not check if prediction is outdated: {ex.Message}[/]"); |
| | | 363 | | } |
| | 0 | 364 | | return false; // Assume not outdated if we can't determine |
| | | 365 | | } |
| | 0 | 366 | | } |
| | | 367 | | |
| | | 368 | | private static bool CompareBonusPredictions(BonusPrediction? databasePrediction, BonusPrediction? kicktippPrediction |
| | | 369 | | { |
| | | 370 | | // Both null - match |
| | 0 | 371 | | if (databasePrediction == null && kicktippPrediction == null) |
| | | 372 | | { |
| | 0 | 373 | | return true; |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | // One null, other not - mismatch |
| | 0 | 377 | | if (databasePrediction == null || kicktippPrediction == null) |
| | | 378 | | { |
| | 0 | 379 | | return false; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | // Both have values - compare selected option IDs |
| | 0 | 383 | | var databaseOptions = databasePrediction.SelectedOptionIds.OrderBy(x => x).ToList(); |
| | 0 | 384 | | var kicktippOptions = kicktippPrediction.SelectedOptionIds.OrderBy(x => x).ToList(); |
| | | 385 | | |
| | 0 | 386 | | return databaseOptions.SequenceEqual(kicktippOptions); |
| | | 387 | | } |
| | | 388 | | } |