diff --git a/Server/SOR.slnx b/Server/SOR.slnx index 785b503..502fc08 100644 --- a/Server/SOR.slnx +++ b/Server/SOR.slnx @@ -8,6 +8,7 @@ + diff --git a/Server/src/SOR.Ai/Core/AiAccountRegistry.cs b/Server/src/SOR.Ai/Core/AiAccountRegistry.cs new file mode 100644 index 0000000..fc8f3d6 --- /dev/null +++ b/Server/src/SOR.Ai/Core/AiAccountRegistry.cs @@ -0,0 +1,47 @@ +namespace SOR.Ai.Core; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Shared; + +/// +/// In-memory registry of all AI account IDs. +/// Loaded at startup by AiSeedStartupService; used by GameEndTurnHandler (and others) +/// to check IsAi in O(1) without a database round-trip. +/// +/// Singleton. Thread-safe after Load() is called once — the HashSet is never +/// mutated after initial population. +/// +public sealed class AiAccountRegistry : IAiAccountRegistry +{ + private volatile HashSet _ids = []; + + /// Number of registered AI accounts. + public int Count => _ids.Count; + + /// + /// Returns true if the given account ID string belongs to an AI account. + /// Safe to call from any thread after Load() completes. + /// + public bool IsAi(string accountId) => _ids.Contains(accountId); + + /// + /// Returns true if the given GUID belongs to an AI account. + /// + public bool IsAi(Guid accountId) => _ids.Contains(accountId.ToString()); + + /// + /// Populates the registry from the database. Called once at startup. + /// Synchronous because it runs in IHostedService.StartAsync before the server + /// accepts traffic — blocking here is intentional. + /// + internal void Load(SorIdentityDbContext identityDb) + { + var ids = identityDb.Users + .Where(u => u.IsAi) + .Select(u => u.Id.ToString()) + .ToHashSet(); + + _ids = ids; + } +} diff --git a/Server/src/SOR.Ai/Core/AiPlayerSession.cs b/Server/src/SOR.Ai/Core/AiPlayerSession.cs new file mode 100644 index 0000000..52ac71c --- /dev/null +++ b/Server/src/SOR.Ai/Core/AiPlayerSession.cs @@ -0,0 +1,193 @@ +namespace SOR.Ai.Core; + +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using SOR.Ai.Transport; +using SOR.Database.Enums; // GamePhase +using SOR.Game; // GameState +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; + +/// +/// Manages one AI-controlled seat in a single active GameSession. +/// +/// Responsibilities: +/// - Submits game.ready at startup so the game can begin. +/// - Executes the AI's turn when AiPlayerSessionManager signals it. +/// +/// Phase 1 stub: ExecuteTurnAsync immediately ends the turn (pass). +/// Later phases add decision logic. +/// +internal sealed class AiPlayerSession : IAsyncDisposable +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + private readonly CancellationTokenSource _sessionCts = new(); + + public Guid SessionId { get; } + public string AiAccountId { get; } + public int Difficulty { get; } + public string Strategy { get; } + public int SeatIndex { get; } + + public AiPlayerSession( + Guid sessionId, + string aiAccountId, + int difficulty, + string strategy, + int seatIndex, + IServiceScopeFactory scopeFactory, + ILogger logger) + { + SessionId = sessionId; + AiAccountId = aiAccountId; + Difficulty = difficulty; + Strategy = strategy; + SeatIndex = seatIndex; + _scopeFactory = scopeFactory; + _logger = logger; + } + + /// + /// Sends game.ready on behalf of the AI after a short humanizing delay. + /// Called once when the game session is detected by AiPlayerSessionManager. + /// + public async Task SendReadyAsync(CancellationToken appCt) + { + using var ct = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token); + + // Short random delay before sending ready — feels more natural. + await Task.Delay(Random.Shared.Next(300, 900), ct.Token); + + _logger.LogDebug("AI {Account} sending game.ready for session {Session}.", + AiAccountId, SessionId); + + await InvokeHandlerAsync("game.ready", + JsonSerializer.SerializeToUtf8Bytes(new { SessionId }), + ct.Token); + } + + /// + /// Executes the AI's full turn. + /// Phase 1 stub: end turn immediately (AI passes). + /// + public async Task ExecuteTurnAsync(GameState state, CancellationToken appCt) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token); + var ct = cts.Token; + + _logger.LogDebug( + "AI {Account} (seat {Seat}) taking turn {Turn} in session {Session}.", + AiAccountId, SeatIndex, state.TurnNumber, SessionId); + + // Handle Placement phase separately — must place ArchSpirit before main turn. + if (state.Phase == GamePhase.Placement) + { + await ExecutePlacementAsync(state, ct); + return; + } + + // Phase 1 stub: immediately end turn with a short simulated delay. + await Task.Delay(Random.Shared.Next(800, 2000), ct); + + _logger.LogDebug( + "AI {Account} ending turn (stub — no decision logic yet).", + AiAccountId); + + await InvokeHandlerAsync("game.end_turn", + JsonSerializer.SerializeToUtf8Bytes(new { SessionId }), + ct); + } + + /// + /// Places the AI's ArchSpirit on a random valid tile in its starting zone. + /// Called during the Placement phase. + /// + private async Task ExecutePlacementAsync(GameState state, CancellationToken ct) + { + if (!state.Players.ContainsKey(AiAccountId)) + { + _logger.LogWarning("AI {Account}: PlayerState not found in Placement phase.", AiAccountId); + return; + } + + // Pick a random coord from the starting zone for this seat. + if (state.Board is null || + !state.Board.StartingZones.TryGetValue(SeatIndex, out var zone) || + zone.Count == 0) + { + _logger.LogWarning( + "AI {Account}: no starting zone for seat {Seat}.", + AiAccountId, SeatIndex); + return; + } + + var zoneList = zone.ToList(); + var coord = zoneList[Random.Shared.Next(zoneList.Count)]; + + await Task.Delay(Random.Shared.Next(400, 1200), ct); + + _logger.LogDebug( + "AI {Account} placing ArchSpirit at ({X},{Y}).", + AiAccountId, coord.X, coord.Y); + + await InvokeHandlerAsync("game.place_arch_spirit", + JsonSerializer.SerializeToUtf8Bytes(new { SessionId, Coord = new { coord.X, coord.Y } }), + ct); + } + + /// + /// Resolves and invokes a game message handler directly in-process, + /// as if the AI were a connected client sending that message. + /// + private async Task InvokeHandlerAsync( + string messageType, + ReadOnlyMemory payload, + CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var handlers = scope.ServiceProvider.GetServices(); + var handler = handlers.FirstOrDefault(h => h.MessageType == messageType); + + if (handler is null) + { + _logger.LogError( + "AI {Account}: no handler found for message type '{Type}'.", + AiAccountId, messageType); + return; + } + + var connection = new AuthenticatedConnection( + Connection : new AiNoOpClientConnection(AiAccountId), + UserId : AiAccountId, + DisplayName : "AI", + SessionToken : string.Empty); + + var message = new AiClientMessage(messageType, payload); + + try + { + await handler.HandleAsync(message, connection, ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // Session or app shutdown — ignore. + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "AI {Account}: handler '{Type}' threw an exception.", + AiAccountId, messageType); + } + } + + public void Cancel() => _sessionCts.Cancel(); + + public ValueTask DisposeAsync() + { + _sessionCts.Cancel(); + _sessionCts.Dispose(); + return ValueTask.CompletedTask; + } +} diff --git a/Server/src/SOR.Ai/Core/AiPlayerSessionManager.cs b/Server/src/SOR.Ai/Core/AiPlayerSessionManager.cs new file mode 100644 index 0000000..4e6ff3f --- /dev/null +++ b/Server/src/SOR.Ai/Core/AiPlayerSessionManager.cs @@ -0,0 +1,277 @@ +namespace SOR.Ai.Core; + +using System.Collections.Concurrent; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Game; +using SOR.Shared.Nats; +using SOR.Networking.Abstractions.EventBus; + +/// +/// Singleton BackgroundService that orchestrates AI player turns across all active sessions. +/// +/// On startup: subscribes to NATS GameStartedEvent and AiTurnStartedEvent. +/// On GameStartedEvent: inspects the session for AI seats and creates AiPlayerSession +/// instances, then sends game.ready on behalf of each AI seat. +/// On AiTurnStartedEvent: loads the game state and calls AiPlayerSession.ExecuteTurnAsync. +/// On GameEndedEvent: disposes AI sessions for that game. +/// +public sealed class AiPlayerSessionManager : BackgroundService +{ + /// Sessions keyed by sessionId. Each session may have multiple AI seats. + private readonly ConcurrentDictionary> _sessions = new(); + + private readonly IServiceScopeFactory _scopeFactory; + private readonly AiAccountRegistry _registry; + private readonly IEventBus _eventBus; + private readonly ILogger _logger; + + public AiPlayerSessionManager( + IServiceScopeFactory scopeFactory, + AiAccountRegistry registry, + IEventBus eventBus, + ILogger logger) + { + _scopeFactory = scopeFactory; + _registry = registry; + _eventBus = eventBus; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogInformation("AiPlayerSessionManager started."); + + // Subscribe to all three NATS subjects concurrently. + var gameStartedTask = ConsumeGameStartedAsync(stoppingToken); + var aiTurnTask = ConsumeAiTurnStartedAsync(stoppingToken); + var gameEndedTask = ConsumeGameEndedAsync(stoppingToken); + + await Task.WhenAll(gameStartedTask, aiTurnTask, gameEndedTask); + + _logger.LogInformation("AiPlayerSessionManager stopped."); + } + + // ── Event consumers ─────────────────────────────────────────────────────── + + private async Task ConsumeGameStartedAsync(CancellationToken ct) + { + try + { + await foreach (var evt in _eventBus.SubscribeAsync( + NatsSubjects.GameStarted, ct)) + { + await OnGameStartedAsync(evt, ct); + } + } + catch (OperationCanceledException) { /* normal shutdown */ } + catch (Exception ex) + { + _logger.LogError(ex, "AiPlayerSessionManager: GameStarted consumer crashed."); + } + } + + private async Task ConsumeAiTurnStartedAsync(CancellationToken ct) + { + try + { + await foreach (var evt in _eventBus.SubscribeAsync( + NatsSubjects.AiTurnStarted, ct)) + { + _ = Task.Run(() => OnAiTurnStartedAsync(evt, ct), ct); + } + } + catch (OperationCanceledException) { /* normal shutdown */ } + catch (Exception ex) + { + _logger.LogError(ex, "AiPlayerSessionManager: AiTurnStarted consumer crashed."); + } + } + + private async Task ConsumeGameEndedAsync(CancellationToken ct) + { + try + { + await foreach (var evt in _eventBus.SubscribeAsync( + NatsSubjects.GameEnded, ct)) + { + OnGameEnded(evt.GameId); + } + } + catch (OperationCanceledException) { /* normal shutdown */ } + catch (Exception ex) + { + _logger.LogError(ex, "AiPlayerSessionManager: GameEnded consumer crashed."); + } + } + + // ── Handlers ────────────────────────────────────────────────────────────── + + private async Task OnGameStartedAsync(GameStartedEvent evt, CancellationToken ct) + { + // Load the session to find AI seats. + await using var scope = _scopeFactory.CreateAsyncScope(); + var gameDb = scope.ServiceProvider.GetRequiredService(); + + var session = await gameDb.GameSessions + .AsNoTracking() + .FirstOrDefaultAsync(s => s.Id == evt.GameId, ct); + + if (session is null) + return; + + // Identify AI seats by checking each participant against the registry. + var aiSeats = new List<(Guid accountId, int seatIndex)>(); + + if (_registry.IsAi(session.PlayerOneAccountId)) + aiSeats.Add((session.PlayerOneAccountId, seatIndex: 0)); + + if (_registry.IsAi(session.PlayerTwoAccountId)) + aiSeats.Add((session.PlayerTwoAccountId, seatIndex: 1)); + + if (!string.IsNullOrEmpty(session.AdditionalPlayersJson)) + { + try + { + var addl = JsonSerializer.Deserialize>( + session.AdditionalPlayersJson, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) + ?? []; + + foreach (var p in addl) + if (_registry.IsAi(p.AccountId)) + aiSeats.Add((p.AccountId, p.SeatIndex)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "AiPlayerSessionManager: could not parse AdditionalPlayersJson for session {Id}.", + session.Id); + } + } + + if (aiSeats.Count == 0) + return; + + // Load difficulty/strategy from the account rows. + var aiAccountIds = aiSeats.Select(s => s.accountId).ToList(); + var aiAccounts = await scope.ServiceProvider + .GetRequiredService().Users + .AsNoTracking() + .Where(u => aiAccountIds.Contains(u.Id)) + .ToDictionaryAsync(u => u.Id, ct); + + // Look up AI slot metadata from the CustomLobby if it exists. + var lobby = await gameDb.CustomLobbies + .AsNoTracking() + .FirstOrDefaultAsync(l => l.GameSessionId == session.Id, ct); + + Dictionary slotMeta = []; + if (lobby?.AiSlotsJson is not null) + { + try + { + var slots = JsonSerializer.Deserialize>( + lobby.AiSlotsJson, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? []; + + foreach (var s in slots) + slotMeta[s.AccountId] = (s.Difficulty, s.Strategy); + } + catch { /* ignore malformed */ } + } + + // Build sessions. + var sessionList = new List(); + foreach (var (accountId, seatIndex) in aiSeats) + { + if (!aiAccounts.TryGetValue(accountId, out var acct)) + continue; + + var difficulty = slotMeta.TryGetValue(accountId, out var meta) + ? meta.difficulty : (acct.AiDifficulty ?? 1); + var strategy = slotMeta.TryGetValue(accountId, out meta) + ? meta.strategy : (acct.AiStrategy ?? "Balanced"); + + var aiSession = new AiPlayerSession( + sessionId : session.Id, + aiAccountId : accountId.ToString(), + difficulty : difficulty, + strategy : strategy, + seatIndex : seatIndex, + scopeFactory: _scopeFactory, + logger : scope.ServiceProvider + .GetRequiredService>()); + + sessionList.Add(aiSession); + + _logger.LogInformation( + "AiPlayerSessionManager: registered AI seat {Seat} ({Strategy} D{Diff}) " + + "for session {SessionId}.", + seatIndex, strategy, difficulty, session.Id); + } + + _sessions.TryAdd(session.Id, sessionList); + + // Send game.ready for each AI seat. + foreach (var aiSession in sessionList) + _ = Task.Run(() => aiSession.SendReadyAsync(ct), ct); + } + + private async Task OnAiTurnStartedAsync(AiTurnStartedEvent evt, CancellationToken ct) + { + if (!_sessions.TryGetValue(evt.SessionId, out var sessionList)) + return; + + var aiSession = sessionList.FirstOrDefault(s => s.AiAccountId == evt.AiAccountId); + if (aiSession is null) + return; + + // Load current game state from the DB. + await using var scope = _scopeFactory.CreateAsyncScope(); + var gameDb = scope.ServiceProvider.GetRequiredService(); + + var session = await gameDb.GameSessions + .AsNoTracking() + .FirstOrDefaultAsync(s => s.Id == evt.SessionId, ct); + + if (session is null || session.Status != GameSessionStatus.Active || session.StateJson is null) + return; + + var state = GameEngine.Deserialize(session.StateJson); + await aiSession.ExecuteTurnAsync(state, ct); + } + + private void OnGameEnded(Guid sessionId) + { + if (_sessions.TryRemove(sessionId, out var sessionList)) + { + foreach (var s in sessionList) + _ = s.DisposeAsync().AsTask(); + + _logger.LogDebug( + "AiPlayerSessionManager: disposed {Count} AI session(s) for {SessionId}.", + sessionList.Count, sessionId); + } + } + + // ── Private DTOs ────────────────────────────────────────────────────────── + + private sealed class AdditionalPlayerRef + { + public Guid AccountId { get; set; } + public int SeatIndex { get; set; } + } + + private sealed class AiSlotRef + { + public Guid AccountId { get; set; } + public int Difficulty { get; set; } + public string Strategy { get; set; } = string.Empty; + } +} diff --git a/Server/src/SOR.Ai/Core/AiTurnContext.cs b/Server/src/SOR.Ai/Core/AiTurnContext.cs new file mode 100644 index 0000000..269dff0 --- /dev/null +++ b/Server/src/SOR.Ai/Core/AiTurnContext.cs @@ -0,0 +1,37 @@ +namespace SOR.Ai.Core; + +using SOR.Game; + +/// +/// A snapshot of the game state from one AI player's perspective. +/// Created by AiPlayerSession before each turn; passed to IAiDecisionEngine. +/// Immutable — the engine must not mutate the State field directly. +/// +public sealed class AiTurnContext +{ + public AiTurnContext(GameState state, string aiAccountId) + { + State = state; + AiAccountId = aiAccountId; + AiPlayer = state.Players[aiAccountId]; + OpponentIds = state.Players.Keys + .Where(k => k != aiAccountId && !state.Players[k].IsEliminated) + .ToList(); + Rules = state.Rules; + } + + /// Full game state at the start of the AI's turn. Do not mutate. + public GameState State { get; } + + /// This AI's account ID string. + public string AiAccountId { get; } + + /// Convenience accessor for this AI's PlayerState. + public PlayerState AiPlayer { get; } + + /// Account IDs of non-eliminated opponents. + public IReadOnlyList OpponentIds { get; } + + /// Effective rules for this game. + public GameRules Rules { get; } +} diff --git a/Server/src/SOR.Ai/Handlers/GameAddAiHandler.cs b/Server/src/SOR.Ai/Handlers/GameAddAiHandler.cs new file mode 100644 index 0000000..843c66a --- /dev/null +++ b/Server/src/SOR.Ai/Handlers/GameAddAiHandler.cs @@ -0,0 +1,201 @@ +namespace SOR.Ai.Handlers; + +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using SOR.Ai.Lobby; +using SOR.Ai.Seeding; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Game; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.ai.add — lobby host adds an AI player to an open custom lobby. +/// +/// The AI account is inserted into the lobby's GuestAccountId (2-player lobby) +/// or AdditionalPlayersJson (3+ player lobby) so the existing game-start flow +/// picks it up exactly like a human guest. +/// +internal sealed class GameAddAiHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly SorIdentityDbContext _identityDb; + private readonly CollectionDbContext _collectionDb; + private readonly IClientPush _clientPush; + private readonly AiSlotAssigner _assigner; + private readonly AiLobbyService _lobbyService; + + public GameAddAiHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + SorIdentityDbContext identityDb, + CollectionDbContext collectionDb, + IClientPush clientPush, + AiSlotAssigner assigner, + AiLobbyService lobbyService) + { + _serializer = serializer; + _gameDb = gameDb; + _identityDb = identityDb; + _collectionDb = collectionDb; + _clientPush = clientPush; + _assigner = assigner; + _lobbyService = lobbyService; + } + + public string MessageType => "game.ai.add"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var requesterId = Guid.Parse(connection.UserId); + + if (req.Difficulty is < 1 or > 10) + throw new GameException("INVALID_DIFFICULTY"); + + if (!AiAccountSeeder.Strategies.Contains(req.Strategy)) + throw new GameException("INVALID_STRATEGY"); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.HostAccountId != requesterId) + throw new GameException("NOT_LOBBY_HOST"); + + if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full)) + throw new GameException("LOBBY_NOT_MODIFIABLE"); + + // Existing slot list and additional players. + var currentSlots = _lobbyService.GetSlots(lobby); + var addlPlayers = DeserializeAdditional(lobby.AdditionalPlayersJson); + + // Total current seats = host + optional guest + additional players. + int currentCount = 1 + + (lobby.GuestAccountId.HasValue ? 1 : 0) + + addlPlayers.Count; + + if (currentCount >= lobby.MaxPlayers) + throw new GameException("LOBBY_FULL"); + + // Resolve the AI account and its deck. + var aiAccount = await _assigner.GetAiAccountAsync(req.Difficulty, req.Strategy, ct); + var aiId = aiAccount.Id; + + var deckId = await _collectionDb.Decks + .AsNoTracking() + .Where(d => d.AccountId == aiId) + .Select(d => d.Id) + .FirstOrDefaultAsync(ct); + + if (deckId == Guid.Empty) + throw new GameException("AI_DECK_NOT_FOUND"); + + // Assign the AI to the correct slot. + int seatIndex; + + if (!lobby.GuestAccountId.HasValue && lobby.MaxPlayers == 2) + { + // Standard 1v1: AI becomes the guest. + lobby.GuestAccountId = aiId; + lobby.GuestDeckId = deckId; + lobby.Status = CustomLobbyStatus.Full; + seatIndex = 1; + } + else + { + // Multi-player: AI goes into AdditionalPlayersJson. + seatIndex = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + addlPlayers.Count; + + addlPlayers.Add(new AdditionalLobbyPlayer + { + AccountId = aiId, + DeckId = deckId, + SeatIndex = seatIndex, + TeamIndex = seatIndex % Math.Max(1, lobby.TeamCount), + }); + lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addlPlayers); + + if (currentCount + 1 >= lobby.MaxPlayers) + lobby.Status = CustomLobbyStatus.Full; + } + + // Track the AI slot so AiPlayerSessionManager identifies it after game start. + currentSlots.Add(new AiLobbySlot + { + AccountId = aiId, + Difficulty = req.Difficulty, + Strategy = req.Strategy, + SeatIndex = seatIndex, + }); + _lobbyService.SetSlots(lobby, currentSlots); + + await _gameDb.SaveChangesAsync(ct); + + // Push updated AI slot list to all human lobby members. + var slotDtos = ToSlotDtos(currentSlots); + var push = ServerMessage.Push("game.ai.slots_changed", + new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos)); + + await PushToAllMembersAsync(lobby, addlPlayers, push, ct); + + var displayName = aiAccount.DisplayName ?? aiAccount.UserName ?? aiId.ToString(); + return ServerMessage.Reply("game.ai.add.ack", message.Seq, + new GameAddAiResponse(aiId, displayName, seatIndex)); + } + + // ── Shared helpers ──────────────────────────────────────────────────────── + + internal static IReadOnlyList ToSlotDtos(List slots) => + slots.Select(s => new AiSlotInfo( + s.AccountId, + AiAccountSeeder.DisplayName(s.Difficulty, s.Strategy), + s.Difficulty, + s.Strategy, + s.SeatIndex)).ToList(); + + internal static List DeserializeAdditional(string? json) + { + if (string.IsNullOrEmpty(json)) return []; + try + { + return JsonSerializer.Deserialize>( + json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? []; + } + catch { return []; } + } + + internal async Task PushToAllMembersAsync( + SOR.Database.Entities.Game.CustomLobby lobby, + List additionalPlayers, + IServerMessage msg, + CancellationToken ct) + { + var tasks = new List + { + _clientPush.PushAsync(lobby.HostAccountId.ToString(), msg, ct), + }; + + if (lobby.GuestAccountId.HasValue) + tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), msg, ct)); + + foreach (var p in additionalPlayers) + tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), msg, ct)); + + await Task.WhenAll(tasks); + } + + internal sealed class AdditionalLobbyPlayer + { + public Guid AccountId { get; set; } + public Guid DeckId { get; set; } + public int SeatIndex { get; set; } + public int TeamIndex { get; set; } + } +} diff --git a/Server/src/SOR.Ai/Handlers/GameConfigureAiHandler.cs b/Server/src/SOR.Ai/Handlers/GameConfigureAiHandler.cs new file mode 100644 index 0000000..9727e2a --- /dev/null +++ b/Server/src/SOR.Ai/Handlers/GameConfigureAiHandler.cs @@ -0,0 +1,129 @@ +namespace SOR.Ai.Handlers; + +using SOR.Ai.Lobby; +using SOR.Ai.Seeding; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Game; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.ai.configure — lobby host changes the difficulty or strategy of an AI slot +/// before the game starts. The underlying AI account ID may change (different account +/// per difficulty/strategy combination), but the seat index stays the same. +/// +internal sealed class GameConfigureAiHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly SorIdentityDbContext _identityDb; + private readonly IClientPush _clientPush; + private readonly AiSlotAssigner _assigner; + private readonly AiLobbyService _lobbyService; + + public GameConfigureAiHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + SorIdentityDbContext identityDb, + IClientPush clientPush, + AiSlotAssigner assigner, + AiLobbyService lobbyService) + { + _serializer = serializer; + _gameDb = gameDb; + _identityDb = identityDb; + _clientPush = clientPush; + _assigner = assigner; + _lobbyService = lobbyService; + } + + public string MessageType => "game.ai.configure"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var requesterId = Guid.Parse(connection.UserId); + + if (req.Difficulty is not null && req.Difficulty is < 1 or > 10) + throw new GameException("INVALID_DIFFICULTY"); + + if (req.Strategy is not null && !AiAccountSeeder.Strategies.Contains(req.Strategy)) + throw new GameException("INVALID_STRATEGY"); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.HostAccountId != requesterId) + throw new GameException("NOT_LOBBY_HOST"); + + if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full)) + throw new GameException("LOBBY_NOT_MODIFIABLE"); + + var currentSlots = _lobbyService.GetSlots(lobby); + var slot = currentSlots.FirstOrDefault(s => s.AccountId == req.AiAccountId) + ?? throw new GameException("AI_SLOT_NOT_FOUND"); + + // Resolve the new difficulty / strategy (default to current if not changed). + int newDifficulty = req.Difficulty ?? slot.Difficulty; + string newStrategy = req.Strategy ?? slot.Strategy; + + if (newDifficulty == slot.Difficulty && newStrategy == slot.Strategy) + // Nothing changed. + return ServerMessage.Reply("game.ai.configure.ack", message.Seq, + new GameConfigureAiResponse(true)); + + // The new combination may map to a different AI account ID. + var newAccount = await _assigner.GetAiAccountAsync(newDifficulty, newStrategy, ct); + var oldId = slot.AccountId; + var newId = newAccount.Id; + + // Swap the account ID in the guest slot or additional players list. + if (lobby.GuestAccountId == oldId) + { + lobby.GuestAccountId = newId; + } + else + { + var addl = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson); + var entry = addl.FirstOrDefault(p => p.AccountId == oldId); + if (entry is not null) + entry.AccountId = newId; + + lobby.AdditionalPlayersJson = System.Text.Json.JsonSerializer.Serialize(addl); + } + + // Update the AI slot metadata. + slot.AccountId = newId; + slot.Difficulty = newDifficulty; + slot.Strategy = newStrategy; + _lobbyService.SetSlots(lobby, currentSlots); + + await _gameDb.SaveChangesAsync(ct); + + // Push updated slot list to all human members. + var addlAfter = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson); + var slotDtos = GameAddAiHandler.ToSlotDtos(currentSlots); + var push = ServerMessage.Push("game.ai.slots_changed", + new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos)); + + var tasks = new List + { + _clientPush.PushAsync(lobby.HostAccountId.ToString(), push, ct), + }; + if (lobby.GuestAccountId.HasValue) + tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), push, ct)); + foreach (var p in addlAfter) + tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), push, ct)); + + await Task.WhenAll(tasks); + + return ServerMessage.Reply("game.ai.configure.ack", message.Seq, + new GameConfigureAiResponse(true)); + } +} diff --git a/Server/src/SOR.Ai/Handlers/GameRemoveAiHandler.cs b/Server/src/SOR.Ai/Handlers/GameRemoveAiHandler.cs new file mode 100644 index 0000000..70e1b85 --- /dev/null +++ b/Server/src/SOR.Ai/Handlers/GameRemoveAiHandler.cs @@ -0,0 +1,107 @@ +namespace SOR.Ai.Handlers; + +using System.Text.Json; +using SOR.Ai.Lobby; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Game; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.ai.remove — lobby host removes an AI player from the lobby. +/// +internal sealed class GameRemoveAiHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly AiLobbyService _lobbyService; + + public GameRemoveAiHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + AiLobbyService lobbyService) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _lobbyService = lobbyService; + } + + public string MessageType => "game.ai.remove"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var requesterId = Guid.Parse(connection.UserId); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.HostAccountId != requesterId) + throw new GameException("NOT_LOBBY_HOST"); + + if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full)) + throw new GameException("LOBBY_NOT_MODIFIABLE"); + + var currentSlots = _lobbyService.GetSlots(lobby); + var slot = currentSlots.FirstOrDefault(s => s.AccountId == req.AiAccountId); + + if (slot is null) + throw new GameException("AI_SLOT_NOT_FOUND"); + + // Remove from GuestAccountId or AdditionalPlayersJson. + if (lobby.GuestAccountId == req.AiAccountId) + { + lobby.GuestAccountId = null; + lobby.GuestDeckId = null; + lobby.Status = CustomLobbyStatus.Open; + } + else + { + var addl = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson); + addl.RemoveAll(p => p.AccountId == req.AiAccountId); + lobby.AdditionalPlayersJson = addl.Count > 0 + ? JsonSerializer.Serialize(addl) + : null; + + // Recalculate status. + int remaining = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + addl.Count; + lobby.Status = remaining < lobby.MaxPlayers + ? CustomLobbyStatus.Open + : CustomLobbyStatus.Full; + } + + currentSlots.Remove(slot); + _lobbyService.SetSlots(lobby, currentSlots); + + await _gameDb.SaveChangesAsync(ct); + + // Push updated slot list to all remaining human members. + var addlAfter = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson); + var slotDtos = GameAddAiHandler.ToSlotDtos(currentSlots); + var push = ServerMessage.Push("game.ai.slots_changed", + new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos)); + + var tasks = new List + { + _clientPush.PushAsync(lobby.HostAccountId.ToString(), push, ct), + }; + if (lobby.GuestAccountId.HasValue) + tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), push, ct)); + foreach (var p in addlAfter) + tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), push, ct)); + + await Task.WhenAll(tasks); + + return ServerMessage.Reply("game.ai.remove.ack", message.Seq, + new GameRemoveAiResponse(true)); + } +} diff --git a/Server/src/SOR.Ai/Lobby/AiLobbyService.cs b/Server/src/SOR.Ai/Lobby/AiLobbyService.cs new file mode 100644 index 0000000..2d7dacf --- /dev/null +++ b/Server/src/SOR.Ai/Lobby/AiLobbyService.cs @@ -0,0 +1,47 @@ +namespace SOR.Ai.Lobby; + +using System.Text.Json; +using SOR.Database.Entities.Game; + +/// +/// Shared read/write helpers for CustomLobby.AiSlotsJson. +/// Scoped service — one instance per request scope. +/// +internal sealed class AiLobbyService +{ + private static readonly JsonSerializerOptions _json = + new() { PropertyNameCaseInsensitive = true }; + + /// Deserializes the AI slot list from a lobby. Never returns null. + public List GetSlots(CustomLobby lobby) + { + if (string.IsNullOrEmpty(lobby.AiSlotsJson)) + return []; + + try + { + return JsonSerializer.Deserialize>(lobby.AiSlotsJson, _json) ?? []; + } + catch + { + return []; + } + } + + /// Serializes and writes the slot list back to the lobby entity. + public void SetSlots(CustomLobby lobby, List slots) + { + lobby.AiSlotsJson = slots.Count > 0 + ? JsonSerializer.Serialize(slots) + : null; + } +} + +/// One AI slot entry stored in CustomLobby.AiSlotsJson. +internal sealed class AiLobbySlot +{ + public Guid AccountId { get; set; } + public string Strategy { get; set; } = string.Empty; + public int Difficulty { get; set; } + public int SeatIndex { get; set; } +} diff --git a/Server/src/SOR.Ai/Lobby/AiSlotAssigner.cs b/Server/src/SOR.Ai/Lobby/AiSlotAssigner.cs new file mode 100644 index 0000000..05537b8 --- /dev/null +++ b/Server/src/SOR.Ai/Lobby/AiSlotAssigner.cs @@ -0,0 +1,40 @@ +namespace SOR.Ai.Lobby; + +using Microsoft.EntityFrameworkCore; +using SOR.Ai.Seeding; +using SOR.Database.Contexts; +using SOR.Database.Entities.Identity; + +/// +/// Resolves a (difficulty, strategy) request to the matching pre-seeded AI account. +/// Scoped service — one instance per request scope. +/// +internal sealed class AiSlotAssigner +{ + private readonly SorIdentityDbContext _identityDb; + + public AiSlotAssigner(SorIdentityDbContext identityDb) + { + _identityDb = identityDb; + } + + /// + /// Returns the AI account for the given difficulty + strategy. + /// Throws if not found (seed should have created it at startup). + /// + public async Task GetAiAccountAsync( + int difficulty, + string strategy, + CancellationToken ct) + { + // Use the deterministic ID to avoid a name-based query. + var id = AiAccountSeeder.AccountId(difficulty, strategy); + + return await _identityDb.Users + .AsNoTracking() + .FirstOrDefaultAsync(u => u.Id == id, ct) + ?? throw new InvalidOperationException( + $"AI account not found for difficulty={difficulty} strategy={strategy}. " + + "Ensure AiSeedStartupService ran before traffic was accepted."); + } +} diff --git a/Server/src/SOR.Ai/SOR.Ai.csproj b/Server/src/SOR.Ai/SOR.Ai.csproj new file mode 100644 index 0000000..f436052 --- /dev/null +++ b/Server/src/SOR.Ai/SOR.Ai.csproj @@ -0,0 +1,18 @@ + + + net8.0 + + + + + + + + + + + + + + diff --git a/Server/src/SOR.Ai/Seeding/AiAccountSeeder.cs b/Server/src/SOR.Ai/Seeding/AiAccountSeeder.cs new file mode 100644 index 0000000..2b1b1b5 --- /dev/null +++ b/Server/src/SOR.Ai/Seeding/AiAccountSeeder.cs @@ -0,0 +1,134 @@ +namespace SOR.Ai.Seeding; + +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Database.Entities.Identity; + +/// +/// Ensures all canonical AI accounts exist in the identity database. +/// Runs once at startup via AiSeedStartupService before traffic is accepted. +/// Uses deterministic GUIDs so re-running is fully idempotent (upsert by ID). +/// +/// Creates 50 accounts: 10 difficulty tiers × 5 strategy archetypes. +/// Each account has IsAi=true, IsHiddenFromLeaderboard=true, RankScore=0. +/// +internal static class AiAccountSeeder +{ + internal static readonly string[] Strategies = ["Aggressive", "Control", "Balanced", "Ramp", "Swarm"]; + + private static readonly string[] DifficultyNames = + [ + "", // 0 — unused + "Novice", // 1 + "Apprentice", // 2 + "Journeyman", // 3 + "Adept", // 4 + "Expert", // 5 + "Master", // 6 + "Grandmaster",// 7 + "Champion", // 8 + "Legend", // 9 + "Mythic", // 10 + ]; + + /// + /// Returns the deterministic GUID used for a given (difficulty, strategy) combination. + /// Deterministic = same inputs always produce the same GUID, so seeds are idempotent. + /// + public static Guid AccountId(int difficulty, string strategy) => + new(GuidV5( + $"sor-ai-account:{difficulty}:{strategy.ToLowerInvariant()}")); + + /// + /// Returns the display name shown in lobbies and game screens for this AI slot. + /// Format: "{Strategy} AI ({DifficultyName})" e.g. "Balanced AI (Adept)" + /// + public static string DisplayName(int difficulty, string strategy) => + $"{strategy} AI ({DifficultyNames[difficulty]})"; + + public static async Task SeedAsync( + SorIdentityDbContext identityDb, + ILogger logger, + CancellationToken ct) + { + var expectedIds = new HashSet(); + var toUpsert = new List(); + + for (int d = 1; d <= 10; d++) + { + foreach (var strategy in Strategies) + { + var id = AccountId(d, strategy); + expectedIds.Add(id); + toUpsert.Add(new Account + { + Id = id, + UserName = $"ai-{DifficultyNames[d].ToLowerInvariant()}-{strategy.ToLowerInvariant()}", + NormalizedUserName = $"AI-{DifficultyNames[d].ToUpperInvariant()}-{strategy.ToUpperInvariant()}", + Email = $"ai-{d}-{strategy.ToLowerInvariant()}@internal.sor", + NormalizedEmail = $"AI-{d}-{strategy.ToUpperInvariant()}@INTERNAL.SOR", + EmailConfirmed = true, + PasswordHash = string.Empty, + SecurityStamp = Guid.NewGuid().ToString(), + DisplayName = DisplayName(d, strategy), + IsAi = true, + AiDifficulty = d, + AiStrategy = strategy, + IsHiddenFromLeaderboard = true, + RankScore = 0, + OriginPoints = 0, + CreatedAt = DateTimeOffset.UtcNow, + }); + } + } + + // Load existing AI accounts to detect what's missing. + var existingList = await identityDb.Users + .Where(u => expectedIds.Contains(u.Id)) + .Select(u => u.Id) + .ToListAsync(ct); + var existing = existingList.ToHashSet(); + + int added = 0; + foreach (var account in toUpsert) + { + if (existing.Contains(account.Id)) + continue; + + identityDb.Users.Add(account); + added++; + } + + if (added > 0) + { + await identityDb.SaveChangesAsync(ct); + logger.LogInformation("SOR.Ai: seeded {Count} AI accounts.", added); + } + else + { + logger.LogDebug("SOR.Ai: all {Total} AI accounts already exist.", expectedIds.Count); + } + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + /// + /// Deterministic UUID v5 (SHA-1 namespace) from a string seed. + /// Produces the same 16-byte GUID every time for the same input. + /// + private static byte[] GuidV5(string seed) + { + // Use a fixed namespace so these GUIDs can never collide with random GUIDs. + var ns = new byte[] { 0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 }; + var name = System.Text.Encoding.UTF8.GetBytes(seed); + var hash = System.Security.Cryptography.SHA1.HashData([..ns, ..name]); + + // Force version 5 and variant bits per RFC 4122. + hash[6] = (byte)((hash[6] & 0x0F) | 0x50); + hash[8] = (byte)((hash[8] & 0x3F) | 0x80); + + return hash[..16]; + } +} diff --git a/Server/src/SOR.Ai/Seeding/AiDeckDefinitions.cs b/Server/src/SOR.Ai/Seeding/AiDeckDefinitions.cs new file mode 100644 index 0000000..42d2e54 --- /dev/null +++ b/Server/src/SOR.Ai/Seeding/AiDeckDefinitions.cs @@ -0,0 +1,70 @@ +namespace SOR.Ai.Seeding; + +/// +/// Describes one AI deck in terms of card names rather than IDs. +/// AiDeckSeeder resolves names to CardDefinitionIds at runtime. +/// One blueprint per strategy archetype. All AI accounts of a given strategy +/// share the same deck blueprint regardless of difficulty. +/// +internal sealed record AiDeckBlueprint( + string Strategy, + /// Display name of the ArchSpirit card in CardDefinitions.Name. + string ArchSpiritName, + /// Display name of the deck shown in the lobby. + string DeckName, + /// Card names with quantities. Keys = CardDefinition.Name, values = quantity. + IReadOnlyDictionary Cards); + +/// +/// Static table of deck blueprints — one per strategy archetype. +/// Card names must match CardDefinition.Name exactly (case-sensitive). +/// +/// NOTE: If a card name does not exist in the catalog at seed time, AiDeckSeeder +/// will log a warning and skip that card rather than failing. This allows the server +/// to start even in environments where only a subset of cards are in the catalog. +/// +internal static class AiDeckDefinitions +{ + /// + /// Returns all deck blueprints, one per strategy. + /// The consuming code matches strategies to AI accounts via AiAccountSeeder.Strategies. + /// + public static IReadOnlyList All { get; } = + [ + // Balanced — generic mix of attack + defense. + // Replace card names with real catalog entries when available. + new AiDeckBlueprint( + Strategy : "Balanced", + ArchSpiritName: "Ignis Pup", // placeholder — update to real ArchSpirit name + DeckName : "Balanced Starter", + Cards : new Dictionary()), + + // Aggressive — rush strategy, cheap Spirits, prioritize ArchSpirit pressure. + new AiDeckBlueprint( + Strategy : "Aggressive", + ArchSpiritName: "Ignis Pup", // placeholder + DeckName : "Aggro Rush", + Cards : new Dictionary()), + + // Control — defensive, Terramorpha tile control, attrition. + new AiDeckBlueprint( + Strategy : "Control", + ArchSpiritName: "Ignis Pup", // placeholder + DeckName : "Control Fortress", + Cards : new Dictionary()), + + // Ramp — Sacrifice-heavy, builds ST then plays expensive threats. + new AiDeckBlueprint( + Strategy : "Ramp", + ArchSpiritName: "Ignis Pup", // placeholder + DeckName : "Sacrifice Engine", + Cards : new Dictionary()), + + // Swarm — flood the board with cheap low-cost Spirits. + new AiDeckBlueprint( + Strategy : "Swarm", + ArchSpiritName: "Ignis Pup", // placeholder + DeckName : "Spirit Horde", + Cards : new Dictionary()), + ]; +} diff --git a/Server/src/SOR.Ai/Seeding/AiDeckSeeder.cs b/Server/src/SOR.Ai/Seeding/AiDeckSeeder.cs new file mode 100644 index 0000000..3de1ab3 --- /dev/null +++ b/Server/src/SOR.Ai/Seeding/AiDeckSeeder.cs @@ -0,0 +1,118 @@ +namespace SOR.Ai.Seeding; + +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Database.Entities.Collection; + +/// +/// Seeds one Deck row per AI account based on the strategy-archetype blueprints +/// in AiDeckDefinitions. Called from AiSeedStartupService after AI accounts exist. +/// +/// Graceful partial-seed: if a card name in the blueprint does not exist in the +/// catalog, it is skipped with a warning rather than throwing. The deck is still +/// created with IsValid=true so the AI can join games even with an incomplete deck. +/// Card definitions should be filled in once the full catalog is available. +/// +internal static class AiDeckSeeder +{ + public static async Task SeedAsync( + SorIdentityDbContext identityDb, + CollectionDbContext collectionDb, + CatalogDbContext catalogDb, + ILogger logger, + CancellationToken ct) + { + // Build a lookup of blueprint by strategy. + var blueprints = AiDeckDefinitions.All.ToDictionary(b => b.Strategy); + + // Load all card definitions by name for lookup. + var catalogCardNames = blueprints.Values + .SelectMany(b => b.Cards.Keys) + .Append(blueprints.Values.Select(b => b.ArchSpiritName).First()) + .Concat(blueprints.Values.Select(b => b.ArchSpiritName)) + .Distinct() + .ToList(); + + var catalogCards = catalogCardNames.Count > 0 + ? await catalogDb.Set() + .AsNoTracking() + .Where(c => catalogCardNames.Contains(c.Name)) + .ToDictionaryAsync(c => c.Name, ct) + : new Dictionary(); + + int seeded = 0; + + for (int difficulty = 1; difficulty <= 10; difficulty++) + { + foreach (var strategy in AiAccountSeeder.Strategies) + { + if (!blueprints.TryGetValue(strategy, out var blueprint)) + continue; + + var accountId = AiAccountSeeder.AccountId(difficulty, strategy); + + // Skip if this AI account already has a deck. + var existingDeck = await collectionDb.Decks + .AsNoTracking() + .AnyAsync(d => d.AccountId == accountId, ct); + + if (existingDeck) + continue; + + // Resolve ArchSpirit definition ID. + if (!catalogCards.TryGetValue(blueprint.ArchSpiritName, out var archDef)) + { + logger.LogWarning( + "SOR.Ai deck seed: ArchSpirit '{Name}' not found in catalog — " + + "skipping deck for {Strategy} difficulty {Diff}.", + blueprint.ArchSpiritName, strategy, difficulty); + continue; + } + + var deck = new Deck + { + AccountId = accountId, + Name = blueprint.DeckName, + Description = $"Pre-built AI deck ({strategy} strategy)", + ArchSpiritCardDefinitionId = archDef.Id, + IsValid = true, // AI decks bypass normal validation + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + + // Add deck cards from the blueprint. + foreach (var (cardName, qty) in blueprint.Cards) + { + if (!catalogCards.TryGetValue(cardName, out var cardDef)) + { + logger.LogWarning( + "SOR.Ai deck seed: card '{Name}' not found in catalog — " + + "skipping for {Strategy} deck.", + cardName, strategy); + continue; + } + + deck.Cards.Add(new DeckCard + { + CardDefinitionId = cardDef.Id, + Quantity = qty, + }); + } + + collectionDb.Decks.Add(deck); + seeded++; + } + } + + if (seeded > 0) + { + await collectionDb.SaveChangesAsync(ct); + logger.LogInformation("SOR.Ai: seeded {Count} AI decks.", seeded); + } + else + { + logger.LogDebug("SOR.Ai: all AI decks already exist or ArchSpirit not in catalog."); + } + } +} diff --git a/Server/src/SOR.Ai/Seeding/AiSeedStartupService.cs b/Server/src/SOR.Ai/Seeding/AiSeedStartupService.cs new file mode 100644 index 0000000..b25ee9b --- /dev/null +++ b/Server/src/SOR.Ai/Seeding/AiSeedStartupService.cs @@ -0,0 +1,54 @@ +namespace SOR.Ai.Seeding; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SOR.Ai.Core; +using SOR.Database.Contexts; + +/// +/// One-shot IHostedService that runs at startup before the server accepts traffic. +/// Seeds AI accounts and decks, then loads the AiAccountRegistry so other services +/// can check IsAi without hitting the database on every turn. +/// +internal sealed class AiSeedStartupService : IHostedService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly AiAccountRegistry _registry; + private readonly ILogger _logger; + + public AiSeedStartupService( + IServiceScopeFactory scopeFactory, + AiAccountRegistry registry, + ILogger logger) + { + _scopeFactory = scopeFactory; + _registry = registry; + _logger = logger; + } + + public async Task StartAsync(CancellationToken cancellationToken) + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var sp = scope.ServiceProvider; + + var identityDb = sp.GetRequiredService(); + var collectionDb = sp.GetRequiredService(); + var catalogDb = sp.GetRequiredService(); + + // 1. Seed AI accounts (idempotent). + await AiAccountSeeder.SeedAsync(identityDb, _logger, cancellationToken); + + // 2. Seed AI decks (idempotent; skips gracefully if catalog cards missing). + await AiDeckSeeder.SeedAsync(identityDb, collectionDb, catalogDb, _logger, cancellationToken); + + // 3. Populate in-memory registry for O(1) IsAi checks. + _registry.Load(identityDb); + + _logger.LogInformation( + "SOR.Ai: startup seed complete. {Count} AI accounts registered.", + _registry.Count); + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/Server/src/SOR.Ai/ServiceRegistration.cs b/Server/src/SOR.Ai/ServiceRegistration.cs new file mode 100644 index 0000000..6dd1514 --- /dev/null +++ b/Server/src/SOR.Ai/ServiceRegistration.cs @@ -0,0 +1,51 @@ +namespace SOR.Ai; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SOR.Ai.Core; +using SOR.Ai.Handlers; +using SOR.Ai.Lobby; +using SOR.Ai.Seeding; +using SOR.Networking.Abstractions.Messaging; +using SOR.Shared; + +/// +/// Registers all AI service components into the DI container. +/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "game" +/// (AI is always co-located with the game service — it depends on game handlers directly). +/// +public static class ServiceRegistration +{ + public static IServiceCollection AddAiService( + this IServiceCollection services, + IConfiguration configuration) + { + // ── Startup seed (one-shot IHostedService) ──────────────────────────── + // Ensures AI accounts and decks exist in the DB before traffic is accepted. + services.AddHostedService(); + + // ── Account registry (singleton, loaded at seed time) ───────────────── + // In-memory set of AI account IDs for O(1) "is this account an AI?" checks. + // Used by GameEndTurnHandler to decide whether to publish AiTurnStartedEvent. + // Registered as both the concrete type AND the shared interface so SOR.Game + // handlers can inject IAiAccountRegistry without referencing SOR.Ai directly. + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + + // ── Session manager (singleton hosted service) ──────────────────────── + // Listens for game-start events and orchestrates AI turns. + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + + // ── Lobby scoped services ───────────────────────────────────────────── + services.AddScoped(); + services.AddScoped(); + + // ── Lobby message handlers ──────────────────────────────────────────── + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services; + } +} diff --git a/Server/src/SOR.Ai/Transport/AiClientMessage.cs b/Server/src/SOR.Ai/Transport/AiClientMessage.cs new file mode 100644 index 0000000..a803062 --- /dev/null +++ b/Server/src/SOR.Ai/Transport/AiClientMessage.cs @@ -0,0 +1,26 @@ +namespace SOR.Ai.Transport; + +using SOR.Networking.Abstractions.Messaging; + +/// +/// An IClientMessage constructed by the AI layer to call game handlers directly, +/// bypassing the WebSocket transport entirely. +/// +/// The payload must be pre-serialized as UTF-8 JSON using +/// JsonSerializer.SerializeToUtf8Bytes(request), which is exactly what the Gateway +/// WebSocket transport produces — so handlers see no difference. +/// +internal sealed class AiClientMessage : IClientMessage +{ + public string Type { get; } + public int Seq { get; } + + public ReadOnlyMemory Payload { get; } + + public AiClientMessage(string type, ReadOnlyMemory payload, int seq = 0) + { + Type = type; + Seq = seq; + Payload = payload; + } +} diff --git a/Server/src/SOR.Ai/Transport/AiNoOpClientConnection.cs b/Server/src/SOR.Ai/Transport/AiNoOpClientConnection.cs new file mode 100644 index 0000000..37976c9 --- /dev/null +++ b/Server/src/SOR.Ai/Transport/AiNoOpClientConnection.cs @@ -0,0 +1,40 @@ +namespace SOR.Ai.Transport; + +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; + +/// +/// A no-op IClientConnection used when constructing an AuthenticatedConnection +/// for an AI player. The AI never receives WebSocket frames and never sends replies +/// over a socket — all communication goes through the game handler's push pipeline +/// (Redis → real players). Any attempt to actually send bytes through this connection +/// is silently discarded. +/// +internal sealed class AiNoOpClientConnection : IClientConnection +{ + private readonly string _aiAccountId; + + public AiNoOpClientConnection(string aiAccountId) + { + _aiAccountId = aiAccountId; + ConnectionId = $"ai-{aiAccountId}"; + } + + public string ConnectionId { get; } + public string RemoteAddress => "127.0.0.1:0"; + public bool IsConnected => true; + + // AI never receives messages via this connection; the session manager drives turns. + public Task ReceiveAsync(CancellationToken cancellationToken) => + Task.FromCanceled(cancellationToken); + + // AI replies are discarded — the handler already pushes state to real players + // via IClientPush (Redis). Nothing is lost by swallowing this. + public ValueTask SendBytesAsync(ReadOnlyMemory bytes, CancellationToken cancellationToken) => + ValueTask.CompletedTask; + + public Task CloseAsync(string reason, CancellationToken cancellationToken) => + Task.CompletedTask; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs index 2aed341..32bfc1f 100644 --- a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs +++ b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs @@ -131,6 +131,22 @@ public sealed class CustomLobby /// public string? TeamAssignmentsJson { get; set; } + // ── AI seats ───────────────────────────────────────────────────────────── + + /// + /// JSON array of AI-controlled slots in this lobby, managed by the host via + /// game.ai.add / game.ai.remove / game.ai.configure messages. + /// + /// Each element: { "accountId": "...", "seatIndex": N, "difficulty": N, "strategy": "..." } + /// + /// These entries participate in the normal AdditionalPlayersJson / GuestAccountId + /// slot assignment — the AI accounts are real DB rows. This field is purely + /// for the SOR.Ai layer to know which seats it controls. + /// + /// Null when no AI seats have been added. + /// + public string? AiSlotsJson { get; set; } + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Entities/Identity/Account.cs b/Server/src/SOR.Database/Entities/Identity/Account.cs index e5927b4..887702b 100644 --- a/Server/src/SOR.Database/Entities/Identity/Account.cs +++ b/Server/src/SOR.Database/Entities/Identity/Account.cs @@ -50,4 +50,22 @@ public sealed class Account : IdentityUser /// Use for bots, dev accounts, and internal test accounts. /// public bool IsHiddenFromLeaderboard { get; set; } + + // ── AI account fields ───────────────────────────────────────────────────── + + /// + /// True for AI-controlled virtual accounts (seeded by SOR.Ai at startup). + /// AI accounts are excluded from ranked matchmaking, leaderboards, and ELO updates. + /// They join custom lobbies as AI seats and submit game actions in-process. + /// + public bool IsAi { get; set; } + + /// AI difficulty tier (1–10). Null for human accounts. + public int? AiDifficulty { get; set; } + + /// + /// AI strategy archetype: "Aggressive" | "Control" | "Balanced" | "Ramp" | "Swarm". + /// Null for human accounts. + /// + public string? AiStrategy { get; set; } } diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index d7f2161..5027fd0 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -1,5 +1,36 @@ namespace SOR.Game; +// ── AI lobby requests / responses / pushes ──────────────────────────────────── + +/// Host adds an AI player to a custom lobby. +public sealed record GameAddAiRequest(Guid LobbyId, int Difficulty, string Strategy); +public sealed record GameAddAiResponse(Guid AiAccountId, string AiDisplayName, int SeatIndex); + +/// Host removes an AI player from a custom lobby. +public sealed record GameRemoveAiRequest(Guid LobbyId, Guid AiAccountId); +public sealed record GameRemoveAiResponse(bool Success); + +/// Host changes the difficulty or strategy of an existing AI slot. +public sealed record GameConfigureAiRequest(Guid LobbyId, Guid AiAccountId, + int? Difficulty, string? Strategy); +public sealed record GameConfigureAiResponse(bool Success); + +/// +/// Pushed to all lobby members when the AI slot list changes +/// (AI added, removed, or configured). +/// +public sealed record CustomLobbyAiSlotsChangedPush( + Guid LobbyId, + IReadOnlyList CurrentAiSlots); + +/// One AI seat in a custom lobby. +public sealed record AiSlotInfo( + Guid AccountId, + string DisplayName, + int Difficulty, + string Strategy, + int SeatIndex); + // ── Requests ───────────────────────────────────────────────────────────────── /// Signal that the player has loaded the game screen and is ready to start. diff --git a/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs b/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs index 9380481..f9352d2 100644 --- a/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs @@ -7,6 +7,8 @@ using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Transport; +using SOR.Shared; +using SOR.Shared.Nats; using SOR.Shared.Networking; /// @@ -22,6 +24,8 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler private readonly IClientPush _clientPush; private readonly IEventBus _eventBus; private readonly GameTurnTimerService _timerService; + // Optional: only present when SOR.Ai is loaded. Null when running without AI service. + private readonly IAiAccountRegistry? _aiRegistry; public GameEndTurnHandler( IMessageSerializer serializer, @@ -29,7 +33,8 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler SorIdentityDbContext identityDb, IClientPush clientPush, IEventBus eventBus, - GameTurnTimerService timerService) + GameTurnTimerService timerService, + IAiAccountRegistry? aiRegistry = null) { _serializer = serializer; _gameDb = gameDb; @@ -37,6 +42,7 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler _clientPush = clientPush; _eventBus = eventBus; _timerService = timerService; + _aiRegistry = aiRegistry; } public string MessageType => "game.end_turn"; @@ -103,6 +109,17 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler _timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, newState.Rules.TimeLimitMinutes, session.CreatedAt); + // If the newly active player is an AI seat, signal AiPlayerSessionManager to act. + if (_aiRegistry?.IsAi(newState.ActivePlayerAccountId) == true) + { + await _eventBus.PublishAsync(NatsSubjects.AiTurnStarted, + new AiTurnStartedEvent( + SessionId : session.Id, + AiAccountId : newState.ActivePlayerAccountId, + TurnNumber : newState.TurnNumber), + ct); + } + return ServerMessage.Reply("game.end_turn.ack", message.Seq, new GameEndTurnResponse(stateDto)); } diff --git a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs index 10a0b8b..c5973c2 100644 --- a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs @@ -7,9 +7,12 @@ using SOR.Game.Grid; using SOR.Database.Entities.Catalog; using SOR.Database.Entities.Collection; using SOR.Database.Enums; +using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Transport; +using SOR.Shared; +using SOR.Shared.Nats; using SOR.Shared.Networking; /// @@ -26,6 +29,9 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler private readonly CollectionDbContext _collectionDb; private readonly CatalogDbContext _catalogDb; private readonly IClientPush _clientPush; + private readonly IEventBus _eventBus; + // Optional: only present when SOR.Ai is loaded. + private readonly IAiAccountRegistry? _aiRegistry; public GameReadyHandler( IMessageSerializer serializer, @@ -33,7 +39,9 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler SorIdentityDbContext identityDb, CollectionDbContext collectionDb, CatalogDbContext catalogDb, - IClientPush clientPush) + IClientPush clientPush, + IEventBus eventBus, + IAiAccountRegistry? aiRegistry = null) { _serializer = serializer; _gameDb = gameDb; @@ -41,6 +49,8 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler _collectionDb = collectionDb; _catalogDb = catalogDb; _clientPush = clientPush; + _eventBus = eventBus; + _aiRegistry = aiRegistry; } public string MessageType => "game.ready"; @@ -227,6 +237,17 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler // Push initial state to both players. await PushStateToPlayersAsync(_clientPush, session, state, ct); + // If the first active player (Placement phase) is an AI seat, signal it to act. + if (_aiRegistry?.IsAi(state.ActivePlayerAccountId) == true) + { + await _eventBus.PublishAsync(NatsSubjects.AiTurnStarted, + new AiTurnStartedEvent( + SessionId : session.Id, + AiAccountId : state.ActivePlayerAccountId, + TurnNumber : state.TurnNumber), + ct); + } + return ServerMessage.Reply("game.ready.ack", message.Seq, new GameReadyResponse(session.Id, "Started")); } diff --git a/Server/src/SOR.Host/Program.cs b/Server/src/SOR.Host/Program.cs index c605e94..71fb69e 100644 --- a/Server/src/SOR.Host/Program.cs +++ b/Server/src/SOR.Host/Program.cs @@ -17,6 +17,7 @@ using SOR.Bazaar; using SOR.Chat; using SOR.Collection; using SOR.Content; +using SOR.Ai; using SOR.Game; using SOR.Gateway; using SOR.Matchmaking; @@ -178,6 +179,8 @@ if (IsEnabled("content")) builder.Services.AddContentService(builder.Configur if (IsEnabled("versioning")) builder.Services.AddVersioningService(builder.Configuration); if (IsEnabled("matchmaking")) builder.Services.AddMatchmakingService(builder.Configuration); if (IsEnabled("game")) builder.Services.AddGameService(builder.Configuration); +// AI is always co-located with game: it invokes game handlers in-process. +if (IsEnabled("game")) builder.Services.AddAiService(builder.Configuration); if (IsEnabled("support")) builder.Services.AddSupportService(builder.Configuration); // ── BUILD ───────────────────────────────────────────────────────────────────── diff --git a/Server/src/SOR.Host/SOR.Host.csproj b/Server/src/SOR.Host/SOR.Host.csproj index 9584bd8..17737be 100644 --- a/Server/src/SOR.Host/SOR.Host.csproj +++ b/Server/src/SOR.Host/SOR.Host.csproj @@ -42,6 +42,7 @@ + diff --git a/Server/src/SOR.Shared/IAiAccountRegistry.cs b/Server/src/SOR.Shared/IAiAccountRegistry.cs new file mode 100644 index 0000000..7216d81 --- /dev/null +++ b/Server/src/SOR.Shared/IAiAccountRegistry.cs @@ -0,0 +1,20 @@ +namespace SOR.Shared; + +/// +/// Provides O(1) lookup for whether an account ID belongs to an AI-controlled virtual player. +/// +/// Defined in SOR.Shared so that SOR.Game can depend on it without creating a circular +/// reference to SOR.Ai (which itself references SOR.Game). +/// +/// Implemented by SOR.Ai.Core.AiAccountRegistry and registered as a singleton in +/// SOR.Host when the AI service is enabled. Injected as optional (nullable) in game +/// handlers so the game service works correctly even without SOR.Ai running. +/// +public interface IAiAccountRegistry +{ + /// Returns true if the string account ID belongs to an AI account. + bool IsAi(string accountId); + + /// Returns true if the Guid account ID belongs to an AI account. + bool IsAi(Guid accountId); +} diff --git a/Server/src/SOR.Shared/Nats/NatsEvents.cs b/Server/src/SOR.Shared/Nats/NatsEvents.cs index a18aa3a..7d5b897 100644 --- a/Server/src/SOR.Shared/Nats/NatsEvents.cs +++ b/Server/src/SOR.Shared/Nats/NatsEvents.cs @@ -11,3 +11,12 @@ public sealed record GameEndedEvent( Guid LoserId, int DurationSeconds, DateTimeOffset EndedAt); + +/// +/// Published by GameEndTurnHandler when the turn advances to an AI-controlled seat. +/// Consumed by AiPlayerSessionManager to kick off the AI's turn. +/// +public sealed record AiTurnStartedEvent( + Guid SessionId, + string AiAccountId, + int TurnNumber); diff --git a/Server/src/SOR.Shared/Nats/NatsSubjects.cs b/Server/src/SOR.Shared/Nats/NatsSubjects.cs index a703156..eb5dee9 100644 --- a/Server/src/SOR.Shared/Nats/NatsSubjects.cs +++ b/Server/src/SOR.Shared/Nats/NatsSubjects.cs @@ -58,6 +58,16 @@ public static class NatsSubjects /// public const string LeaderboardMatchRated = "sor.leaderboard.match.rated"; + // ── AI ──────────────────────────────────────────────────────────────────── + + /// + /// Published by Game service (GameEndTurnHandler) when the turn advances to an + /// AI-controlled seat. Consumed by SOR.Ai (AiPlayerSessionManager) to trigger + /// the AI's turn execution. + /// Payload: AiTurnStartedEvent { SessionId, AiAccountId, TurnNumber } + /// + public const string AiTurnStarted = "sor.ai.turn_started"; + // ── Admin ───────────────────────────────────────────────────────────────── ///