| | | 1 | | using System.Globalization; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Spectre.Console.Cli; |
| | | 4 | | using Spectre.Console; |
| | | 5 | | using EHonda.KicktippAi.Core; |
| | | 6 | | using Orchestrator.Infrastructure; |
| | | 7 | | using Orchestrator.Infrastructure.Factories; |
| | | 8 | | using Orchestrator.Services; |
| | | 9 | | |
| | | 10 | | namespace Orchestrator.Commands.Operations.CollectContext; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Command for collecting Kicktipp context documents and storing them in the database. |
| | | 14 | | /// </summary> |
| | | 15 | | public class CollectContextKicktippCommand : AsyncCommand<CollectContextKicktippSettings> |
| | | 16 | | { |
| | | 17 | | private readonly IAnsiConsole _console; |
| | | 18 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 19 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 20 | | private readonly IContextProviderFactory _contextProviderFactory; |
| | | 21 | | private readonly MatchOutcomeCollectionService _matchOutcomeCollectionService; |
| | | 22 | | private readonly TimeProvider _timeProvider; |
| | | 23 | | private readonly ILogger<CollectContextKicktippCommand> _logger; |
| | | 24 | | |
| | 1 | 25 | | public CollectContextKicktippCommand( |
| | 1 | 26 | | IAnsiConsole console, |
| | 1 | 27 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 28 | | IKicktippClientFactory kicktippClientFactory, |
| | 1 | 29 | | IContextProviderFactory contextProviderFactory, |
| | 1 | 30 | | MatchOutcomeCollectionService matchOutcomeCollectionService, |
| | 1 | 31 | | TimeProvider timeProvider, |
| | 1 | 32 | | ILogger<CollectContextKicktippCommand> logger) |
| | | 33 | | { |
| | 1 | 34 | | _console = console; |
| | 1 | 35 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 36 | | _kicktippClientFactory = kicktippClientFactory; |
| | 1 | 37 | | _contextProviderFactory = contextProviderFactory; |
| | 1 | 38 | | _matchOutcomeCollectionService = matchOutcomeCollectionService; |
| | 1 | 39 | | _timeProvider = timeProvider; |
| | 1 | 40 | | _logger = logger; |
| | 1 | 41 | | } |
| | | 42 | | |
| | | 43 | | protected override async Task<int> ExecuteAsync(CommandContext context, CollectContextKicktippSettings settings, Can |
| | | 44 | | { |
| | 1 | 45 | | return await ExecuteWithSettingsAsync(settings, cancellationToken); |
| | 1 | 46 | | } |
| | | 47 | | |
| | | 48 | | internal async Task<int> ExecuteWithSettingsAsync(CollectContextKicktippSettings settings, CancellationToken cancell |
| | | 49 | | { |
| | | 50 | | try |
| | | 51 | | { |
| | | 52 | | // Validate settings |
| | 1 | 53 | | if (string.IsNullOrWhiteSpace(settings.CommunityContext)) |
| | | 54 | | { |
| | 1 | 55 | | _console.MarkupLine("[red]Error: Community context is required[/]"); |
| | 1 | 56 | | return 1; |
| | | 57 | | } |
| | | 58 | | |
| | 1 | 59 | | _console.MarkupLine($"[green]Collect-context kicktipp command initialized[/]"); |
| | | 60 | | |
| | 1 | 61 | | if (settings.Verbose) |
| | | 62 | | { |
| | 1 | 63 | | _console.MarkupLine("[dim]Verbose mode enabled[/]"); |
| | | 64 | | } |
| | | 65 | | |
| | 1 | 66 | | if (settings.DryRun) |
| | | 67 | | { |
| | 1 | 68 | | _console.MarkupLine("[magenta]Dry run mode enabled - no changes will be made to database[/]"); |
| | | 69 | | } |
| | | 70 | | |
| | 1 | 71 | | if (settings.MatchOutcomesOnly) |
| | | 72 | | { |
| | 0 | 73 | | _console.MarkupLine("[blue]Match outcomes only mode enabled - context documents will not be updated[/]") |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | // Execute the context collection workflow |
| | 1 | 77 | | await ExecuteKicktippContextCollection(settings, cancellationToken); |
| | | 78 | | |
| | 1 | 79 | | return 0; |
| | | 80 | | } |
| | 1 | 81 | | catch (Exception ex) |
| | | 82 | | { |
| | 1 | 83 | | _logger.LogError(ex, "Error executing collect-context kicktipp command"); |
| | 1 | 84 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 1 | 85 | | return 1; |
| | | 86 | | } |
| | 1 | 87 | | } |
| | | 88 | | |
| | | 89 | | private async Task ExecuteKicktippContextCollection(CollectContextKicktippSettings settings, CancellationToken cance |
| | | 90 | | { |
| | 1 | 91 | | var competition = CompetitionResolver.ResolveCompetition(settings.Competition, settings.CommunityContext, settin |
| | 1 | 92 | | var repositoryCompetition = CompetitionResolver.ToRepositoryCompetitionArgument(competition); |
| | | 93 | | |
| | 1 | 94 | | var outcomeCollectionResult = await _matchOutcomeCollectionService.CollectAsync( |
| | 1 | 95 | | settings.CommunityContext, |
| | 1 | 96 | | settings.DryRun, |
| | 1 | 97 | | repositoryCompetition, |
| | 1 | 98 | | cancellationToken); |
| | | 99 | | |
| | 1 | 100 | | PrintOutcomeCollectionSummary(outcomeCollectionResult, settings); |
| | | 101 | | |
| | 1 | 102 | | if (settings.MatchOutcomesOnly) |
| | | 103 | | { |
| | 0 | 104 | | var completionMessage = settings.DryRun |
| | 0 | 105 | | ? "[magenta]✓ Match outcome dry run completed[/]" |
| | 0 | 106 | | : "[green]✓ Match outcome collection completed![/]"; |
| | 0 | 107 | | _console.MarkupLine(completionMessage); |
| | 0 | 108 | | return; |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | // Create services using factories (factories handle env var loading) |
| | 1 | 112 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | 1 | 113 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(repositoryCompetition); |
| | | 114 | | |
| | 1 | 115 | | _console.MarkupLine($"[blue]Using community context:[/] [yellow]{settings.CommunityContext}[/]"); |
| | 1 | 116 | | _console.MarkupLine($"[blue]Using competition:[/] [yellow]{competition}[/]"); |
| | | 117 | | |
| | 1 | 118 | | var requestedMatchdays = ParseMatchdays(settings.Matchdays); |
| | 1 | 119 | | var targetMatchdays = requestedMatchdays.Count > 0 |
| | 1 | 120 | | ? requestedMatchdays.Select<int, int?>(matchday => matchday).ToList() |
| | 1 | 121 | | : new List<int?> { null }; |
| | | 122 | | |
| | | 123 | | // Collect all unique context documents for all matches |
| | 1 | 124 | | var allContextDocuments = new Dictionary<string, string>(); // documentName -> content |
| | | 125 | | |
| | 1 | 126 | | foreach (var targetMatchday in targetMatchdays) |
| | | 127 | | { |
| | 1 | 128 | | var matchdayLabel = targetMatchday.HasValue ? $"matchday {targetMatchday.Value}" : "current matchday"; |
| | | 129 | | |
| | | 130 | | // Create context provider using factory |
| | 1 | 131 | | var contextProvider = _contextProviderFactory.CreateKicktippContextProvider( |
| | 1 | 132 | | kicktippClient, |
| | 1 | 133 | | settings.CommunityContext, |
| | 1 | 134 | | settings.CommunityContext, |
| | 1 | 135 | | repositoryCompetition, |
| | 1 | 136 | | targetMatchday); |
| | | 137 | | |
| | 1 | 138 | | _console.MarkupLine($"[blue]Getting {matchdayLabel} matches...[/]"); |
| | | 139 | | |
| | | 140 | | // Step 1: Get target matchday matches |
| | 1 | 141 | | var matchesWithHistory = targetMatchday.HasValue |
| | 1 | 142 | | ? await kicktippClient.GetMatchesWithHistoryAsync(settings.CommunityContext, targetMatchday.Value) |
| | 1 | 143 | | : await kicktippClient.GetMatchesWithHistoryAsync(settings.CommunityContext); |
| | | 144 | | |
| | 1 | 145 | | if (!matchesWithHistory.Any()) |
| | | 146 | | { |
| | 1 | 147 | | _console.MarkupLine($"[yellow]No matches found for {matchdayLabel}[/]"); |
| | 1 | 148 | | continue; |
| | | 149 | | } |
| | | 150 | | |
| | 1 | 151 | | _console.MarkupLine($"[green]Found {matchesWithHistory.Count} matches for {matchdayLabel}[/]"); |
| | | 152 | | |
| | | 153 | | // Step 2: Collect all unique context documents for all matches |
| | 1 | 154 | | foreach (var matchWithHistory in matchesWithHistory) |
| | | 155 | | { |
| | 1 | 156 | | var match = matchWithHistory.Match; |
| | 1 | 157 | | _console.MarkupLine($"[cyan]Collecting context for:[/] {match.HomeTeam} vs {match.AwayTeam}"); |
| | | 158 | | |
| | | 159 | | try |
| | | 160 | | { |
| | | 161 | | // Get context for this specific match |
| | 1 | 162 | | await foreach (var contextDoc in contextProvider.GetMatchContextAsync(match.HomeTeam, match.AwayTeam |
| | | 163 | | { |
| | | 164 | | // Use the document name as key to avoid duplicates |
| | 1 | 165 | | if (!allContextDocuments.ContainsKey(contextDoc.Name)) |
| | | 166 | | { |
| | 1 | 167 | | allContextDocuments[contextDoc.Name] = contextDoc.Content; |
| | | 168 | | |
| | 1 | 169 | | if (settings.Verbose) |
| | | 170 | | { |
| | 1 | 171 | | _console.MarkupLine($"[dim] Collected context document: {contextDoc.Name}[/]"); |
| | | 172 | | } |
| | | 173 | | } |
| | | 174 | | } |
| | 1 | 175 | | } |
| | 1 | 176 | | catch (Exception ex) |
| | | 177 | | { |
| | 1 | 178 | | _logger.LogError(ex, "Failed to collect context for match {HomeTeam} vs {AwayTeam}", match.HomeTeam, |
| | 1 | 179 | | _console.MarkupLine($"[red] ✗ Failed to collect context: {ex.Message}[/]"); |
| | 1 | 180 | | } |
| | 1 | 181 | | } |
| | 1 | 182 | | } |
| | | 183 | | |
| | 1 | 184 | | if (!allContextDocuments.Any()) |
| | | 185 | | { |
| | 1 | 186 | | return; |
| | | 187 | | } |
| | | 188 | | |
| | 1 | 189 | | _console.MarkupLine($"[green]Collected {allContextDocuments.Count} unique context documents[/]"); |
| | | 190 | | |
| | | 191 | | // Step 3: Save context documents to database |
| | 1 | 192 | | var savedCount = 0; |
| | 1 | 193 | | var skippedCount = 0; |
| | 1 | 194 | | var currentDate = DateOnly.FromDateTime(_timeProvider.GetLocalNow().DateTime) |
| | 1 | 195 | | .ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); |
| | | 196 | | |
| | 1 | 197 | | foreach (var (documentName, content) in allContextDocuments) |
| | | 198 | | { |
| | | 199 | | try |
| | | 200 | | { |
| | 1 | 201 | | if (settings.DryRun) |
| | | 202 | | { |
| | 1 | 203 | | _console.MarkupLine($"[magenta] Dry run - would save:[/] {documentName}"); |
| | 1 | 204 | | continue; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // Check if this is a history document that needs Data_Collected_At column |
| | 1 | 208 | | string finalContent = content; |
| | 1 | 209 | | if (IsHistoryDocument(documentName)) |
| | | 210 | | { |
| | | 211 | | // Get the previous version to compare against |
| | 1 | 212 | | var previousDocument = await contextRepository.GetLatestContextDocumentAsync(documentName, settings. |
| | 1 | 213 | | var previousContent = previousDocument?.Content; |
| | | 214 | | |
| | | 215 | | // Add Data_Collected_At column with current date for new matches |
| | 1 | 216 | | finalContent = HistoryCsvUtility.AddDataCollectedAtColumn(content, previousContent, currentDate); |
| | | 217 | | |
| | 1 | 218 | | if (settings.Verbose) |
| | | 219 | | { |
| | 1 | 220 | | _console.MarkupLine($"[dim] Added Data_Collected_At column to {documentName}[/]"); |
| | | 221 | | } |
| | | 222 | | } |
| | | 223 | | |
| | 1 | 224 | | var savedVersion = await contextRepository.SaveContextDocumentAsync( |
| | 1 | 225 | | documentName, |
| | 1 | 226 | | finalContent, |
| | 1 | 227 | | settings.CommunityContext); |
| | | 228 | | |
| | 1 | 229 | | if (savedVersion.HasValue) |
| | | 230 | | { |
| | 1 | 231 | | savedCount++; |
| | 1 | 232 | | if (settings.Verbose) |
| | | 233 | | { |
| | 1 | 234 | | _console.MarkupLine($"[green] ✓ Saved {documentName} as version {savedVersion.Value}[/]"); |
| | | 235 | | } |
| | | 236 | | } |
| | | 237 | | else |
| | | 238 | | { |
| | 1 | 239 | | skippedCount++; |
| | 1 | 240 | | if (settings.Verbose) |
| | | 241 | | { |
| | 1 | 242 | | _console.MarkupLine($"[dim] - Skipped {documentName} (content unchanged)[/]"); |
| | | 243 | | } |
| | | 244 | | } |
| | 1 | 245 | | } |
| | 1 | 246 | | catch (Exception ex) |
| | | 247 | | { |
| | 1 | 248 | | _logger.LogError(ex, "Failed to save context document {DocumentName}", documentName); |
| | 1 | 249 | | _console.MarkupLine($"[red] ✗ Failed to save {documentName}: {ex.Message}[/]"); |
| | 1 | 250 | | } |
| | 1 | 251 | | } |
| | | 252 | | |
| | 1 | 253 | | if (settings.DryRun) |
| | | 254 | | { |
| | 1 | 255 | | _console.MarkupLine($"[magenta]✓ Dry run completed - would have processed {allContextDocuments.Count} docume |
| | | 256 | | } |
| | | 257 | | else |
| | | 258 | | { |
| | 1 | 259 | | _console.MarkupLine($"[green]✓ Context collection completed![/]"); |
| | 1 | 260 | | _console.MarkupLine($"[green] Saved: {savedCount} documents[/]"); |
| | 1 | 261 | | _console.MarkupLine($"[dim] Skipped: {skippedCount} documents (unchanged)[/]"); |
| | | 262 | | } |
| | 1 | 263 | | } |
| | | 264 | | |
| | | 265 | | private static bool IsHistoryDocument(string documentName) |
| | | 266 | | { |
| | 1 | 267 | | return documentName.StartsWith("recent-history-", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 268 | | documentName.StartsWith("home-history-", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 269 | | documentName.StartsWith("away-history-", StringComparison.OrdinalIgnoreCase); |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | private static IReadOnlyList<int> ParseMatchdays(string? matchdays) |
| | | 273 | | { |
| | 1 | 274 | | if (string.IsNullOrWhiteSpace(matchdays)) |
| | | 275 | | { |
| | 1 | 276 | | return []; |
| | | 277 | | } |
| | | 278 | | |
| | 1 | 279 | | var result = new List<int>(); |
| | 1 | 280 | | foreach (var token in matchdays.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie |
| | | 281 | | { |
| | 1 | 282 | | if (!int.TryParse(token, out var matchday) || matchday <= 0) |
| | | 283 | | { |
| | 0 | 284 | | throw new ArgumentException($"Invalid matchday '{token}'. Use positive integers separated by commas."); |
| | | 285 | | } |
| | | 286 | | |
| | 1 | 287 | | if (!result.Contains(matchday)) |
| | | 288 | | { |
| | 1 | 289 | | result.Add(matchday); |
| | | 290 | | } |
| | | 291 | | } |
| | | 292 | | |
| | 1 | 293 | | return result; |
| | | 294 | | } |
| | | 295 | | |
| | | 296 | | private void PrintOutcomeCollectionSummary(MatchOutcomeCollectionResult result, CollectContextKicktippSettings setti |
| | | 297 | | { |
| | 1 | 298 | | _console.MarkupLine($"[blue]Current tippuebersicht matchday:[/] [yellow]{result.CurrentMatchday}[/]"); |
| | | 299 | | |
| | 1 | 300 | | if (!result.IncompleteMatchdays.Any()) |
| | | 301 | | { |
| | 1 | 302 | | _console.MarkupLine("[green]All persisted matchdays up to the current matchday are already complete[/]"); |
| | 1 | 303 | | return; |
| | | 304 | | } |
| | | 305 | | |
| | 0 | 306 | | _console.MarkupLine($"[blue]Incomplete matchdays to check:[/] [yellow]{string.Join(", ", result.IncompleteMatchd |
| | | 307 | | |
| | 0 | 308 | | foreach (var summary in result.MatchdaySummaries) |
| | | 309 | | { |
| | 0 | 310 | | if (settings.DryRun) |
| | | 311 | | { |
| | 0 | 312 | | _console.MarkupLine( |
| | 0 | 313 | | $"[magenta] Dry run - would evaluate matchday {summary.Matchday}[/] " + |
| | 0 | 314 | | $"({summary.FetchedMatches} matches, {summary.CompletedMatches} completed, {summary.PendingMatches} |
| | 0 | 315 | | continue; |
| | | 316 | | } |
| | | 317 | | |
| | 0 | 318 | | _console.MarkupLine( |
| | 0 | 319 | | $"[green] Matchday {summary.Matchday}:[/] {summary.FetchedMatches} matches, " + |
| | 0 | 320 | | $"created {summary.CreatedCount}, updated {summary.UpdatedCount}, unchanged {summary.UnchangedCount}, " |
| | 0 | 321 | | $"pending {summary.PendingMatches}"); |
| | | 322 | | } |
| | 0 | 323 | | } |
| | | 324 | | } |