using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using SVSim.BattleNode.Bridge;
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Wire;
using SVSim.UnitTests.Infrastructure;
namespace SVSim.UnitTests.BattleNode.Integration;
///
/// Wire-shape conformance of our server-authored synchronize frames against real prod TK2
/// captures (data_dumps/captures/battle-traffic_tk2_regular.ndjson +
/// …_tk2_second.ndjson, captured 2026-05-31 from a real client mid-PvP).
///
/// What this guards: for every frame our server *authors* (as opposed to forwarding a
/// client's bytes), the payload it emits must carry every key prod sent, with a matching value
/// *category* (object / array / string / number / bool). This is the bug class that has bitten the
/// node repeatedly — wrong casing (card_id vs cardID), a missing field the client
/// reads without a guard, or a string where the client expects a number. The existing
/// assert frame *ordering and routing*; they never inspect the
/// body. This closes that gap and turns the prod captures into a permanent regression oracle that
/// survives the June-2026 server shutdown.
///
/// Direction of the check is capture ⊆ ours — we must emit at least what prod emits
/// (missing/miscased/mistyped = fail), but we may emit extra envelope fields (we send
/// viewerId/uuid/try/cat on pushes; prod's receive frames omit them). Pure
/// envelope/sequencing keys (viewerId, uuid, try, cat, bid, pubSeq, playSeq) are excluded
/// from the comparison: they're transport concerns assigned by the sequencer, covered by the
/// reliability layer + integration tests, and legitimately vary per frame (e.g. the no-stock
/// BattleFinish frame is played immediately whether or not it carries a playSeq).
/// The check is on *body shape*.
///
/// Coverage: a single Scripted session emits all ten server-authored URIs
/// (InitNetwork, Matched, BattleStart, Deal, Swap, Ready, TurnStart, TurnEnd, Judge,
/// BattleFinish). PvP uses the same
/// builders for the handshake/mulligan frames, so this transitively covers the PvP handshake shape
/// too. Forwarded frames (PlayActions / TurnEndActions / ChatStamp / TurnEndFinal) relay the
/// client's own bytes verbatim, so their shape is the client's contract, not ours — out of scope
/// here.
///
[TestFixture]
public class CaptureConformanceTests
{
private const long ViewerId = 906243102L;
// Top-level keys that are envelope/transport, not body shape. Excluded from the comparison
// at the root level only (nested objects never contain these).
private static readonly HashSet IgnoredEnvelopeKeys = new()
{
"viewerId", "uuid", "try", "cat", "bid", "pubSeq", "playSeq",
};
[Test]
[Timeout(30000)]
public async Task ServerAuthoredFrames_MatchProdCaptureShapes()
{
await using var factory = new SVSimTestFactory();
var bridge = factory.Services.GetRequiredService();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var ct = cts.Token;
var pending = bridge.RegisterBattle(
new BattlePlayer(ViewerId, BattleNodeFlowTests.FixtureCtx()),
p2: null,
SVSim.BattleNode.Sessions.BattleType.Scripted);
var key = MakeKey();
var encryptedVid = NodeCrypto.EncryptForNode(ViewerId.ToString(), key);
var wsUri = new Uri(
$"ws://localhost/socket.io/?BattleId={pending.BattleId}&viewerId={Uri.EscapeDataString(encryptedVid)}&EIO=3&transport=websocket");
var wsClient = factory.Server.CreateWebSocketClient();
var ws = await wsClient.ConnectAsync(wsUri, ct);
await using var client = new RawSocketIoTestClient(ws);
await client.ConsumeHandshakeAsync(ct);
// Drive the full Scripted lifecycle, harvesting every server-pushed frame by URI.
var harvested = new Dictionary();
async Task DriveAsync(NetworkBattleUri send, long pubSeq, int expectPushes,
Dictionary? body = null)
{
await client.SendMsgAsync(MakeEnvelope(send, pubSeq, body), key, ct);
for (var i = 0; i < expectPushes; i++)
{
var frame = await client.ReceiveSynchronizeAsync(ct);
harvested[frame.Uri] = frame;
}
}
await DriveAsync(NetworkBattleUri.InitNetwork, 1, expectPushes: 1);
await DriveAsync(NetworkBattleUri.InitBattle, 2, expectPushes: 1); // Matched
await DriveAsync(NetworkBattleUri.Loaded, 3, expectPushes: 2); // BattleStart + Deal
await DriveAsync(NetworkBattleUri.Swap, 4, expectPushes: 2, // Swap + Ready
body: new Dictionary { ["idxList"] = new List