#pragma warning disable CS0618 // AbilitySystem is the authorized reader of obsolete Actions/Cost fields for backwards-compat migration
namespace SOR.Game.Abilities;
using System.Text.Json;
using SOR.Database.Enums;
using SOR.Game.Abilities.Models;
using SOR.Game.Grid;
///
/// Evaluates and resolves ability activations and triggered ability firings.
///
/// Design:
/// • GameEngine delegates directly to the static methods here.
/// • All mutation is on GameState (pure — no DB access).
/// • Triggered abilities are fired inline during engine mutations via FireTrigger.
///
public static class AbilitySystem
{
// ── JSON options ───────────────────────────────────────────────────────────
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
Converters =
{
new System.Text.Json.Serialization.JsonStringEnumConverter(),
// Handle polymorphic deserialization when $type is not the first property.
// The default [JsonPolymorphic] behavior requires $type first for abstract
// base types; admin-tool JSON does not guarantee that ordering.
new EffectPolymorphicConverter(),
new ConditionPolymorphicConverter(),
new TriggerPolymorphicConverter(),
new FilterPolymorphicConverter(),
},
};
// Runtime limiter for Triggered abilities: (source instance, ability key, turn) -> count
private static readonly Dictionary<(string SourceInstanceId, string AbilityKey, int Turn), int> _triggerCountsPerTurn = new();
// Per-game trigger limiter: (session+source instance, ability key) -> count; never resets mid-game
private static readonly Dictionary<(string SessionAndSource, string AbilityKey), int> _triggerCountsPerGame = new();
// Transient prevention markers.
private static readonly Dictionary _preventNextDamageByUnit = new();
private static readonly HashSet _preventDeathUnits = new();
// Top-level ability/action sequence depth for UntilEndOfSequence cleanup.
private static int _sequenceDepth = 0;
// ── JSON options (public factory for tooling) ─────────────────────────────
/// Returns the same JsonSerializerOptions used by the ability engine. Used by SOR.Tools.
public static JsonSerializerOptions CreateJsonOptions() => new()
{
PropertyNameCaseInsensitive = true,
Converters =
{
new System.Text.Json.Serialization.JsonStringEnumConverter(),
new EffectPolymorphicConverter(),
new ConditionPolymorphicConverter(),
new TriggerPolymorphicConverter(),
new FilterPolymorphicConverter(),
},
};
// ── Parsing ────────────────────────────────────────────────────────────────
public static AbilityDefinition[] ParseAbilities(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
return JsonSerializer.Deserialize(json, _jsonOpts) ?? [];
}
public static Models.Action[] ParseEffects(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
return JsonSerializer.Deserialize(json, _jsonOpts) ?? [];
}
// ── Active ability activation ──────────────────────────────────────────────
///
/// Entry point for a player manually activating an Active ability on one of
/// their units. Validates conditions, pays cost, resolves targets and effects.
///
public static GameState ActivateAbility(
GameState state,
string actorId,
string sourceInstanceId,
int abilityIndex,
IReadOnlyList? clientTargets)
{
var player = state.Players[actorId];
// ArchSpirit is stored in player.ArchSpirit, not player.Field — check both.
var source = player.Field.OfType()
.FirstOrDefault(f => f.InstanceId == sourceInstanceId)
?? (player.ArchSpirit?.InstanceId == sourceInstanceId ? player.ArchSpirit : null)
?? throw new GameException("UNIT_NOT_FOUND");
if (source.IsExhausted)
throw new GameException("UNIT_EXHAUSTED");
if (!source.CanUseAbility)
throw new GameException("UNIT_CANNOT_USE_ABILITY");
var abilities = ParseAbilities(source.AbilitiesJson);
if (abilityIndex < 0 || abilityIndex >= abilities.Length)
throw new GameException("ABILITY_INDEX_OUT_OF_RANGE");
var def = abilities[abilityIndex];
if (def.Type != AbilityType.Active)
throw new GameException("ABILITY_NOT_ACTIVE");
if (def.Name is not null && source.DisabledAbilities?.Contains(def.Name) == true)
throw new GameException("ABILITY_DISABLED");
source.AbilityUsesThisTurn ??= new();
source.AbilityUsesThisTurn.TryGetValue(abilityIndex, out int usedThisTurn);
if (usedThisTurn >= def.UsesPerTurn)
throw new GameException("ABILITY_USES_EXHAUSTED");
var ctx = new AbilityContext { State = state, ActorId = actorId, Source = source };
// Source-side activation conditions are shared with card-active execution.
if (!ValidateSourceActivationConditions(def, ctx, source))
throw new GameException("ABILITY_CONDITION_NOT_MET");
// Pre-validate client tile targets against effect-level TileFilters BEFORE
// incrementing the use count or paying any costs, so a bad pick wastes nothing.
PreValidateClientTileTargets(def, clientTargets, ctx);
source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1;
var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex, def.Range, def.Duration);
// GetEffectiveActions returns null when it emitted PendingActionGroupPick (OR/XOR, interactive).
if (effectiveActions is null) return state;
if (def.CostGroup is { } cg)
{
bool paused = PayCostGroup(cg, ctx, abilityIndex, effectiveActions, def.Range, def.Duration);
if (paused) return state;
}
else if (def.Cost is { Length: > 0 })
{
bool paused = PayCosts(def.Cost, ctx, abilityIndex, effectiveActions, def.Range, def.Duration);
if (paused) return state; // waiting for client cost pick
}
ExecuteActions(effectiveActions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration);
return state;
}
// ── Triggered ability firing ───────────────────────────────────────────────
///
/// Resolve the AbilitiesJson active ability list on a non-unit card (Repentance, Instinct)
/// immediately when it is channeled. The card itself is the source in the context.
///
public static GameState FireCardEffects(GameState state, string actorId, CardInstance card,
IReadOnlyList? clientTargets = null)
{
var activeDefs = ParseAbilities(card.AbilitiesJson)
.Where(d => d.Type == AbilityType.Active)
.ToList();
foreach (var def in activeDefs)
{
var ctx = new AbilityContext { State = state, ActorId = actorId, Source = card };
if (!ValidateSourceActivationConditions(def, ctx, card))
continue;
var cardActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration);
if (cardActions is null) continue; // paused for interactive ActionGroup pick
ExecuteActions(cardActions, ctx, clientTargets, requireClientTargets: true,
activationRange: def.Range, forceDuration: def.Duration);
}
return state;
}
private static bool ValidateSourceActivationConditions(
AbilityDefinition def,
AbilityContext ctx,
object sourceSubject)
{
if (def.ActivationConditions is not { Length: > 0 })
return true;
foreach (var cond in def.ActivationConditions.Where(c => c.Subject != "Target"))
if (!EvaluateCondition(cond, ctx, sourceSubject))
return false;
return true;
}
///
/// Checks client-supplied tile targets against any effect-level TileFilter constraints
/// (e.g. ). Called before the use-count is
/// incremented and before costs are paid, so a rejected pick costs the player nothing.
///
private static void PreValidateClientTileTargets(
AbilityDefinition def,
IReadOnlyList? clientTargets,
AbilityContext ctx)
{
if (clientTargets is null || ctx.State.Board is null) return;
// Iterate the flat action list in the top-level AND group (the common case).
// OR/XOR groups with pending interactive picks are handled after the pick resolves
// and never reach this path with client-provided tile coords.
var actions = def.ActionGroup?.Actions ?? def.Actions ?? [];
for (int ai = 0; ai < actions.Length; ai++)
{
var action = actions[ai];
if (action.Target.Type != TargetType.Tile) continue;
foreach (var effect in action.Effects)
{
if (effect is not SummonTokenEffect ste || ste.TileFilter is not { Length: > 0 }) continue;
var ct = clientTargets.FirstOrDefault(t => t.ActionIndex == ai && t.Coord is not null);
if (ct is null) continue;
var coord = new Coord(ct.Coord!.X, ct.Coord!.Y);
var tile = ctx.State.Board.GetTile(coord);
if (tile is null || !TileMatchesFilters(ste.TileFilter, tile, ctx))
throw new GameException("INVALID_TILE");
}
}
}
///
/// Scans every battlefield unit (and, when SourceZoneGate is set, hand/discard/deck cards)
/// for Triggered abilities matching the occurrence and fires each matching one.
/// Called inline from GameEngine mutation methods.
///
public static GameState FireTrigger(GameState state, TriggerOccurrence occurrence)
{
foreach (var (ownerId, player) in state.Players)
{
// Build the set of cards to scan for triggered abilities.
// Always include battlefield units. Cards with SourceZoneGate including
// Hand/Discard/Deck are scanned from those zones too.
var scanTargets = new List<(CardInstance Card, string Zone)>();
foreach (var fc in player.Field.OfType())
scanTargets.Add((fc, "Battlefield"));
foreach (var c in player.Hand)
scanTargets.Add((c, "Hand"));
foreach (var c in player.Discard)
scanTargets.Add((c, "Discard"));
foreach (var c in player.Deck)
scanTargets.Add((c, "Deck"));
foreach (var (card, zone) in scanTargets)
{
// SetCanUseAbility(false) suppresses triggered ability firing.
if (card is FieldCard fc2 && !fc2.CanUseAbility) continue;
var abilities = ParseAbilities(card.AbilitiesJson);
for (int i = 0; i < abilities.Length; i++)
{
var def = abilities[i];
if (def.Type != AbilityType.Triggered) continue;
if (def.TriggerEvent is null) continue;
// ── SourceZoneGate ────────────────────────────────────────
// When a gate is configured, only fire when the card is in one of the
// specified zones. When no gate is configured, apply the legacy rule:
// only battlefield cards fire (skip non-battlefield cards).
if (def.SourceZoneGate is { Length: > 0 })
{
if (!def.SourceZoneGate.Contains(zone, StringComparer.OrdinalIgnoreCase))
continue;
}
else
{
// No gate → legacy: only battlefield cards trigger.
if (zone != "Battlefield") continue;
}
if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId,
card is FieldCard fc3 ? fc3 : null)) continue;
// 6-D: Prevent double-firing the source Ruin's own OnRuinActivation abilities.
// FireRuinAbilities already executed one chosen ability directly; the subsequent
// FireTrigger call is only for observer cards. Skip the source Ruin itself.
if (occurrence.Kind == TriggerEventKind.RuinActivation
&& def.TriggerEvent is OnRuinActivationTrigger
&& card.InstanceId == occurrence.Data?.SourceId)
continue;
var ctx = new AbilityContext
{
State = state,
ActorId = ownerId,
Source = card,
EventData = occurrence.Data,
};
if (def.ActivationConditions is { Length: > 0 })
if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, card)))
continue;
// ── Per-turn limit ────────────────────────────────────────
if (def.TriggerLimitPerTurn is > 0)
{
var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}";
var key = (card.InstanceId, abilityKey, state.TurnNumber);
_triggerCountsPerTurn.TryGetValue(key, out var used);
if (used >= def.TriggerLimitPerTurn.Value)
continue;
_triggerCountsPerTurn[key] = used + 1;
}
// ── Per-game limit ────────────────────────────────────────
if (def.TriggerLimitPerGame is > 0)
{
var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}";
var gameKey = ($"{state.SessionId}:{card.InstanceId}", abilityKey);
_triggerCountsPerGame.TryGetValue(gameKey, out var usedGame);
if (usedGame >= def.TriggerLimitPerGame.Value)
continue;
_triggerCountsPerGame[gameKey] = usedGame + 1;
}
// If any action needs a human pick, pause and request client input.
var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration) ?? [];
var pickAction = Array.Find(effectiveActions, ActionNeedsClientTargets);
if (pickAction is not null)
{
// Determine which player must actually submit the target picks.
// For Chooser.Opponent/Ally, route the request to the non-activating player.
string chooserActorId = pickAction.Target.Chooser switch
{
TargetChooser.Opponent =>
state.GetEnemyIds(ownerId).FirstOrDefault() ?? ownerId,
TargetChooser.Ally =>
state.Players.Values
.FirstOrDefault(p => p.AccountId != ownerId
&& state.AreAllies(p.AccountId, ownerId))
?.AccountId ?? ownerId,
_ => ownerId, // Self or default
};
state.PendingTriggeredTarget = new PendingTriggeredTarget
{
ActorId = ownerId,
ChooserActorId = chooserActorId,
SourceInstanceId = card.InstanceId,
AbilityName = def.Name ?? "Triggered Ability",
ActionsJson = JsonSerializer.Serialize(effectiveActions, _jsonOpts),
RangeJson = def.Range is not null
? JsonSerializer.Serialize(def.Range, _jsonOpts)
: null,
ForceDurationJson = def.Duration is not null
? JsonSerializer.Serialize(def.Duration, _jsonOpts)
: null,
};
// Return immediately — only one pending request at a time.
return state;
}
ExecuteActions(effectiveActions, ctx, clientTargets: null, forceDuration: def.Duration);
}
}
}
// ── Check pending deferred effects ────────────────────────────────────
var toFire = state.PendingDeferredEffects
.Where(p =>
{
TriggerEvent? t;
try { t = JsonSerializer.Deserialize(p.TriggerJson, _jsonOpts); }
catch { return false; }
return t is not null && TriggerMatches(t, occurrence, state, p.OwnerAccountId);
})
.ToList();
foreach (var pending in toFire)
{
state.PendingDeferredEffects.Remove(pending);
var dSrc = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var dCtx = new AbilityContext { State = state, ActorId = pending.OwnerAccountId, Source = dSrc };
// Pre-seed the deferred target as action-0 resolved target so chained
// actions inside the deferred tree can reference it.
var tgt = FindDeferredTarget(state, pending.TargetRef);
if (tgt is not null)
dCtx.ResolvedTargets[0] = [tgt];
// Prefer ActionGroupJson (full recursive tree) over legacy flat ActionsJson.
if (pending.ActionGroupJson is not null)
{
Models.ActionGroup? ag;
try { ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts); }
catch { continue; }
if (ag is null) continue;
var resolved = ResolveActionGroup(ag, dCtx, abilityIndex: 0,
range: null, forceDuration: null, continuationActions: []);
if (resolved is not null)
ExecuteActions(resolved, dCtx, clientTargets: null, requireClientTargets: false);
}
else
{
Models.Action[]? deferredActions;
try { deferredActions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts); }
catch { continue; }
if (deferredActions is null || deferredActions.Length == 0) continue;
ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false);
}
}
return state;
}
private static object? FindDeferredTarget(GameState state, string targetRef)
{
foreach (var player in state.Players.Values)
{
var ci = (CardInstance?)(
player.Field.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Hand.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Deck.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Discard.FirstOrDefault(c => c.InstanceId == targetRef));
if (ci is not null) return ci;
if (player.AccountId == targetRef) return player;
}
return null;
}
///
/// At the start of each turn: for every Ruin on the battlefield whose tile is occupied
/// by a Spirit or ArchSpirit, pick ONE of the Ruin's OnRuinActivationTrigger abilities
/// at random and execute it. Then fire RuinActivation for any observer cards.
///
public static GameState FireRuinAbilities(GameState state)
{
foreach (var (ownerId, player) in state.Players)
{
var ruins = player.Field
.OfType()
.Where(c => c.CardType == "Ruin" && c.Position.HasValue)
.ToList();
foreach (var ruin in ruins)
{
var tile = state.Board?.GetTile(ruin.Position!.Value);
if (tile?.OccupantId is null) continue;
// Skip if this ruin is disabled by DisableRuinForDurationEffect.
if (tile.RuinDisabledUntilTurn > 0 && state.TurnNumber <= tile.RuinDisabledUntilTurn)
continue;
// Only fires if a Spirit or ArchSpirit is on the tile.
var occupantType = FindUnitType(state, tile.OccupantId);
if (occupantType is not ("Spirit" or "ArchSpirit" or "SpiritToken")) continue;
var abilities = ParseAbilities(ruin.AbilitiesJson);
var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = ruin };
var eligible = abilities
.Where(a => a.Type == AbilityType.Triggered
&& a.TriggerEvent is OnRuinActivationTrigger)
.Where(a => a.ActivationConditions is not { Length: > 0 }
|| a.ActivationConditions.All(c => EvaluateCondition(c, ctx, ruin)))
.ToList();
if (eligible.Count == 0) continue;
// Select exactly one ability at random.
var chosen = eligible[Random.Shared.Next(eligible.Count)];
var chosenActions = GetEffectiveActions(chosen, ctx, abilityIndex: 0, chosen.Range, chosen.Duration);
if (chosenActions is not null)
ExecuteActions(chosenActions, ctx, clientTargets: null);
// Notify observer cards that the ruin activated.
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.RuinActivation,
ActorId = ownerId,
Data = new TriggerEventData
{
SourceId = ruin.InstanceId,
TargetId = tile.OccupantId,
},
});
}
}
return state;
}
private static string? FindUnitType(GameState state, string instanceId)
{
foreach (var player in state.Players.Values)
{
var c = player.Field.FirstOrDefault(x => x.InstanceId == instanceId)
?? player.ArchSpirit as CardInstance;
if (c?.InstanceId == instanceId) return c.CardType;
}
return null;
}
// ── Cost payment ──────────────────────────────────────────────────────────
///
/// Pays all costs in that can be auto-resolved.
/// When an interactive pick-mode cost is encountered, stores
/// on .State and returns true (caller must stop and return state).
/// Returns false when all costs are paid without pausing.
///
private static bool PayCosts(
CostEntry[] costs,
AbilityContext ctx,
int abilityIndex,
Models.Action[] pendingActions,
AbilityRange? range,
DurationModel? forceDuration)
{
var player = ctx.State.Players[ctx.ActorId];
for (int ci = 0; ci < costs.Length; ci++)
{
var cost = costs[ci];
// Interactive costs: pause for player pick.
if (cost.PickMode is CostPickMode.SelfPick or CostPickMode.EnemySeePick
or CostPickMode.EnemyRandomPick or CostPickMode.EnemyPick)
{
// Only DiscardFromHand / SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit
// support interactive pick. Auto-resolve all others even if PickMode is set.
if (cost.Type is CostType.DiscardFromHand
or CostType.SendSpiritFromBattlefieldToDiscard
or CostType.DealDamageToOwnSpirit)
{
// Determine who picks.
var pickerActorId = cost.PickMode is CostPickMode.SelfPick
? ctx.ActorId
: ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId;
// Remaining costs after this one.
var remaining = costs.Skip(ci + 1).ToArray();
// Compute candidates: the actor's eligible cards for this cost type.
IEnumerable rawCandidates = cost.Type switch
{
CostType.DiscardFromHand =>
player.Hand,
CostType.SendSpiritFromBattlefieldToDiscard =>
player.Field.OfType().Where(f => f.CardType == "Spirit").Cast(),
CostType.DealDamageToOwnSpirit =>
player.Field.OfType().Where(f => f.CardType == "Spirit").Cast(),
_ => Enumerable.Empty()
};
// Apply cost filters so only eligible cards are offered to the picker.
var filteredCandidates = cost.Filters is not null && cost.Filters.Length > 0
? rawCandidates.Where(c => FiltersMatch(cost.Filters, c, ctx))
: rawCandidates;
var candidateItems = filteredCandidates
.Select(c => new { instanceId = c.InstanceId, name = c.Name, cardType = c.CardType })
.ToArray();
ctx.State.PendingCostPick = new PendingCostPick
{
ActorId = ctx.ActorId,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
AbilityIndex = abilityIndex,
PickerActorId = pickerActorId,
CostType = cost.Type.ToString(),
Amount = cost.Amount,
PickMode = cost.PickMode.ToString()!,
FiltersJson = cost.Filters is not null
? JsonSerializer.Serialize(cost.Filters, _jsonOpts) : null,
RemainingCostsJson = JsonSerializer.Serialize(remaining, _jsonOpts),
ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts),
RangeJson = range is not null
? JsonSerializer.Serialize(range, _jsonOpts) : null,
ForceDurationJson = forceDuration is not null
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
CandidatesJson = JsonSerializer.Serialize(candidateItems),
};
return true; // paused
}
}
// Auto-resolve the cost.
PaySingleCost(cost, player, ctx);
}
return false; // all paid
}
///
/// Pays a CostGroup.
/// AND: recursively pays all entries and sub-groups; pauses on first interactive cost.
/// OR/XOR + Random: picks one child (entry or sub-group) at random and pays it.
/// OR/XOR + Self/Opponent: stores and returns true.
/// Returns true when paused (caller must stop and return state).
///
private static bool PayCostGroup(
CostGroup group,
AbilityContext ctx,
int abilityIndex,
Models.Action[] pendingActions,
AbilityRange? range,
DurationModel? forceDuration)
{
if (group.LogicOp == CostGroupLogicOp.And)
{
// Pay all leaf entries.
if (group.Entries.Length > 0)
{
bool paused = PayCosts(group.Entries, ctx, abilityIndex, pendingActions, range, forceDuration);
if (paused) return true;
}
// Recurse into sub-groups.
foreach (var child in group.Groups)
{
bool paused = PayCostGroup(child, ctx, abilityIndex, pendingActions, range, forceDuration);
if (paused) return true;
}
return false;
}
// OR / XOR: combined pool = leaf entry sets + nested groups
int entryCount = group.Entries.Length;
int groupCount = group.Groups.Length;
int total = entryCount + groupCount;
if (total == 0) return false;
if (group.ChooserRole == "Random")
{
int idx = Random.Shared.Next(total);
if (idx < entryCount)
{
PaySingleCost(group.Entries[idx], ctx.State.Players[ctx.ActorId], ctx);
return false;
}
return PayCostGroup(group.Groups[idx - entryCount], ctx, abilityIndex,
pendingActions, range, forceDuration);
}
// Self or Opponent: pause for interactive pick.
var chooserActorId = group.ChooserRole == "Opponent"
? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId
: ctx.ActorId;
ctx.State.PendingCostGroupPick = new PendingCostGroupPick
{
ActorId = ctx.ActorId,
ChooserActorId = chooserActorId,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
AbilityIndex = abilityIndex,
CostGroupJson = JsonSerializer.Serialize(group, _jsonOpts),
ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts),
RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null,
ForceDurationJson = forceDuration is not null
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
};
return true; // paused
}
///
/// Resumes execution after the chooser has responded to a game.cost_group_pick.
///
public static GameState ResumeCostGroupPick(
GameState state,
string actorId,
string requestId,
int choiceIndex)
{
var pending = state.PendingCostGroupPick
?? throw new GameException("NO_PENDING_COST_GROUP_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
if (actorId != pending.ActorId && actorId != pending.ChooserActorId)
throw new GameException("NOT_YOUR_COST_GROUP_PICK");
state.PendingCostGroupPick = null;
var group = JsonSerializer.Deserialize(pending.CostGroupJson, _jsonOpts)
?? throw new GameException("INVALID_COST_GROUP_STATE");
int entryCount = group.Entries.Length;
int groupCount = group.Groups.Length;
int total = entryCount + groupCount;
if (choiceIndex < 0 || choiceIndex >= total)
throw new GameException("INVALID_COST_GROUP_CHOICE");
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
if (source is null) return state;
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
var player = state.Players[pending.ActorId];
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
var actions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts) ?? [];
if (choiceIndex < entryCount)
{
// Pay the chosen leaf entry.
PaySingleCost(group.Entries[choiceIndex], player, ctx);
}
else
{
// Recursively pay the chosen nested group (AND-only for now; nested OR/XOR would recurse further).
bool paused = PayCostGroup(group.Groups[choiceIndex - entryCount], ctx,
pending.AbilityIndex, actions, range, forceDuration);
if (paused) return state;
}
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false,
activationRange: range, forceDuration: forceDuration);
return state;
}
private static void PaySingleCost(CostEntry cost, PlayerState player, AbilityContext ctx)
{
switch (cost.Type)
{
case CostType.SpiritPoints:
if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP");
player.CurrentSp -= cost.Amount;
break;
case CostType.SacrificeTokens:
if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST");
player.CurrentSt -= cost.Amount;
break;
case CostType.DiscardFromHand:
{
var pool = player.Hand
.Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx))
.ToList();
if (cost.PickMode == CostPickMode.Random)
pool = pool.OrderBy(_ => Random.Shared.Next()).ToList();
var candidates = pool.Take(cost.Amount).ToList();
if (candidates.Count < cost.Amount)
throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD");
foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); }
break;
}
case CostType.MillTopOfDeck:
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
{
var top = player.Deck[^1];
player.Deck.RemoveAt(player.Deck.Count - 1);
player.Discard.Add(top);
}
break;
case CostType.MillBottomOfDeck:
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
{
var bottom = player.Deck[0];
player.Deck.RemoveAt(0);
player.Discard.Add(bottom);
}
break;
case CostType.DealDamageToOwnArchSpirit:
if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT");
ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx);
break;
case CostType.DealDamageToOwnSpirit:
{
var spirit = player.Field.OfType()
.FirstOrDefault(f => !f.IsLeader
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx);
break;
}
case CostType.SendSpiritFromBattlefieldToDiscard:
{
var spirit = player.Field.OfType()
.FirstOrDefault(f => !f.IsLeader
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
ctx.State.Board?.RemoveUnit(spirit.InstanceId);
player.Field.Remove(spirit);
player.Discard.Add(spirit);
break;
}
}
}
///
/// Resumes an Active ability after the picker has submitted their cost-pick selections.
/// Called by GameCostPickHandler.
///
public static GameState ResumeCostPick(
GameState state,
string actorId,
string requestId,
IReadOnlyList selectedInstanceIds)
{
var pending = state.PendingCostPick
?? throw new GameException("NO_PENDING_COST_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
// Allow both the actor and the designated picker to respond.
if (actorId != pending.ActorId && actorId != pending.PickerActorId)
throw new GameException("NOT_YOUR_COST_PICK");
state.PendingCostPick = null;
var player = state.Players[pending.ActorId];
// Resolve source early so the filter context can evaluate source-relative filters
// (IsSelf, IsAdjacentToSource, etc.). Source may have left the field — that's OK;
// those spatial filters simply return false and thus never apply to hand/field cost picks.
var earlySource = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var filterCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = earlySource };
var pickFilters = pending.FiltersJson is not null
? JsonSerializer.Deserialize(pending.FiltersJson, _jsonOpts)
: null;
// Validate and pay the interactive cost using the client-selected IDs.
switch (pending.CostType)
{
case nameof(CostType.DiscardFromHand):
{
var toDiscard = selectedInstanceIds
.Select(id => player.Hand.FirstOrDefault(c => c.InstanceId == id))
.OfType()
.Take(pending.Amount)
.ToList();
if (toDiscard.Count < pending.Amount)
throw new GameException("INVALID_COST_PICK_SELECTION");
if (pickFilters is not null && toDiscard.Any(c => !FiltersMatch(pickFilters, c, filterCtx)))
throw new GameException("INVALID_COST_PICK_SELECTION");
foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); }
break;
}
case nameof(CostType.SendSpiritFromBattlefieldToDiscard):
{
var picked = selectedInstanceIds.FirstOrDefault()
?? throw new GameException("INVALID_COST_PICK_SELECTION");
var spirit = player.Field.OfType()
.FirstOrDefault(f => f.InstanceId == picked)
?? throw new GameException("INVALID_COST_PICK_SELECTION");
if (pickFilters is not null && !FiltersMatch(pickFilters, spirit, filterCtx))
throw new GameException("INVALID_COST_PICK_SELECTION");
state.Board?.RemoveUnit(spirit.InstanceId);
player.Field.Remove(spirit);
player.Discard.Add(spirit);
break;
}
case nameof(CostType.DealDamageToOwnSpirit):
{
var picked = selectedInstanceIds.FirstOrDefault()
?? throw new GameException("INVALID_COST_PICK_SELECTION");
var spirit = player.Field.OfType()
.FirstOrDefault(f => f.InstanceId == picked)
?? throw new GameException("INVALID_COST_PICK_SELECTION");
if (pickFilters is not null && !FiltersMatch(pickFilters, spirit, filterCtx))
throw new GameException("INVALID_COST_PICK_SELECTION");
// Temporary context for damage application.
var dmgCtx = new AbilityContext { State = state, ActorId = pending.ActorId };
ApplyDamageToUnit(spirit, pending.Amount, bypassDefense: false, dmgCtx);
break;
}
}
// Find the source unit (may have left the field while waiting — skip if gone).
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
if (source is null) return state;
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
// Pay any remaining non-interactive costs.
var remainingCosts = JsonSerializer.Deserialize(
pending.RemainingCostsJson, _jsonOpts) ?? [];
foreach (var c in remainingCosts)
PaySingleCost(c, player, ctx);
// Execute the ability actions.
var actions = JsonSerializer.Deserialize(
pending.ActionsJson, _jsonOpts) ?? [];
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts)
: null;
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts)
: null;
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false,
activationRange: range, forceDuration: forceDuration);
return state;
}
///
/// Resumes execution after the chooser has responded to a game.branch_pick.
///
public static GameState ResumeBranchPick(
GameState state,
string actorId,
string requestId,
int branchIndex)
{
var pending = state.PendingBranchPick
?? throw new GameException("NO_PENDING_BRANCH_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
if (actorId != pending.ActorId && actorId != pending.ChooserActorId)
throw new GameException("NOT_YOUR_BRANCH_PICK");
if (branchIndex < 0 || branchIndex >= pending.BranchCount)
throw new GameException("INVALID_BRANCH_INDEX");
state.PendingBranchPick = null;
var branches = JsonSerializer.Deserialize(pending.BranchesJson, _jsonOpts) ?? [];
var continuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
var allActions = branches[branchIndex].Actions.Concat(continuation).ToArray();
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false,
activationRange: range, forceDuration: forceDuration);
return state;
}
// ── ActionGroup resolution ────────────────────────────────────────────────
///
/// Returns the flat action list to execute for an ability.
/// AND groups are flattened recursively (leaves + nested group leaves).
/// OR/XOR + Random: picks one child (action or nested group) server-side.
/// OR/XOR + Self/Opponent: emits , returns null (caller must pause).
/// Falls back to for pre-Phase-1 data.
///
private static Models.Action[]? GetEffectiveActions(
AbilityDefinition def,
AbilityContext ctx,
int abilityIndex,
AbilityRange? range,
DurationModel? forceDuration)
{
if (def.ActionGroup is { } ag)
return ResolveActionGroup(ag, ctx, abilityIndex, range, forceDuration,
continuationActions: []);
return def.Actions; // backward-compat: pre-Phase-1 rows use the flat array
}
///
/// Recursively resolves an ActionGroup into a flat action list.
/// Returns null when the group is interactive (OR/XOR + Self/Opponent) and
/// has been stored.
///
private static Models.Action[]? ResolveActionGroup(
ActionGroup ag,
AbilityContext ctx,
int abilityIndex,
AbilityRange? range,
DurationModel? forceDuration,
Models.Action[] continuationActions)
{
if (ag.LogicOp == ActionGroupLogicOp.And)
{
// AND: run leaves then recurse into nested groups, flattening all.
var all = new List(ag.Actions);
for (int gi = 0; gi < ag.Groups.Length; gi++)
{
var childActions = ResolveActionGroup(ag.Groups[gi], ctx, abilityIndex, range,
forceDuration, continuationActions);
if (childActions is null)
{
// Child emitted PendingActionGroupPick. Patch it:
// - Store preceding actions (all actions resolved so far in this AND group)
// so resume can execute them BEFORE the chosen branch.
// - Store remaining sibling groups.
// - Leave ContinuationActionsJson untouched (it already carries the outer
// continuation that was passed into this recursive call).
if (ctx.State.PendingActionGroupPick is { } pend)
{
// An inner AND group may have already set PrecedingActionsJson.
// Prepend our own `all` to whatever the inner group stored.
var innerPreceding = pend.PrecedingActionsJson is not null
? JsonSerializer.Deserialize(pend.PrecedingActionsJson, _jsonOpts) ?? []
: [];
pend.PrecedingActionsJson = JsonSerializer.Serialize(
all.Concat(innerPreceding).ToArray(), _jsonOpts);
var remaining = ag.Groups.Skip(gi + 1).ToArray();
if (remaining.Length > 0)
pend.RemainingGroupsJson = JsonSerializer.Serialize(remaining, _jsonOpts);
}
return null;
}
all.AddRange(childActions);
}
return all.ToArray();
}
// OR / XOR: combined pool = leaf actions + nested groups
int leafCount = ag.Actions.Length;
int groupCount = ag.Groups.Length;
int total = leafCount + groupCount;
if (total == 0) return [];
if (ag.ChooserRole == "Random")
{
int idx = Random.Shared.Next(total);
if (idx < leafCount)
return [ag.Actions[idx]];
return ResolveActionGroup(ag.Groups[idx - leafCount], ctx, abilityIndex,
range, forceDuration, continuationActions);
}
// Self or Opponent: pause for interactive pick.
var chooserActorId = ag.ChooserRole == "Opponent"
? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId
: ctx.ActorId;
ctx.State.PendingActionGroupPick = new PendingActionGroupPick
{
ActorId = ctx.ActorId,
ChooserActorId = chooserActorId,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
ActionGroupJson = JsonSerializer.Serialize(ag, _jsonOpts),
ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts),
RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null,
ForceDurationJson = forceDuration is not null
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
};
return null; // paused
}
///
/// Resumes execution after the chooser has responded to a game.action_group_pick.
///
public static GameState ResumeActionGroupPick(
GameState state,
string actorId,
string requestId,
int choiceIndex)
{
var pending = state.PendingActionGroupPick
?? throw new GameException("NO_PENDING_ACTION_GROUP_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
if (actorId != pending.ActorId && actorId != pending.ChooserActorId)
throw new GameException("NOT_YOUR_ACTION_GROUP_PICK");
state.PendingActionGroupPick = null;
var ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts)
?? throw new GameException("INVALID_ACTION_GROUP_STATE");
int leafCount = ag.Actions.Length;
int groupCount = ag.Groups.Length;
int total = leafCount + groupCount;
if (choiceIndex < 0 || choiceIndex >= total)
throw new GameException("INVALID_ACTION_GROUP_CHOICE");
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
var continuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
// Actions that ran before the pause in a parent AND group.
// These must execute BEFORE the chosen branch to preserve AND-group order.
var preceding = pending.PrecedingActionsJson is not null
? JsonSerializer.Deserialize(pending.PrecedingActionsJson, _jsonOpts) ?? []
: System.Array.Empty();
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
Models.Action[]? chosen;
if (choiceIndex < leafCount)
{
chosen = [ag.Actions[choiceIndex]];
}
else
{
chosen = ResolveActionGroup(ag.Groups[choiceIndex - leafCount], ctx,
abilityIndex: 0, range, forceDuration, continuation);
if (chosen is null)
{
// Nested group triggered another pick.
// Accumulate our preceding into whatever the inner group set.
if (ctx.State.PendingActionGroupPick is { } innerPend && preceding.Length > 0)
{
var innerInner = innerPend.PrecedingActionsJson is not null
? JsonSerializer.Deserialize(innerPend.PrecedingActionsJson, _jsonOpts) ?? []
: [];
innerPend.PrecedingActionsJson = JsonSerializer.Serialize(
preceding.Concat(innerInner).ToArray(), _jsonOpts);
}
return state;
}
}
// Process any remaining sibling groups (from a parent AND group that paused here).
ActionGroup[]? remainingGroups = pending.RemainingGroupsJson is not null
? JsonSerializer.Deserialize(pending.RemainingGroupsJson, _jsonOpts)
: null;
if (remainingGroups is { Length: > 0 })
{
var tempList = new List(chosen);
for (int rgi = 0; rgi < remainingGroups.Length; rgi++)
{
var rgActions = ResolveActionGroup(remainingGroups[rgi], ctx,
abilityIndex: 0, range, forceDuration, continuation);
if (rgActions is null)
{
// This remaining group paused. Carry forward the full preceding context:
// preceding (from parent) + tempList (chosen branch + already-resolved groups)
if (ctx.State.PendingActionGroupPick is { } newPend)
{
var newInnerPreceding = newPend.PrecedingActionsJson is not null
? JsonSerializer.Deserialize(newPend.PrecedingActionsJson, _jsonOpts) ?? []
: [];
newPend.PrecedingActionsJson = JsonSerializer.Serialize(
preceding.Concat(tempList).Concat(newInnerPreceding).ToArray(), _jsonOpts);
// ContinuationActionsJson is already set by the new pause.
var afterThis = remainingGroups.Skip(rgi + 1).ToArray();
newPend.RemainingGroupsJson = afterThis.Length > 0
? JsonSerializer.Serialize(afterThis, _jsonOpts) : null;
}
return state;
}
tempList.AddRange(rgActions);
}
chosen = tempList.ToArray();
}
// Correct AND-group order: [preceding] + [chosen/remaining] + [outer continuation].
var allActions = preceding.Concat(chosen).Concat(continuation).ToArray();
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false,
activationRange: range, forceDuration: forceDuration);
return state;
}
///
/// Resumes execution after the chooser has responded to a game.reveal_choice_pick.
/// is the chooser's desired ordering of the revealed cards
/// (0-based indices into ).
/// Unspecified cards are placed beneath the chosen cards in their original relative order.
///
public static GameState ResumeRevealChoicePick(
GameState state,
string actorId,
string requestId,
int[] orderedIndices)
{
var pending = state.PendingRevealChoicePick
?? throw new GameException("NO_PENDING_REVEAL_CHOICE_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
if (actorId != pending.ActorId && actorId != pending.ChooserActorId)
throw new GameException("NOT_YOUR_REVEAL_CHOICE_PICK");
state.PendingRevealChoicePick = null;
if (pending.EffectType == "StackDeck")
{
var revealed = JsonSerializer.Deserialize(
pending.RevealedCardsJson, _jsonOpts) ?? [];
if (!state.Players.TryGetValue(pending.TargetPlayerAccountId, out var ps))
return state;
// Validate indices (deduplicate, clamp to valid range).
var validIndices = orderedIndices
.Where(i => i >= 0 && i < revealed.Length)
.Distinct()
.ToArray();
var usedSet = new HashSet(validIndices);
// Unspecified cards go at the bottom of the returned block (drawn last).
var bottom = Enumerable.Range(0, revealed.Length)
.Where(i => !usedSet.Contains(i))
.Select(i => revealed[i])
.ToList();
// Specified cards go on top (drawn first) in the chooser's order.
var top = validIndices.Select(i => revealed[i]).ToList();
// Deck is stored with index 0 = bottom; top of deck is last element.
ps.Deck.AddRange(bottom);
ps.Deck.AddRange(top);
}
// Continue execution after the chooser submits their ordering.
var rrcSource = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var rrcCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = rrcSource };
DurationModel? rrcActionDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
// Apply remaining effects within the same action.
ApplyIntraActionContinuation(pending.IntraActionContinuationJson, rrcActionDuration, rrcCtx);
// Execute outer continuation actions.
if (!rrcCtx.State.HasPendingInteraction())
{
var rrcContinuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
if (rrcContinuation.Length > 0)
{
AbilityRange? rrcRange = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(rrcContinuation, rrcCtx, clientTargets: null, activationRange: rrcRange,
forceDuration: rrcActionDuration);
}
}
return state;
}
///
/// Resumes an effect-level pause where the player must pick a specific tile
/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile).
/// Called by GameTilePickHandler.
///
public static GameState ResumeTilePick(
GameState state,
string actorId,
string requestId,
Coord pickedTile)
{
var pending = state.PendingTilePick
?? throw new GameException("NO_PENDING_TILE_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
if (expectedChooser != actorId)
throw new GameException("NOT_YOUR_TILE_PICK");
state.PendingTilePick = null;
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
switch (pending.EffectType)
{
case "CloneSpiritAsToken":
{
var spiritToClone = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.TargetInstanceId);
if (spiritToClone is null || state.Board is null) break;
var tile = state.Board.GetTile(pickedTile);
if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE");
var tokenProto = new CardInstance
{
InstanceId = Guid.NewGuid().ToString("N")[..8],
CardType = "SpiritToken",
Name = spiritToClone.Name,
Affinity = spiritToClone.Affinity,
MaxHealth = spiritToClone.MaxHealth,
CurrentHealth = spiritToClone.MaxHealth,
MaxDefense = spiritToClone.MaxDefense,
CurrentDefense = spiritToClone.MaxDefense,
Damage = spiritToClone.Damage,
CanMove = spiritToClone.CanMove,
CanAttack = spiritToClone.CanAttack,
CanDefend = spiritToClone.CanDefend,
MovementType = spiritToClone.MovementType,
AbilitiesJson = spiritToClone.AbilitiesJson,
};
var tokenField = CreateTokenFieldCard(tokenProto, pickedTile);
state.Players[pending.ActorId].Field.Add(tokenField);
state.Board.PlaceUnit(pickedTile, tokenField.InstanceId, pending.ActorId);
EvaluateAurasOnEnter(state, tokenField.InstanceId);
ApplyPassivesForSource(state, tokenField.InstanceId, pending.ActorId);
ApplyPassivesToNewTarget(state, tokenField.InstanceId);
break;
}
case "ChannelCardFromZone":
{
if (state.Board is null) break;
var board = state.Board;
// Resolve card and dest player.
var ccCard = state.Players.Values
.SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast())
.FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId);
if (ccCard is null) break;
var ccFromOwner = FindCardOwner(state, pending.TargetInstanceId);
if (ccFromOwner is null) break;
var ccDestOwnerId = string.IsNullOrEmpty(pending.DestPlayerAccountId)
? pending.ActorId
: pending.DestPlayerAccountId;
if (!state.Players.TryGetValue(ccDestOwnerId, out var ccDestPlayer)) break;
var tile = board.GetTile(pickedTile);
if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE");
var ccze = pending.EffectJson is not null
? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect
: null;
// Affinity check.
if (ccze?.IgnoreAffinity != true && Enum.TryParse(ccCard.Affinity, out var tpAffinity))
{
if (!AffinitySystem.IsAffinityValid(tile, tpAffinity))
throw new GameException("INVALID_AFFINITY");
}
// Cost.
if (ccze?.IgnoreChannelCost != true)
{
ccDestPlayer.CurrentSp -= ccCard.SpCost;
ccDestPlayer.CurrentSt -= ccCard.StCost;
}
// Remove from zone.
if (ccze?.KeepInZone != true)
RemoveFromZone(ccFromOwner, ccze?.Zone ?? "Hand", ccCard);
// Place on board.
var tpField = GameEngine.ToFieldCardInternal(ccCard, pickedTile);
ccDestPlayer.Field.Add(tpField);
board.PlaceUnit(pickedTile, tpField.InstanceId, ccDestOwnerId);
EvaluateAurasOnEnter(state, tpField.InstanceId);
ApplyPassivesForSource(state, tpField.InstanceId, ccDestOwnerId);
ApplyPassivesToNewTarget(state, tpField.InstanceId);
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = ccDestOwnerId,
CardType = ccCard.CardType,
Data = new TriggerEventData { SourceId = tpField.InstanceId },
});
break;
}
}
// Apply remaining effects within the same action before the outer continuation.
DurationModel? tpActionDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
ApplyIntraActionContinuation(pending.IntraActionContinuationJson, tpActionDuration, ctx);
// Execute outer continuation actions.
if (!ctx.State.HasPendingInteraction())
{
var continuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
if (continuation.Length > 0)
{
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(continuation, ctx, clientTargets: null, activationRange: range,
forceDuration: tpActionDuration);
}
}
return state;
}
///
/// Resumes an effect-level pause where the player must pick another player
/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice).
/// Called by GamePlayerPickHandler.
///
public static GameState ResumePlayerPick(
GameState state,
string actorId,
string requestId,
string pickedPlayerId)
{
var pending = state.PendingPlayerPick
?? throw new GameException("NO_PENDING_PLAYER_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
if (expectedChooser != actorId)
throw new GameException("NOT_YOUR_PLAYER_PICK");
if (pending.ValidPlayerIds.Count > 0 && !pending.ValidPlayerIds.Contains(pickedPlayerId))
throw new GameException("INVALID_PLAYER_PICK");
state.PendingPlayerPick = null;
var ppSource = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var ppCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = ppSource };
// Dispatch per effect type.
switch (pending.EffectType)
{
case "ChannelCardFromZone":
{
if (!state.Players.TryGetValue(pickedPlayerId, out var ppDest)) break;
var ppBoard = state.Board;
if (ppBoard is null) break;
var ppCard = state.Players.Values
.SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast())
.FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId);
if (ppCard is null) break;
var ppFromOwner = FindCardOwner(state, pending.TargetInstanceId);
if (ppFromOwner is null) break;
var ppCcze = pending.EffectJson is not null
? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect
: null;
if (ppCcze?.TargetTile == true)
{
// Chain into a tile pick for the chosen dest player.
// Forward IntraActionContinuationJson so the tile-pick resume
// continues with the same intra-action remainder.
state.PendingTilePick = new PendingTilePick
{
ActorId = pending.ActorId,
ChooserActorId = pickedPlayerId,
SourceInstanceId = pending.SourceInstanceId,
EffectType = "ChannelCardFromZone",
TargetInstanceId = pending.TargetInstanceId,
DestPlayerAccountId = pickedPlayerId,
RequireEmpty = true,
EffectJson = pending.EffectJson,
IntraActionContinuationJson = pending.IntraActionContinuationJson,
ContinuationActionsJson = pending.ContinuationActionsJson,
RangeJson = pending.RangeJson,
ForceDurationJson = pending.ForceDurationJson,
};
return state;
}
// Random tile in channel range.
var ppArch = ppDest.ArchSpirit;
Coord? ppCoord;
if (ppCcze?.IgnoreChannelRange != true && ppArch?.Position.HasValue == true)
{
var maxR = ppCard.MaxChannelRange ?? 2;
var minR = ppCard.MinChannelRange ?? 1;
ppCoord = ppBoard.Tiles.Values
.Where(t => t.IsEmpty)
.Where(t =>
{
var d = ppBoard.HexSides > 0
? HexGrid.Distance(ppArch.Position!.Value, t.Coord, ppBoard.HexSides)
: ppArch.Position!.Value.ManhattanDistance(t.Coord);
return d >= minR && d <= maxR;
})
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast()
.FirstOrDefault();
}
else
{
ppCoord = ppBoard.Tiles.Values
.Where(t => t.IsEmpty)
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast()
.FirstOrDefault();
}
if (ppCoord is null) break;
// Affinity check.
if (ppCcze?.IgnoreAffinity != true && Enum.TryParse(ppCard.Affinity, out var ppAff))
{
var ppTile = ppBoard.GetTile(ppCoord.Value);
if (ppTile is null || !AffinitySystem.IsAffinityValid(ppTile, ppAff)) break;
}
// Cost.
if (ppCcze?.IgnoreChannelCost != true)
{
ppDest.CurrentSp -= ppCard.SpCost;
ppDest.CurrentSt -= ppCard.StCost;
}
// Remove from zone.
if (ppCcze?.KeepInZone != true)
RemoveFromZone(ppFromOwner, ppCcze?.Zone ?? "Hand", ppCard);
// Place on board.
var ppField = GameEngine.ToFieldCardInternal(ppCard, ppCoord.Value);
ppDest.Field.Add(ppField);
ppBoard.PlaceUnit(ppCoord.Value, ppField.InstanceId, pickedPlayerId);
EvaluateAurasOnEnter(state, ppField.InstanceId);
ApplyPassivesForSource(state, ppField.InstanceId, pickedPlayerId);
ApplyPassivesToNewTarget(state, ppField.InstanceId);
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = pickedPlayerId,
CardType = ppCard.CardType,
Data = new TriggerEventData { SourceId = ppField.InstanceId },
});
break;
}
default:
{
// Generic case: store the picked player in resolved targets for continuation use.
if (state.Players.TryGetValue(pickedPlayerId, out var genericPickedPlayer))
ppCtx.ResolvedTargets[0] = [(object)genericPickedPlayer];
break;
}
}
DurationModel? ppActionDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
// Apply remaining effects within the same action before the outer continuation.
ApplyIntraActionContinuation(pending.IntraActionContinuationJson, ppActionDuration, ppCtx);
if (!ppCtx.State.HasPendingInteraction())
{
var ppContinuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
if (ppContinuation.Length > 0)
{
AbilityRange? ppRange = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(ppContinuation, ppCtx, clientTargets: null, activationRange: ppRange,
forceDuration: ppActionDuration);
}
}
return state;
}
///
/// Resumes an active ability that was paused because a leaf Action had
/// Chooser=Opponent/Ally and needed the non-activating player to supply targets.
/// Called by GameTargetPickHandler.
///
public static GameState ResumeTargetPick(
GameState state,
string actorId,
string requestId,
IReadOnlyList clientTargets)
{
var pending = state.PendingTargetPick
?? throw new GameException("NO_PENDING_TARGET_PICK");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
if (expectedChooser != actorId)
throw new GameException("NOT_YOUR_TARGET_PICK");
state.PendingTargetPick = null;
var action = JsonSerializer.Deserialize(pending.ActionJson, _jsonOpts)
?? throw new GameException("INVALID_TARGET_PICK_STATE");
var continuation = JsonSerializer.Deserialize(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null;
// Execute the paused action (now with client targets) then run the continuation.
// CONTRACT: The paused action is placed at index 0 in the replayed slice, so
// the client must submit targets using ActionIndex=0 regardless of the original
// action index in the ability definition. The prompt payload should reflect this.
var allActions = new[] { action }.Concat(continuation).ToArray();
ExecuteActions(allActions, ctx, clientTargets, requireClientTargets: true,
activationRange: range, forceDuration: forceDuration);
return state;
}
// ── Action execution ──────────────────────────────────────────────────────
private static void ExecuteActions(
Models.Action[] actions,
AbilityContext ctx,
IReadOnlyList? clientTargets,
bool requireClientTargets = false,
AbilityRange? activationRange = null,
HashSet? restrictTargets = null,
DurationModel? forceDuration = null)
{
_sequenceDepth++;
try
{
for (int i = 0; i < actions.Length; i++)
{
ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i,
requireClientTargets, activationRange, restrictTargets, forceDuration,
continuationActions: actions[(i + 1)..]);
// Stop iterating as soon as any interactive pause is set.
if (ctx.State.HasPendingInteraction()) break;
}
}
finally
{
_sequenceDepth--;
if (_sequenceDepth <= 0)
{
_sequenceDepth = 0;
ExpireEndOfSequenceEffects(ctx.State);
}
}
}
private static void ExecuteSingleAction(
Models.Action action,
AbilityContext ctx,
IReadOnlyList? clientTargets,
int actionIndex,
bool requireClientTargets = false,
AbilityRange? activationRange = null,
HashSet? restrictTargets = null,
DurationModel? forceDuration = null,
Models.Action[] continuationActions = null!)
{
continuationActions ??= [];
// ChooseOne branch selector: execute the chosen branch's actions instead.
if (action.ChooseOne is { Branches.Length: > 0 })
{
var chooser = action.ChooseOne;
int branchIdx;
if (chooser.ChooserRole == "Random")
{
branchIdx = Random.Shared.Next(chooser.Branches.Length);
}
else if (chooser.ChooserRole is "Opponent" or "Ally")
{
// Pause — let the non-activating player pick.
var chooserActorId = chooser.ChooserRole == "Opponent"
? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId
: ctx.State.Players.Values
.FirstOrDefault(p => p.AccountId != ctx.ActorId
&& ctx.State.AreAllies(p.AccountId, ctx.ActorId))
?.AccountId ?? ctx.ActorId;
ctx.State.PendingBranchPick = new PendingBranchPick
{
ActorId = ctx.ActorId,
ChooserActorId = chooserActorId,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
BranchCount = chooser.Branches.Length,
BranchesJson = JsonSerializer.Serialize(chooser.Branches, _jsonOpts),
ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts),
RangeJson = activationRange is not null
? JsonSerializer.Serialize(activationRange, _jsonOpts) : null,
ForceDurationJson = forceDuration is not null
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
};
return; // paused — caller will propagate stop
}
else
{
// Self: use client-provided BranchIndex.
branchIdx = clientTargets?
.FirstOrDefault(t => t.ActionIndex == actionIndex)?.BranchIndex ?? 0;
branchIdx = Math.Clamp(branchIdx, 0, chooser.Branches.Length - 1);
}
ExecuteActions(chooser.Branches[branchIdx].Actions, ctx,
clientTargets: null, requireClientTargets: false,
forceDuration: forceDuration);
return;
}
// Source-level conditions (Subject != "Target"): gate the whole action.
if (action.Conditions is { Length: > 0 })
foreach (var cond in action.Conditions)
if (cond.Subject != "Target" && !EvaluateCondition(cond, ctx, ctx.Source!))
return;
// If Chooser=Opponent/Ally and we have no client-provided targets, pause for the
// non-activating player to pick. (Chooser=Random is server-resolved in ResolveTargets.)
var sel = action.Target;
if (sel.Chooser is TargetChooser.Opponent or TargetChooser.Ally
&& clientTargets is null
&& sel.Type != TargetType.Player
&& !sel.Count.All)
{
var tpChooser = sel.Chooser == TargetChooser.Opponent
? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId
: ctx.State.Players.Values
.FirstOrDefault(p => p.AccountId != ctx.ActorId
&& ctx.State.AreAllies(p.AccountId, ctx.ActorId))
?.AccountId ?? ctx.ActorId;
ctx.State.PendingTargetPick = new PendingTargetPick
{
ActorId = ctx.ActorId,
ChooserActorId = tpChooser,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
ActionJson = JsonSerializer.Serialize(action, _jsonOpts),
ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts),
RangeJson = activationRange is not null
? JsonSerializer.Serialize(activationRange, _jsonOpts) : null,
ForceDurationJson = forceDuration is not null
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
};
return;
}
var resolved = ResolveTargets(
action.Target, ctx, clientTargets, actionIndex, requireClientTargets, activationRange, restrictTargets);
ctx.ResolvedTargets[actionIndex] = resolved;
// Target-level conditions (Subject == "Target"): filter per target.
var targetConds = action.Conditions?.Where(c => c.Subject == "Target").ToArray();
var duration = forceDuration ?? action.Duration;
// Snapshot all targets and effects for intra-action continuation capture.
ctx.CurrentActionAllEffects = action.Effects;
ctx.CurrentActionTargets = [.. resolved];
ctx.CurrentActionDuration = duration;
ctx.ContinuationActions = continuationActions;
ctx.ActivationRange = activationRange;
for (int ti = 0; ti < resolved.Count; ti++)
{
var target = resolved[ti];
ctx.CurrentTargetIndex = ti;
if (targetConds is { Length: > 0 })
{
// Temporarily expose current target so EvaluateCondition resolves "Target" correctly.
ctx.ResolvedTargets[actionIndex] = [target];
bool passes = targetConds.All(c => EvaluateCondition(c, ctx, target));
ctx.ResolvedTargets[actionIndex] = resolved;
if (!passes) continue;
}
for (int ei = 0; ei < action.Effects.Length; ei++)
{
ctx.CurrentEffectIndex = ei;
ExecuteEffect(action.Effects[ei], target, duration, ctx);
// Stop as soon as an effect sets an interactive pause.
if (ctx.State.HasPendingInteraction()) return;
}
// Also stop between targets if a pause was set mid-loop.
if (ctx.State.HasPendingInteraction()) return;
}
}
// ── Triggered ability client-target detection & resume ────────────────────
///
/// Returns true when the action requires a human target pick rather than
/// being fully server-auto-resolvable. Used by to
/// decide whether to pause and request client input.
/// Also called by GameHandlerBase to locate the first client-pick action
/// for the TriggeredTargetRequestPush payload.
///
internal static bool ActionNeedsClientTargets_Public(Models.Action action)
=> ActionNeedsClientTargets(action);
private static bool ActionNeedsClientTargets(Models.Action action)
{
// ChooseOne always needs the player to pick a branch.
if (action.ChooseOne is { Branches.Length: > 0 })
return true;
var sel = action.Target;
// Player-type targets are always server-resolved.
if (sel.Type == TargetType.Player)
return false;
// "All" targets are enumerated server-side with no player choice.
if (sel.Count.All)
return false;
// Random chooser: server resolves without client input regardless of ownership.
if (sel.Chooser == TargetChooser.Random)
return false;
// These ownerships are auto-resolved: self, random, chained from prior action.
return sel.Ownership is not (
TargetOwnership.Self or
TargetOwnership.ExactSelf or
TargetOwnership.Target or
TargetOwnership.Random);
}
///
/// Resumes a triggered ability that was paused for client target input.
/// Called by GameTriggeredTargetHandler once the player submits their picks.
///
public static GameState ResumeTriggeredAbility(
GameState state,
string actorId,
string requestId,
IReadOnlyList clientTargets)
{
var pending = state.PendingTriggeredTarget
?? throw new GameException("NO_PENDING_TRIGGER");
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
// ChooserActorId is who must respond — may be an opponent/ally for Chooser.Opponent/Ally.
// Fall back to ActorId for older records that predate ChooserActorId.
var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
if (expectedChooser != actorId)
throw new GameException("NOT_YOUR_TRIGGER");
// Clear before executing so any nested triggers don't see a stale request.
state.PendingTriggeredTarget = null;
var actions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts) ?? [];
// Source unit may have left the battlefield while waiting — skip silently if so.
var source = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
if (source is null) return state;
var ctx = new AbilityContext
{
State = state,
ActorId = pending.ActorId,
Source = source,
};
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts)
: null;
ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true,
forceDuration: forceDuration);
return state;
}
// ── Target resolution ─────────────────────────────────────────────────────
private static List