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