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