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