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