| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Spectre.Console.Cli; |
| | | 4 | | using Spectre.Console; |
| | | 5 | | using KicktippIntegration; |
| | | 6 | | using OpenAiIntegration; |
| | | 7 | | using ContextProviders.Kicktipp; |
| | | 8 | | using EHonda.KicktippAi.Core; |
| | | 9 | | using Orchestrator.Commands.Shared; |
| | | 10 | | using Orchestrator.Infrastructure; |
| | | 11 | | using Orchestrator.Infrastructure.Factories; |
| | | 12 | | using Orchestrator.Infrastructure.Langfuse; |
| | | 13 | | |
| | | 14 | | namespace Orchestrator.Commands.Operations.Matchday; |
| | | 15 | | |
| | | 16 | | public class MatchdayCommand : AsyncCommand<BaseSettings> |
| | | 17 | | { |
| | | 18 | | private readonly IAnsiConsole _console; |
| | | 19 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 20 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 21 | | private readonly IOpenAiServiceFactory _openAiServiceFactory; |
| | | 22 | | private readonly IContextProviderFactory _contextProviderFactory; |
| | | 23 | | private readonly ILogger<MatchdayCommand> _logger; |
| | | 24 | | private readonly ILangfusePublicApiClient? _langfuseClient; |
| | | 25 | | |
| | 1 | 26 | | public MatchdayCommand( |
| | 1 | 27 | | IAnsiConsole console, |
| | 1 | 28 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 29 | | IKicktippClientFactory kicktippClientFactory, |
| | 1 | 30 | | IOpenAiServiceFactory openAiServiceFactory, |
| | 1 | 31 | | IContextProviderFactory contextProviderFactory, |
| | 1 | 32 | | ILogger<MatchdayCommand> logger, |
| | 1 | 33 | | ILangfusePublicApiClient? langfuseClient = null) |
| | | 34 | | { |
| | 1 | 35 | | _console = console; |
| | 1 | 36 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 37 | | _kicktippClientFactory = kicktippClientFactory; |
| | 1 | 38 | | _openAiServiceFactory = openAiServiceFactory; |
| | 1 | 39 | | _contextProviderFactory = contextProviderFactory; |
| | 1 | 40 | | _logger = logger; |
| | 1 | 41 | | _langfuseClient = langfuseClient; |
| | 1 | 42 | | } |
| | | 43 | | |
| | | 44 | | protected override async Task<int> ExecuteAsync(CommandContext context, BaseSettings settings, CancellationToken can |
| | | 45 | | { |
| | 1 | 46 | | return await ExecuteWithSettingsAsync(settings, cancellationToken); |
| | 1 | 47 | | } |
| | | 48 | | |
| | | 49 | | internal async Task<int> ExecuteWithSettingsAsync(BaseSettings settings, CancellationToken cancellationToken = defau |
| | | 50 | | { |
| | | 51 | | |
| | | 52 | | try |
| | | 53 | | { |
| | 1 | 54 | | var initialModel = string.IsNullOrWhiteSpace(settings.Model) ? "(competition default)" : settings.Model; |
| | 1 | 55 | | _console.MarkupLine($"[green]Matchday command initialized with model:[/] [yellow]{initialModel}[/]"); |
| | | 56 | | |
| | 1 | 57 | | if (settings.Verbose) |
| | | 58 | | { |
| | 1 | 59 | | _console.MarkupLine("[dim]Verbose mode enabled[/]"); |
| | | 60 | | } |
| | | 61 | | |
| | 1 | 62 | | if (settings.OverrideKicktipp) |
| | | 63 | | { |
| | 1 | 64 | | _console.MarkupLine("[yellow]Override mode enabled - will override existing Kicktipp predictions[/]"); |
| | | 65 | | } |
| | | 66 | | |
| | 1 | 67 | | if (settings.OverrideDatabase) |
| | | 68 | | { |
| | 1 | 69 | | _console.MarkupLine("[yellow]Override database mode enabled - will override existing database prediction |
| | | 70 | | } |
| | | 71 | | |
| | 1 | 72 | | if (settings.Agent) |
| | | 73 | | { |
| | 1 | 74 | | _console.MarkupLine("[blue]Agent mode enabled - prediction details will be hidden[/]"); |
| | | 75 | | } |
| | | 76 | | |
| | 1 | 77 | | if (settings.DryRun) |
| | | 78 | | { |
| | 1 | 79 | | _console.MarkupLine("[magenta]Dry run mode enabled - no changes will be made to database or Kicktipp[/]" |
| | | 80 | | } |
| | | 81 | | |
| | 1 | 82 | | if (!string.IsNullOrEmpty(settings.EstimatedCostsModel)) |
| | | 83 | | { |
| | 1 | 84 | | _console.MarkupLine($"[cyan]Estimated costs will be calculated for model:[/] [yellow]{settings.Estimated |
| | | 85 | | } |
| | | 86 | | |
| | 1 | 87 | | if (settings.WithJustification) |
| | | 88 | | { |
| | 1 | 89 | | if (settings.Agent) |
| | | 90 | | { |
| | 1 | 91 | | _console.MarkupLine("[red]Error:[/] --with-justification cannot be used with --agent"); |
| | 1 | 92 | | return 1; |
| | | 93 | | } |
| | | 94 | | |
| | 1 | 95 | | _console.MarkupLine("[green]Justification output enabled - model reasoning will be captured[/]"); |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | // Validate reprediction settings |
| | 1 | 99 | | if (settings.OverrideDatabase && settings.IsRepredictMode) |
| | | 100 | | { |
| | 1 | 101 | | _console.MarkupLine($"[red]Error:[/] --override-database cannot be used with reprediction flags (--repre |
| | 1 | 102 | | return 1; |
| | | 103 | | } |
| | | 104 | | |
| | 1 | 105 | | if (settings.MaxRepredictions.HasValue && settings.MaxRepredictions.Value < 0) |
| | | 106 | | { |
| | 1 | 107 | | _console.MarkupLine($"[red]Error:[/] --max-repredictions must be 0 or greater"); |
| | 1 | 108 | | return 1; |
| | | 109 | | } |
| | | 110 | | |
| | 1 | 111 | | if (settings.IsRepredictMode) |
| | | 112 | | { |
| | 1 | 113 | | var maxValue = settings.MaxRepredictions ?? int.MaxValue; |
| | 1 | 114 | | _console.MarkupLine($"[yellow]Reprediction mode enabled - max repredictions: {(settings.MaxRepredictions |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // Execute the matchday workflow |
| | 1 | 118 | | await ExecuteMatchdayWorkflow(settings); |
| | | 119 | | |
| | 1 | 120 | | return 0; |
| | | 121 | | } |
| | 1 | 122 | | catch (Exception ex) |
| | | 123 | | { |
| | 1 | 124 | | _logger.LogError(ex, "Error executing matchday command"); |
| | 1 | 125 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 1 | 126 | | return 1; |
| | | 127 | | } |
| | 1 | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// Communities that have production workflows invoking the matchday command. |
| | | 132 | | /// Update this set when adding or removing community matchday workflows in .github/workflows/. |
| | | 133 | | /// See .github/workflows/AGENTS.md for details. |
| | | 134 | | /// </summary> |
| | 1 | 135 | | private static readonly HashSet<string> ProductionCommunities = new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 136 | | { |
| | 1 | 137 | | "schadensfresse", |
| | 1 | 138 | | "pes-squad", |
| | 1 | 139 | | "ehonda-ai-arena", |
| | 1 | 140 | | "rabetrabauken2026" |
| | 1 | 141 | | }; |
| | | 142 | | |
| | | 143 | | private async Task ExecuteMatchdayWorkflow(BaseSettings settings) |
| | | 144 | | { |
| | | 145 | | // Start root OTel activity for Langfuse trace |
| | 1 | 146 | | using var activity = Telemetry.Source.StartActivity("matchday"); |
| | | 147 | | |
| | | 148 | | // Set Langfuse environment based on community |
| | 1 | 149 | | var environment = ProductionCommunities.Contains(settings.Community) ? "production" : "development"; |
| | 1 | 150 | | LangfuseActivityPropagation.SetEnvironment(activity, environment); |
| | | 151 | | |
| | 1 | 152 | | string communityContext = settings.CommunityContext ?? settings.Community; |
| | 1 | 153 | | var competition = CompetitionResolver.ResolveCompetition(settings.Competition, settings.Community, communityCont |
| | 1 | 154 | | var modelConfig = PredictionServiceCommandSupport.CreateModelConfig(settings.Model, settings.ReasoningEffort); |
| | 1 | 155 | | var model = modelConfig.Model; |
| | 1 | 156 | | var repositoryCompetition = CompetitionResolver.ToRepositoryCompetitionArgument(competition); |
| | | 157 | | |
| | 1 | 158 | | if (settings.WithJustification && PredictionServiceCommandSupport.UsesLangfusePromptSource( |
| | 1 | 159 | | competition, |
| | 1 | 160 | | settings.Community, |
| | 1 | 161 | | communityContext, |
| | 1 | 162 | | settings.PromptSource, |
| | 1 | 163 | | bonusPrompt: false)) |
| | | 164 | | { |
| | 1 | 165 | | throw new NotSupportedException( |
| | 1 | 166 | | "WM 2026 hosted match prompts with justification are not supported yet. Use local prompts or omit --with |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | // Create services using factories |
| | 1 | 170 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | 1 | 171 | | var predictionService = PredictionServiceCommandSupport.CreatePredictionService( |
| | 1 | 172 | | _openAiServiceFactory, |
| | 1 | 173 | | _langfuseClient, |
| | 1 | 174 | | _console, |
| | 1 | 175 | | model, |
| | 1 | 176 | | competition, |
| | 1 | 177 | | settings.Community, |
| | 1 | 178 | | communityContext, |
| | 1 | 179 | | settings.PromptSource, |
| | 1 | 180 | | settings.LangfusePromptName, |
| | 1 | 181 | | settings.LangfusePromptLabel, |
| | 1 | 182 | | settings.LangfusePromptVersion, |
| | 1 | 183 | | modelConfig.ReasoningEffort, |
| | 1 | 184 | | settings.MaxOutputTokenCount, |
| | 1 | 185 | | bonusPrompt: false); |
| | | 186 | | |
| | | 187 | | // Create context provider using factory |
| | 1 | 188 | | var contextProvider = _contextProviderFactory.CreateKicktippContextProvider( |
| | 1 | 189 | | kicktippClient, settings.Community, communityContext, repositoryCompetition); |
| | | 190 | | |
| | 1 | 191 | | var tokenUsageTracker = _openAiServiceFactory.GetTokenUsageTracker(); |
| | | 192 | | |
| | | 193 | | // Log the prompt paths being used |
| | 1 | 194 | | if (settings.Verbose) |
| | | 195 | | { |
| | 1 | 196 | | _console.MarkupLine($"[dim]Match prompt:[/] [blue]{predictionService.GetMatchPromptPath(settings.WithJustifi |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | // Create repositories |
| | 1 | 200 | | var predictionRepository = _firebaseServiceFactory.CreatePredictionRepository(repositoryCompetition); |
| | 1 | 201 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(repositoryCompetition); |
| | 1 | 202 | | var databaseEnabled = true; |
| | | 203 | | |
| | | 204 | | // Reset token usage tracker for this workflow |
| | 1 | 205 | | tokenUsageTracker.Reset(); |
| | | 206 | | |
| | 1 | 207 | | _console.MarkupLine($"[blue]Using community:[/] [yellow]{settings.Community}[/]"); |
| | 1 | 208 | | _console.MarkupLine($"[blue]Using community context:[/] [yellow]{communityContext}[/]"); |
| | 1 | 209 | | _console.MarkupLine($"[blue]Using competition:[/] [yellow]{competition}[/]"); |
| | 1 | 210 | | _console.MarkupLine("[blue]Getting current matchday matches...[/]"); |
| | | 211 | | |
| | | 212 | | // Step 1: Get current matchday via GetMatchesWithHistoryAsync |
| | 1 | 213 | | var matchesWithHistory = await kicktippClient.GetMatchesWithHistoryAsync(settings.Community); |
| | | 214 | | |
| | 1 | 215 | | if (!matchesWithHistory.Any()) |
| | | 216 | | { |
| | 1 | 217 | | _console.MarkupLine("[yellow]No matches found for current matchday[/]"); |
| | 1 | 218 | | return; |
| | | 219 | | } |
| | | 220 | | |
| | | 221 | | // Set Langfuse trace-level attributes now that we know the matchday |
| | 1 | 222 | | var matchday = matchesWithHistory.First().Match.Matchday; |
| | 1 | 223 | | var sessionId = $"matchday-{matchday}-{settings.Community}"; |
| | 1 | 224 | | var traceTags = new[] { settings.Community, model, competition }; |
| | 1 | 225 | | LangfuseActivityPropagation.SetSessionId(activity, sessionId); |
| | 1 | 226 | | LangfuseActivityPropagation.SetTraceTags(activity, traceTags); |
| | 1 | 227 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "community", settings.Community); |
| | 1 | 228 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "communityContext", communityContext); |
| | 1 | 229 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "competition", competition); |
| | 1 | 230 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "matchday", matchday.ToString()); |
| | 1 | 231 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "model", model); |
| | 1 | 232 | | if (modelConfig.ReasoningEffort is not null) |
| | | 233 | | { |
| | 1 | 234 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "reasoningEffort", modelConfig.ReasoningEffort); |
| | | 235 | | } |
| | 1 | 236 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "homeTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 237 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "awayTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 238 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "teams", PredictionTelemetryMetadata.BuildDelimitedFilter |
| | 1 | 239 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "repredictMode", settings.IsRepredictMode ? "true" : "fal |
| | | 240 | | |
| | | 241 | | // Set trace input |
| | 1 | 242 | | var traceInput = new |
| | 1 | 243 | | { |
| | 1 | 244 | | community = settings.Community, |
| | 1 | 245 | | matchday, |
| | 1 | 246 | | model, |
| | 1 | 247 | | competition, |
| | 1 | 248 | | matches = matchesWithHistory.Select(m => $"{m.Match.HomeTeam} vs {m.Match.AwayTeam}").ToArray() |
| | 1 | 249 | | }; |
| | 1 | 250 | | activity?.SetTag("langfuse.trace.input", JsonSerializer.Serialize(traceInput)); |
| | | 251 | | |
| | 1 | 252 | | _console.MarkupLine($"[green]Found {matchesWithHistory.Count} matches for current matchday[/]"); |
| | | 253 | | |
| | 1 | 254 | | if (databaseEnabled) |
| | | 255 | | { |
| | 1 | 256 | | _console.MarkupLine("[blue]Database enabled - checking for existing predictions...[/]"); |
| | | 257 | | } |
| | | 258 | | |
| | 1 | 259 | | var predictions = new Dictionary<Match, BetPrediction>(); |
| | 1 | 260 | | var traceRepredictionIndices = new HashSet<string>(StringComparer.Ordinal); |
| | | 261 | | |
| | | 262 | | // Step 2: For each match, check database first, then predict if needed |
| | 1 | 263 | | foreach (var matchWithHistory in matchesWithHistory) |
| | | 264 | | { |
| | 1 | 265 | | var match = matchWithHistory.Match; |
| | | 266 | | |
| | | 267 | | // Log warning for cancelled matches - they have inherited times which may affect database operations |
| | 1 | 268 | | if (match.IsCancelled) |
| | | 269 | | { |
| | 1 | 270 | | _console.MarkupLine($"[yellow] ⚠ {match.HomeTeam} vs {match.AwayTeam} is cancelled (Abgesagt). " + |
| | 1 | 271 | | $"Processing with inherited time - prediction may need re-evaluation when rescheduled.[/]"); |
| | | 272 | | } |
| | | 273 | | |
| | 1 | 274 | | _console.MarkupLine($"[cyan]Processing:[/] {match.HomeTeam} vs {match.AwayTeam}{(match.IsCancelled ? " [yell |
| | | 275 | | |
| | | 276 | | try |
| | | 277 | | { |
| | 1 | 278 | | Prediction? prediction = null; |
| | 1 | 279 | | bool fromDatabase = false; |
| | 1 | 280 | | bool shouldPredict = false; |
| | 1 | 281 | | int? predictionRepredictionIndex = settings.IsRepredictMode ? null : 0; |
| | | 282 | | |
| | | 283 | | // Check if we have an existing prediction in the database |
| | 1 | 284 | | if (databaseEnabled && !settings.OverrideDatabase && !settings.IsRepredictMode) |
| | | 285 | | { |
| | | 286 | | // For cancelled matches, use team-names-only lookup to handle startsAt inconsistencies |
| | | 287 | | // See IPredictionRepository.cs for detailed documentation on this edge case |
| | 1 | 288 | | if (match.IsCancelled) |
| | | 289 | | { |
| | 1 | 290 | | prediction = await predictionRepository!.GetCancelledMatchPredictionAsync( |
| | 1 | 291 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 292 | | } |
| | | 293 | | else |
| | | 294 | | { |
| | 1 | 295 | | prediction = await predictionRepository!.GetPredictionAsync(match, modelConfig, communityContext |
| | | 296 | | } |
| | | 297 | | |
| | 1 | 298 | | if (prediction != null) |
| | | 299 | | { |
| | 1 | 300 | | fromDatabase = true; |
| | 1 | 301 | | if (settings.Agent) |
| | | 302 | | { |
| | 1 | 303 | | _console.MarkupLine($"[green] ✓ Found existing prediction[/] [dim](from database)[/]"); |
| | | 304 | | } |
| | | 305 | | else |
| | | 306 | | { |
| | 1 | 307 | | _console.MarkupLine($"[green] ✓ Found existing prediction:[/] {prediction.HomeGoals}:{predi |
| | 1 | 308 | | WriteJustificationIfNeeded(prediction, settings.WithJustification, fromDatabase: true); |
| | | 309 | | } |
| | | 310 | | } |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | // Handle reprediction logic |
| | 1 | 314 | | if (settings.IsRepredictMode && databaseEnabled) |
| | | 315 | | { |
| | | 316 | | // For cancelled matches, use team-names-only lookup to handle startsAt inconsistencies |
| | | 317 | | int currentRepredictionIndex; |
| | 1 | 318 | | if (match.IsCancelled) |
| | | 319 | | { |
| | 1 | 320 | | currentRepredictionIndex = await predictionRepository!.GetCancelledMatchRepredictionIndexAsync( |
| | 1 | 321 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 322 | | } |
| | | 323 | | else |
| | | 324 | | { |
| | 1 | 325 | | currentRepredictionIndex = await predictionRepository!.GetMatchRepredictionIndexAsync(match, mod |
| | | 326 | | } |
| | | 327 | | |
| | 1 | 328 | | if (currentRepredictionIndex == -1) |
| | | 329 | | { |
| | | 330 | | // No prediction exists yet - create first prediction |
| | 1 | 331 | | shouldPredict = true; |
| | 1 | 332 | | predictionRepredictionIndex = 0; |
| | 1 | 333 | | _console.MarkupLine($"[yellow] → No existing prediction found, creating first prediction...[/]" |
| | | 334 | | } |
| | | 335 | | else |
| | | 336 | | { |
| | | 337 | | // Check if we can create another reprediction |
| | 1 | 338 | | var maxAllowed = settings.MaxRepredictions ?? int.MaxValue; |
| | 1 | 339 | | var nextIndex = currentRepredictionIndex + 1; |
| | | 340 | | |
| | 1 | 341 | | if (nextIndex <= maxAllowed) |
| | | 342 | | { |
| | | 343 | | // Before repredicting, check if the current prediction is actually outdated |
| | 1 | 344 | | var isOutdated = await CheckPredictionOutdated(predictionRepository!, contextRepository, mat |
| | | 345 | | |
| | 1 | 346 | | if (isOutdated) |
| | | 347 | | { |
| | 1 | 348 | | shouldPredict = true; |
| | 1 | 349 | | predictionRepredictionIndex = nextIndex; |
| | 1 | 350 | | _console.MarkupLine($"[yellow] → Creating reprediction {nextIndex} (current: {currentRe |
| | | 351 | | } |
| | | 352 | | else |
| | | 353 | | { |
| | 1 | 354 | | traceRepredictionIndices.Add(currentRepredictionIndex.ToString()); |
| | 1 | 355 | | _console.MarkupLine($"[green] ✓ Skipped reprediction - current prediction is up-to-date |
| | | 356 | | |
| | | 357 | | // Get the latest prediction for display purposes |
| | | 358 | | // For cancelled matches, use team-names-only lookup |
| | 1 | 359 | | if (match.IsCancelled) |
| | | 360 | | { |
| | 1 | 361 | | prediction = await predictionRepository!.GetCancelledMatchPredictionAsync( |
| | 1 | 362 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 363 | | } |
| | | 364 | | else |
| | | 365 | | { |
| | 1 | 366 | | prediction = await predictionRepository!.GetPredictionAsync(match, modelConfig, comm |
| | | 367 | | } |
| | | 368 | | |
| | 1 | 369 | | if (prediction != null) |
| | | 370 | | { |
| | 1 | 371 | | fromDatabase = true; |
| | 1 | 372 | | if (!settings.Agent) |
| | | 373 | | { |
| | 1 | 374 | | _console.MarkupLine($"[green] ✓ Latest prediction:[/] {prediction.HomeGoals}:{p |
| | 1 | 375 | | WriteJustificationIfNeeded(prediction, settings.WithJustification, fromDatabase: |
| | | 376 | | } |
| | | 377 | | } |
| | | 378 | | } |
| | | 379 | | } |
| | | 380 | | else |
| | | 381 | | { |
| | 1 | 382 | | traceRepredictionIndices.Add(currentRepredictionIndex.ToString()); |
| | 1 | 383 | | _console.MarkupLine($"[yellow] ✗ Skipped - already at max repredictions ({currentRepredicti |
| | | 384 | | |
| | | 385 | | // Get the latest prediction for display purposes |
| | | 386 | | // For cancelled matches, use team-names-only lookup |
| | 1 | 387 | | if (match.IsCancelled) |
| | | 388 | | { |
| | 1 | 389 | | prediction = await predictionRepository!.GetCancelledMatchPredictionAsync( |
| | 1 | 390 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 391 | | } |
| | | 392 | | else |
| | | 393 | | { |
| | 1 | 394 | | prediction = await predictionRepository!.GetPredictionAsync(match, modelConfig, communit |
| | | 395 | | } |
| | | 396 | | |
| | 1 | 397 | | if (prediction != null) |
| | | 398 | | { |
| | 1 | 399 | | fromDatabase = true; |
| | 1 | 400 | | if (!settings.Agent) |
| | | 401 | | { |
| | 1 | 402 | | _console.MarkupLine($"[green] ✓ Latest prediction:[/] {prediction.HomeGoals}:{predi |
| | 1 | 403 | | WriteJustificationIfNeeded(prediction, settings.WithJustification, fromDatabase: tru |
| | | 404 | | } |
| | | 405 | | } |
| | | 406 | | } |
| | | 407 | | } |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | // If no existing prediction (normal mode) or we need to predict (reprediction mode), generate a new one |
| | 1 | 411 | | if (prediction == null || shouldPredict) |
| | | 412 | | { |
| | 1 | 413 | | _console.MarkupLine($"[yellow] → Generating new prediction...[/]"); |
| | | 414 | | |
| | | 415 | | // Step 3: Get context using hybrid approach (database first, fallback to on-demand) |
| | 1 | 416 | | var contextDocuments = await GetHybridContextAsync( |
| | 1 | 417 | | contextRepository, |
| | 1 | 418 | | contextProvider, |
| | 1 | 419 | | match.HomeTeam, |
| | 1 | 420 | | match.AwayTeam, |
| | 1 | 421 | | communityContext, |
| | 1 | 422 | | competition, |
| | 1 | 423 | | settings.Verbose); |
| | | 424 | | |
| | 1 | 425 | | if (settings.Verbose) |
| | | 426 | | { |
| | 1 | 427 | | _console.MarkupLine($"[dim] Using {contextDocuments.Count} context documents[/]"); |
| | | 428 | | } |
| | | 429 | | |
| | | 430 | | // Show context documents if requested |
| | 1 | 431 | | if (settings.ShowContextDocuments) |
| | | 432 | | { |
| | 1 | 433 | | _console.MarkupLine($"[cyan] Context documents for {match.HomeTeam} vs {match.AwayTeam}:[/]") |
| | 1 | 434 | | foreach (var doc in contextDocuments) |
| | | 435 | | { |
| | 1 | 436 | | _console.MarkupLine($"[dim] 📄 {doc.Name}[/]"); |
| | | 437 | | |
| | | 438 | | // Show first few lines and total line count for readability |
| | 1 | 439 | | var lines = doc.Content.Split('\n'); |
| | 1 | 440 | | var previewLines = lines.Take(10).ToArray(); |
| | 1 | 441 | | var hasMore = lines.Length > 10; |
| | | 442 | | |
| | 1 | 443 | | foreach (var line in previewLines) |
| | | 444 | | { |
| | 1 | 445 | | _console.MarkupLine($"[grey] {line.EscapeMarkup()}[/]"); |
| | | 446 | | } |
| | | 447 | | |
| | 1 | 448 | | if (hasMore) |
| | | 449 | | { |
| | 1 | 450 | | _console.MarkupLine($"[dim] ... ({lines.Length - 10} more lines) ...[/]"); |
| | | 451 | | } |
| | | 452 | | |
| | 1 | 453 | | _console.MarkupLine($"[dim] (Total: {lines.Length} lines, {doc.Content.Length} characte |
| | 1 | 454 | | _console.WriteLine(); |
| | | 455 | | } |
| | | 456 | | } |
| | | 457 | | |
| | 1 | 458 | | var telemetryMetadata = new PredictionTelemetryMetadata( |
| | 1 | 459 | | HomeTeam: match.HomeTeam, |
| | 1 | 460 | | AwayTeam: match.AwayTeam, |
| | 1 | 461 | | RepredictionIndex: predictionRepredictionIndex); |
| | | 462 | | |
| | | 463 | | // Predict the match |
| | 1 | 464 | | prediction = await predictionService.PredictMatchAsync(match, contextDocuments, settings.WithJustifi |
| | | 465 | | |
| | 1 | 466 | | if (prediction != null) |
| | | 467 | | { |
| | 1 | 468 | | if (predictionRepredictionIndex.HasValue) |
| | | 469 | | { |
| | 1 | 470 | | traceRepredictionIndices.Add(predictionRepredictionIndex.Value.ToString()); |
| | | 471 | | } |
| | | 472 | | |
| | 1 | 473 | | if (settings.Agent) |
| | | 474 | | { |
| | 1 | 475 | | _console.MarkupLine($"[green] ✓ Generated prediction[/]"); |
| | | 476 | | } |
| | | 477 | | else |
| | | 478 | | { |
| | 1 | 479 | | _console.MarkupLine($"[green] ✓ Generated prediction:[/] {prediction.HomeGoals}:{prediction |
| | 1 | 480 | | WriteJustificationIfNeeded(prediction, settings.WithJustification); |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | // Save to database immediately if enabled |
| | 1 | 484 | | if (databaseEnabled && !settings.DryRun) |
| | | 485 | | { |
| | | 486 | | try |
| | | 487 | | { |
| | | 488 | | // Get token usage and cost information |
| | 1 | 489 | | var cost = (double)tokenUsageTracker.GetLastCost(); // Get the cost for this individual |
| | | 490 | | // Use the new GetLastUsageJson method to get full JSON |
| | 1 | 491 | | var tokenUsageJson = tokenUsageTracker.GetLastUsageJson() ?? "{}"; |
| | | 492 | | |
| | 1 | 493 | | if (settings.IsRepredictMode) |
| | | 494 | | { |
| | | 495 | | // Save as reprediction with specific index |
| | | 496 | | // For cancelled matches, use team-names-only lookup for the current index |
| | | 497 | | int currentIndex; |
| | 1 | 498 | | if (match.IsCancelled) |
| | | 499 | | { |
| | 1 | 500 | | currentIndex = await predictionRepository!.GetCancelledMatchRepredictionIndexAsy |
| | 1 | 501 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 502 | | } |
| | | 503 | | else |
| | | 504 | | { |
| | 1 | 505 | | currentIndex = await predictionRepository!.GetMatchRepredictionIndexAsync(match, |
| | | 506 | | } |
| | 1 | 507 | | var nextIndex = currentIndex == -1 ? 0 : currentIndex + 1; |
| | | 508 | | |
| | 1 | 509 | | await predictionRepository!.SaveRepredictionAsync( |
| | 1 | 510 | | match, |
| | 1 | 511 | | prediction, |
| | 1 | 512 | | modelConfig, |
| | 1 | 513 | | tokenUsageJson, |
| | 1 | 514 | | cost, |
| | 1 | 515 | | communityContext, |
| | 0 | 516 | | contextDocuments.Select(d => d.Name), |
| | 1 | 517 | | nextIndex); |
| | | 518 | | |
| | 1 | 519 | | if (settings.Verbose) |
| | | 520 | | { |
| | 1 | 521 | | _console.MarkupLine($"[dim] ✓ Saved as reprediction {nextIndex} to database[/ |
| | | 522 | | } |
| | | 523 | | } |
| | | 524 | | else |
| | | 525 | | { |
| | | 526 | | // Save normally (override or new prediction) |
| | 1 | 527 | | await predictionRepository!.SavePredictionAsync( |
| | 1 | 528 | | match, |
| | 1 | 529 | | prediction, |
| | 1 | 530 | | modelConfig, |
| | 1 | 531 | | tokenUsageJson, |
| | 1 | 532 | | cost, |
| | 1 | 533 | | communityContext, |
| | 0 | 534 | | contextDocuments.Select(d => d.Name), |
| | 1 | 535 | | overrideCreatedAt: settings.OverrideDatabase); |
| | | 536 | | |
| | 1 | 537 | | if (settings.Verbose) |
| | | 538 | | { |
| | 1 | 539 | | _console.MarkupLine($"[dim] ✓ Saved to database[/]"); |
| | | 540 | | } |
| | | 541 | | } |
| | 1 | 542 | | } |
| | 1 | 543 | | catch (Exception ex) |
| | | 544 | | { |
| | 1 | 545 | | _logger.LogError(ex, "Failed to save prediction for match {Match}", match); |
| | 1 | 546 | | _console.MarkupLine($"[red] ✗ Failed to save to database: {ex.Message}[/]"); |
| | 1 | 547 | | } |
| | | 548 | | } |
| | 1 | 549 | | else if (databaseEnabled && settings.DryRun && settings.Verbose) |
| | | 550 | | { |
| | 1 | 551 | | _console.MarkupLine($"[dim] (Dry run - skipped database save)[/]"); |
| | | 552 | | } |
| | | 553 | | |
| | | 554 | | // Show individual match token usage in verbose mode |
| | 1 | 555 | | if (settings.Verbose) |
| | | 556 | | { |
| | 1 | 557 | | var matchUsage = !string.IsNullOrEmpty(settings.EstimatedCostsModel) |
| | 1 | 558 | | ? tokenUsageTracker.GetLastUsageCompactSummaryWithEstimatedCosts(settings.EstimatedCosts |
| | 1 | 559 | | : tokenUsageTracker.GetLastUsageCompactSummary(); |
| | 1 | 560 | | _console.MarkupLine($"[dim] Token usage: {matchUsage}[/]"); |
| | | 561 | | } |
| | | 562 | | } |
| | | 563 | | else |
| | | 564 | | { |
| | 1 | 565 | | _console.MarkupLine($"[red] ✗ Failed to generate prediction[/]"); |
| | 1 | 566 | | continue; |
| | | 567 | | } |
| | 1 | 568 | | } |
| | | 569 | | |
| | | 570 | | // Convert to BetPrediction for Kicktipp |
| | 1 | 571 | | var betPrediction = new BetPrediction(prediction.HomeGoals, prediction.AwayGoals); |
| | 1 | 572 | | predictions[match] = betPrediction; |
| | | 573 | | |
| | 1 | 574 | | if (!fromDatabase && settings.Verbose) |
| | | 575 | | { |
| | 1 | 576 | | _console.MarkupLine($"[dim] Already saved to database[/]"); |
| | | 577 | | } |
| | 1 | 578 | | } |
| | 1 | 579 | | catch (Exception ex) |
| | | 580 | | { |
| | 1 | 581 | | _logger.LogError(ex, "Error processing match {Match}", match); |
| | 1 | 582 | | _console.MarkupLine($"[red] ✗ Error processing match: {ex.Message}[/]"); |
| | 1 | 583 | | } |
| | 1 | 584 | | } |
| | | 585 | | |
| | 1 | 586 | | if (traceRepredictionIndices.Count > 0) |
| | | 587 | | { |
| | 1 | 588 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "repredictionIndices", PredictionTelemetryMetadata.Bu |
| | 1 | 589 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "hasRepredictions", traceRepredictionIndices.Any(inde |
| | | 590 | | } |
| | | 591 | | |
| | 1 | 592 | | if (!predictions.Any()) |
| | | 593 | | { |
| | 1 | 594 | | _console.MarkupLine("[yellow]No predictions available, nothing to place[/]"); |
| | 1 | 595 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(new { error = "No predictions available" |
| | 1 | 596 | | return; |
| | | 597 | | } |
| | | 598 | | |
| | | 599 | | // Set trace output with all predictions |
| | 1 | 600 | | var traceOutput = predictions.Select(p => new |
| | 1 | 601 | | { |
| | 1 | 602 | | match = $"{p.Key.HomeTeam} vs {p.Key.AwayTeam}", |
| | 1 | 603 | | prediction = $"{p.Value.HomeGoals}:{p.Value.AwayGoals}" |
| | 1 | 604 | | }).ToArray(); |
| | 1 | 605 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(traceOutput)); |
| | | 606 | | |
| | | 607 | | // Step 4: Place all predictions using PlaceBetsAsync |
| | 1 | 608 | | _console.MarkupLine($"[blue]Placing {predictions.Count} predictions to Kicktipp...[/]"); |
| | | 609 | | |
| | 1 | 610 | | if (settings.DryRun) |
| | | 611 | | { |
| | 1 | 612 | | _console.MarkupLine($"[magenta]✓ Dry run mode - would have placed {predictions.Count} predictions (no actual |
| | | 613 | | } |
| | | 614 | | else |
| | | 615 | | { |
| | 1 | 616 | | var success = await kicktippClient.PlaceBetsAsync(settings.Community, predictions, overrideBets: settings.Ov |
| | | 617 | | |
| | 1 | 618 | | if (success) |
| | | 619 | | { |
| | 1 | 620 | | _console.MarkupLine($"[green]✓ Successfully placed all {predictions.Count} predictions![/]"); |
| | | 621 | | } |
| | | 622 | | else |
| | | 623 | | { |
| | 1 | 624 | | _console.MarkupLine("[red]✗ Failed to place some or all predictions[/]"); |
| | | 625 | | } |
| | | 626 | | } |
| | | 627 | | |
| | | 628 | | // Display token usage summary |
| | 1 | 629 | | var summary = !string.IsNullOrEmpty(settings.EstimatedCostsModel) |
| | 1 | 630 | | ? tokenUsageTracker.GetCompactSummaryWithEstimatedCosts(settings.EstimatedCostsModel) |
| | 1 | 631 | | : tokenUsageTracker.GetCompactSummary(); |
| | 1 | 632 | | _console.MarkupLine($"[dim]Token usage (uncached/cached/reasoning/output/$cost): {summary}[/]"); |
| | 1 | 633 | | } |
| | | 634 | | |
| | | 635 | | /// <summary> |
| | | 636 | | /// Retrieves all available context documents from the database for the given community context. |
| | | 637 | | /// </summary> |
| | | 638 | | private async Task<Dictionary<string, DocumentContext>> GetMatchContextDocumentsAsync( |
| | | 639 | | IContextRepository contextRepository, |
| | | 640 | | string homeTeam, |
| | | 641 | | string awayTeam, |
| | | 642 | | string communityContext, |
| | | 643 | | string competition, |
| | | 644 | | bool verbose = false) |
| | | 645 | | { |
| | 1 | 646 | | var contextDocuments = new Dictionary<string, DocumentContext>(); |
| | 1 | 647 | | var selection = MatchContextDocumentCatalog.ForMatch(homeTeam, awayTeam, communityContext, competition); |
| | | 648 | | |
| | 1 | 649 | | if (verbose) |
| | | 650 | | { |
| | 1 | 651 | | _console.MarkupLine($"[dim] Looking for {selection.RequiredDocumentNames.Count} specific context document |
| | | 652 | | } |
| | | 653 | | |
| | | 654 | | try |
| | | 655 | | { |
| | | 656 | | // Retrieve each required document |
| | 1 | 657 | | foreach (var documentName in selection.RequiredDocumentNames) |
| | | 658 | | { |
| | 1 | 659 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContext); |
| | 1 | 660 | | if (contextDoc != null) |
| | | 661 | | { |
| | 1 | 662 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content); |
| | | 663 | | |
| | 1 | 664 | | if (verbose) |
| | | 665 | | { |
| | 1 | 666 | | _console.MarkupLine($"[dim] ✓ Retrieved {documentName} (version {contextDoc.Version})[/]"); |
| | | 667 | | } |
| | | 668 | | } |
| | | 669 | | else |
| | | 670 | | { |
| | 1 | 671 | | if (verbose) |
| | | 672 | | { |
| | 1 | 673 | | _console.MarkupLine($"[dim] ✗ Missing {documentName}[/]"); |
| | | 674 | | } |
| | | 675 | | } |
| | 1 | 676 | | } |
| | | 677 | | |
| | | 678 | | // Retrieve optional transfers documents (best-effort) |
| | 1 | 679 | | foreach (var documentName in selection.OptionalDocumentNames) |
| | | 680 | | { |
| | | 681 | | try |
| | | 682 | | { |
| | 1 | 683 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContex |
| | 1 | 684 | | if (contextDoc != null) |
| | | 685 | | { |
| | | 686 | | // Display name suffix to distinguish optional docs in prediction metadata (helps debug) |
| | 1 | 687 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content |
| | 1 | 688 | | if (verbose) |
| | | 689 | | { |
| | 1 | 690 | | _console.MarkupLine($"[dim] ✓ Retrieved optional {documentName} (version {contextDoc.Ve |
| | | 691 | | } |
| | | 692 | | } |
| | 1 | 693 | | else if (verbose) |
| | | 694 | | { |
| | 1 | 695 | | _console.MarkupLine($"[dim] · Missing optional {documentName}[/]"); |
| | | 696 | | } |
| | 1 | 697 | | } |
| | 1 | 698 | | catch (Exception optEx) |
| | | 699 | | { |
| | 1 | 700 | | if (verbose) |
| | | 701 | | { |
| | 1 | 702 | | _console.MarkupLine($"[dim] · Failed optional {documentName}: {optEx.Message}[/]"); |
| | | 703 | | } |
| | 1 | 704 | | } |
| | 1 | 705 | | } |
| | 1 | 706 | | } |
| | 1 | 707 | | catch (Exception ex) |
| | | 708 | | { |
| | 1 | 709 | | _console.MarkupLine($"[red] Warning: Failed to retrieve context from database: {ex.Message}[/]"); |
| | 1 | 710 | | } |
| | | 711 | | |
| | 1 | 712 | | return contextDocuments; |
| | 1 | 713 | | } |
| | | 714 | | |
| | | 715 | | /// <summary> |
| | | 716 | | /// Gets context documents using database first, falling back to on-demand context provider if needed. |
| | | 717 | | /// </summary> |
| | | 718 | | private async Task<List<DocumentContext>> GetHybridContextAsync( |
| | | 719 | | IContextRepository contextRepository, |
| | | 720 | | IKicktippContextProvider contextProvider, |
| | | 721 | | string homeTeam, |
| | | 722 | | string awayTeam, |
| | | 723 | | string communityContext, |
| | | 724 | | string competition, |
| | | 725 | | bool verbose = false) |
| | | 726 | | { |
| | 1 | 727 | | var contextDocuments = new List<DocumentContext>(); |
| | | 728 | | // Step 1: Retrieve any database documents (required + optional) |
| | 1 | 729 | | var databaseContexts = await GetMatchContextDocumentsAsync( |
| | 1 | 730 | | contextRepository, |
| | 1 | 731 | | homeTeam, |
| | 1 | 732 | | awayTeam, |
| | 1 | 733 | | communityContext, |
| | 1 | 734 | | competition, |
| | 1 | 735 | | verbose); |
| | | 736 | | |
| | 1 | 737 | | var requiredDocuments = MatchContextDocumentCatalog |
| | 1 | 738 | | .ForMatch(homeTeam, awayTeam, communityContext, competition) |
| | 1 | 739 | | .RequiredDocumentNames; |
| | | 740 | | |
| | 1 | 741 | | int requiredPresent = requiredDocuments.Count(d => databaseContexts.ContainsKey(d)); |
| | 1 | 742 | | int requiredTotal = requiredDocuments.Count; |
| | | 743 | | |
| | 1 | 744 | | if (requiredPresent == requiredTotal) |
| | | 745 | | { |
| | | 746 | | // All required docs present; include every database doc (required + optional) |
| | 1 | 747 | | if (verbose) |
| | | 748 | | { |
| | 1 | 749 | | _console.MarkupLine($"[green] Using {databaseContexts.Count} context documents from database (all req |
| | | 750 | | } |
| | 1 | 751 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 752 | | } |
| | | 753 | | else |
| | | 754 | | { |
| | | 755 | | // Fallback: use on-demand provider but still include any database docs we already have (including optional |
| | 1 | 756 | | _console.MarkupLine($"[yellow] Warning: Only found {requiredPresent}/{requiredTotal} required context doc |
| | | 757 | | |
| | | 758 | | // Start with database docs |
| | 1 | 759 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 760 | | |
| | | 761 | | // Add on-demand docs, skipping duplicates by name |
| | 1 | 762 | | var existingNames = new HashSet<string>(contextDocuments.Select(c => c.Name), StringComparer.OrdinalIgnoreCa |
| | 1 | 763 | | await foreach (var context in contextProvider.GetMatchContextAsync(homeTeam, awayTeam)) |
| | | 764 | | { |
| | 1 | 765 | | if (existingNames.Add(context.Name)) |
| | | 766 | | { |
| | 1 | 767 | | contextDocuments.Add(context); |
| | | 768 | | } |
| | | 769 | | } |
| | | 770 | | |
| | 1 | 771 | | if (verbose) |
| | | 772 | | { |
| | 1 | 773 | | _console.MarkupLine($"[yellow] Using {contextDocuments.Count} merged context documents (database + on |
| | | 774 | | } |
| | 1 | 775 | | } |
| | | 776 | | |
| | 1 | 777 | | if (CompetitionResolver.IsWorldCupCompetition(competition)) |
| | | 778 | | { |
| | 1 | 779 | | EnsureWorldCupRequiredContextPresent(contextDocuments, requiredDocuments); |
| | | 780 | | } |
| | | 781 | | |
| | 1 | 782 | | return contextDocuments; |
| | 1 | 783 | | } |
| | | 784 | | |
| | | 785 | | private static void EnsureWorldCupRequiredContextPresent( |
| | | 786 | | IReadOnlyList<DocumentContext> contextDocuments, |
| | | 787 | | IReadOnlyList<string> requiredDocuments) |
| | | 788 | | { |
| | 1 | 789 | | var presentDocumentNames = new HashSet<string>( |
| | 1 | 790 | | contextDocuments.Select(document => document.Name), |
| | 1 | 791 | | StringComparer.OrdinalIgnoreCase); |
| | 1 | 792 | | var missingDocumentNames = requiredDocuments |
| | 1 | 793 | | .Where(documentName => !presentDocumentNames.Contains(documentName)) |
| | 1 | 794 | | .ToList(); |
| | | 795 | | |
| | 1 | 796 | | if (missingDocumentNames.Count == 0) |
| | | 797 | | { |
| | 1 | 798 | | return; |
| | | 799 | | } |
| | | 800 | | |
| | 1 | 801 | | throw new InvalidOperationException( |
| | 1 | 802 | | "Missing required WM26 context documents after database and on-demand fallback: " + |
| | 1 | 803 | | $"{string.Join(", ", missingDocumentNames)}. Seed FIFA rankings with collect-context fifa and lineups with c |
| | | 804 | | } |
| | | 805 | | |
| | | 806 | | private async Task<bool> CheckPredictionOutdated(IPredictionRepository predictionRepository, IContextRepository cont |
| | | 807 | | { |
| | | 808 | | try |
| | | 809 | | { |
| | | 810 | | // Get prediction metadata with context document names and timestamps |
| | | 811 | | // For cancelled matches, use team-names-only lookup to handle startsAt inconsistencies |
| | | 812 | | PredictionMetadata? predictionMetadata; |
| | 1 | 813 | | if (match.IsCancelled) |
| | | 814 | | { |
| | 1 | 815 | | predictionMetadata = await predictionRepository.GetCancelledMatchPredictionMetadataAsync( |
| | 1 | 816 | | match.HomeTeam, match.AwayTeam, modelConfig, communityContext); |
| | | 817 | | } |
| | | 818 | | else |
| | | 819 | | { |
| | 1 | 820 | | predictionMetadata = await predictionRepository.GetPredictionMetadataAsync(match, modelConfig, community |
| | | 821 | | } |
| | | 822 | | |
| | 1 | 823 | | if (predictionMetadata == null || !predictionMetadata.ContextDocumentNames.Any()) |
| | | 824 | | { |
| | | 825 | | // If no context documents were used, prediction can't be outdated based on context changes |
| | 1 | 826 | | return false; |
| | | 827 | | } |
| | | 828 | | |
| | 1 | 829 | | if (verbose) |
| | | 830 | | { |
| | 1 | 831 | | _console.MarkupLine($"[dim] Checking {predictionMetadata.ContextDocumentNames.Count} context documents |
| | | 832 | | } |
| | | 833 | | |
| | | 834 | | // Check if any context document has been updated after the prediction was created |
| | 1 | 835 | | foreach (var documentName in predictionMetadata.ContextDocumentNames) |
| | | 836 | | { |
| | | 837 | | // Strip any display suffix (e.g., " (kpi-context)") from the context document name |
| | | 838 | | // to get the actual document name stored in the repository |
| | 1 | 839 | | var actualDocumentName = StripDisplaySuffix(documentName); |
| | | 840 | | |
| | 1 | 841 | | var standingsDocumentName = MatchContextDocumentCatalog.GetStandingsDocumentName(competition); |
| | 1 | 842 | | if (actualDocumentName.Equals(standingsDocumentName, StringComparison.OrdinalIgnoreCase)) |
| | | 843 | | { |
| | 1 | 844 | | if (verbose) |
| | | 845 | | { |
| | 1 | 846 | | _console.MarkupLine($"[dim] Skipping outdated check for '{actualDocumentName}' (excluded from c |
| | | 847 | | } |
| | 1 | 848 | | continue; |
| | | 849 | | } |
| | | 850 | | |
| | 1 | 851 | | var latestContextDocument = await contextRepository.GetLatestContextDocumentAsync(actualDocumentName, co |
| | | 852 | | |
| | 1 | 853 | | if (latestContextDocument != null && latestContextDocument.CreatedAt > predictionMetadata.CreatedAt) |
| | | 854 | | { |
| | 1 | 855 | | var predictionTimeContextDocument = await contextRepository.GetContextDocumentByTimestampAsync( |
| | 1 | 856 | | actualDocumentName, |
| | 1 | 857 | | predictionMetadata.CreatedAt, |
| | 1 | 858 | | communityContext); |
| | | 859 | | |
| | 1 | 860 | | if (predictionTimeContextDocument != null && |
| | 1 | 861 | | string.Equals( |
| | 1 | 862 | | predictionTimeContextDocument.Content, |
| | 1 | 863 | | latestContextDocument.Content, |
| | 1 | 864 | | StringComparison.Ordinal)) |
| | | 865 | | { |
| | 1 | 866 | | if (verbose) |
| | | 867 | | { |
| | 1 | 868 | | _console.MarkupLine( |
| | 1 | 869 | | $"[dim] Context document '{actualDocumentName}' has newer versions after the prediction |
| | | 870 | | } |
| | | 871 | | |
| | 1 | 872 | | continue; |
| | | 873 | | } |
| | | 874 | | |
| | 1 | 875 | | if (verbose) |
| | | 876 | | { |
| | 1 | 877 | | _console.MarkupLine($"[dim] Context document '{actualDocumentName}' (stored as '{documentName}' |
| | | 878 | | } |
| | 1 | 879 | | return true; // Prediction is outdated |
| | | 880 | | } |
| | 1 | 881 | | else if (verbose && latestContextDocument == null) |
| | | 882 | | { |
| | 1 | 883 | | _console.MarkupLine($"[yellow] Warning: Context document '{actualDocumentName}' not found in reposi |
| | | 884 | | } |
| | 1 | 885 | | } |
| | | 886 | | |
| | 1 | 887 | | return false; // Prediction is up-to-date |
| | | 888 | | } |
| | 1 | 889 | | catch (Exception ex) |
| | | 890 | | { |
| | | 891 | | // Log error but don't fail verification due to outdated check issues |
| | 1 | 892 | | if (verbose) |
| | | 893 | | { |
| | 1 | 894 | | _console.MarkupLine($"[yellow] Warning: Failed to check outdated status: {ex.Message}[/]"); |
| | | 895 | | } |
| | 1 | 896 | | return false; |
| | | 897 | | } |
| | 1 | 898 | | } |
| | | 899 | | |
| | | 900 | | private void WriteJustificationIfNeeded(Prediction? prediction, bool includeJustification, bool fromDatabase = false |
| | | 901 | | { |
| | 1 | 902 | | if (!includeJustification || prediction == null) |
| | | 903 | | { |
| | 1 | 904 | | return; |
| | | 905 | | } |
| | | 906 | | |
| | 1 | 907 | | var sourceLabel = fromDatabase ? "stored prediction" : "model response"; |
| | | 908 | | |
| | 1 | 909 | | var justificationWriter = new JustificationConsoleWriter(_console); |
| | 1 | 910 | | justificationWriter.WriteJustification( |
| | 1 | 911 | | prediction.Justification, |
| | 1 | 912 | | "[dim] ↳ Justification:[/]", |
| | 1 | 913 | | " ", |
| | 1 | 914 | | $"[yellow] ↳ No justification available for this {sourceLabel}[/]"); |
| | 1 | 915 | | } |
| | | 916 | | |
| | | 917 | | /// <summary> |
| | | 918 | | /// Strips display suffixes like " (kpi-context)" from context document names |
| | | 919 | | /// to get the actual document name used in the repository. |
| | | 920 | | /// </summary> |
| | | 921 | | /// <param name="displayName">The display name that may contain a suffix</param> |
| | | 922 | | /// <returns>The actual document name without any display suffix</returns> |
| | | 923 | | private static string StripDisplaySuffix(string displayName) |
| | | 924 | | { |
| | | 925 | | // Look for patterns like " (some-text)" at the end and remove them |
| | 1 | 926 | | var lastParenIndex = displayName.LastIndexOf(" ("); |
| | 1 | 927 | | if (lastParenIndex > 0 && displayName.EndsWith(")")) |
| | | 928 | | { |
| | 1 | 929 | | return displayName.Substring(0, lastParenIndex); |
| | | 930 | | } |
| | 1 | 931 | | return displayName; |
| | | 932 | | } |
| | | 933 | | } |