namespace SOR.Ai.Handlers; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using SOR.Ai.Lobby; using SOR.Ai.Seeding; using SOR.Database.Contexts; using SOR.Database.Entities.Game; using SOR.Database.Enums; using SOR.Game; using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Transport; using SOR.Shared.Nats; using SOR.Shared.Networking; /// /// game.ai.create_match — creates a spectatable AI-vs-AI match and returns the session ID. /// /// Flow: /// 1. Validate difficulty (1–10) and strategy for each side. /// 2. Resolve AI account IDs (deterministic from AiAccountSeeder.AccountId). /// 3. Resolve decks via AiDeckResolver. /// 4. Build a minimal CustomLobby with AiSlotsJson so AiPlayerSessionManager can /// read difficulty/strategy when GameStartedEvent arrives. /// 5. Create GameSession, link to lobby, publish GameStartedEvent. /// 6. Return { sessionId, player1Name, player2Name } — client sends game.spectate. /// internal sealed class GameAiMatchHandler : IMessageHandler { private readonly IMessageSerializer _serializer; private readonly GameDbContext _gameDb; private readonly SorIdentityDbContext _identityDb; private readonly AiDeckResolver _deckResolver; private readonly IEventBus _eventBus; private readonly ILogger _logger; public GameAiMatchHandler( IMessageSerializer serializer, GameDbContext gameDb, SorIdentityDbContext identityDb, AiDeckResolver deckResolver, IEventBus eventBus, ILogger logger) { _serializer = serializer; _gameDb = gameDb; _identityDb = identityDb; _deckResolver = deckResolver; _eventBus = eventBus; _logger = logger; } public string MessageType => "game.ai.create_match"; public async Task HandleAsync( IClientMessage message, AuthenticatedConnection connection, CancellationToken ct) { var req = _serializer.DeserializePayload(message.Payload); // ── Validate ────────────────────────────────────────────────────────── if (req.Difficulty1 is < 1 or > 10 || req.Difficulty2 is < 1 or > 10) throw new GameException("INVALID_DIFFICULTY"); if (!AiAccountSeeder.Strategies.Contains(req.Strategy1) || !AiAccountSeeder.Strategies.Contains(req.Strategy2)) throw new GameException("INVALID_STRATEGY"); // ── Resolve account IDs ─────────────────────────────────────────────── var id1 = AiAccountSeeder.AccountId(req.Difficulty1, req.Strategy1); var id2 = AiAccountSeeder.AccountId(req.Difficulty2, req.Strategy2); // ── Resolve decks ───────────────────────────────────────────────────── var deckId1 = await _deckResolver.ResolveAsync(id1, req.Difficulty1, ct); var deckId2 = await _deckResolver.ResolveAsync(id2, req.Difficulty2, ct); // ── Build AI slot metadata (for AiPlayerSessionManager) ─────────────── var aiSlots = JsonSerializer.Serialize(new[] { new { AccountId = id1, SeatIndex = 0, Difficulty = req.Difficulty1, Strategy = req.Strategy1 }, new { AccountId = id2, SeatIndex = 1, Difficulty = req.Difficulty2, Strategy = req.Strategy2 }, }); // ── Create minimal CustomLobby ──────────────────────────────────────── // Status = Started so the lobby doesn't appear in open-lobby lists. // Both AIs are immediately "ready", so HostReady/GuestReady = true. var lobby = new CustomLobby { Name = $"AI Match: {AiAccountSeeder.DisplayName(req.Difficulty1, req.Strategy1)} vs {AiAccountSeeder.DisplayName(req.Difficulty2, req.Strategy2)}", HostAccountId = id1, HostDeckId = deckId1, GuestAccountId = id2, GuestDeckId = deckId2, HostReady = true, GuestReady = true, Status = CustomLobbyStatus.Started, MaxPlayers = 2, GameMode = "FFA", TeamCount = 1, AiSlotsJson = aiSlots, CreatedAt = DateTimeOffset.UtcNow, }; _gameDb.CustomLobbies.Add(lobby); // ── Create GameSession ──────────────────────────────────────────────── // P1 is chosen randomly between the two AI accounts. var (p1Id, p2Id, p1Deck, p2Deck) = Random.Shared.Next(2) == 0 ? (id1, id2, deckId1, deckId2) : (id2, id1, deckId2, deckId1); var rules = GameRules.Default with { PlayerCount = 2 }; var session = new GameSession { PlayerOneAccountId = p1Id, PlayerOneDeckId = p1Deck, PlayerTwoAccountId = p2Id, PlayerTwoDeckId = p2Deck, PlayerCount = 2, GameMode = "FFA", TeamCount = 1, PlayerOneTeamIndex = 0, PlayerTwoTeamIndex = 1, Status = GameSessionStatus.Initializing, CreatedAt = DateTimeOffset.UtcNow, RuleSnapshotJson = JsonSerializer.Serialize(rules), }; _gameDb.GameSessions.Add(session); lobby.GameSessionId = session.Id; await _gameDb.SaveChangesAsync(ct); // ── Publish GameStartedEvent ────────────────────────────────────────── try { await _eventBus.PublishAsync( NatsSubjects.GameStarted, new GameStartedEvent(session.Id, [p1Id, p2Id], DateTimeOffset.UtcNow), ct); } catch (Exception ex) { _logger.LogError(ex, "GameAiMatchHandler: failed to publish GameStartedEvent for session {SessionId}.", session.Id); } // ── Fetch display names ─────────────────────────────────────────────── var ids = new[] { p1Id, p2Id }; var names = await _identityDb.Users .AsNoTracking() .Where(u => ids.Contains(u.Id)) .Select(u => new { u.Id, Name = u.DisplayName ?? u.UserName ?? u.Id.ToString().Substring(0, 8) }) .ToDictionaryAsync(u => u.Id, u => u.Name, ct); var p1Name = names.GetValueOrDefault(p1Id, p1Id.ToString()[..8]); var p2Name = names.GetValueOrDefault(p2Id, p2Id.ToString()[..8]); _logger.LogInformation( "GameAiMatchHandler: created AI match {SessionId} ({P1} vs {P2}).", session.Id, p1Name, p2Name); return ServerMessage.Reply("game.ai.create_match.ack", message.Seq, new GameAiMatchResponse(session.Id, p1Name, p2Name)); } }