using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace SVSim.BattleNode.Protocol;
///
/// The shared envelope on every encrypted msg / synchronize frame. Body is
/// — either a typed body record (outbound) or a
/// (inbound).
///
public sealed record MsgEnvelope(
NetworkBattleUri Uri,
long ViewerId,
string Uuid,
string? Bid,
int Try,
EmitCategory Cat,
long? PubSeq,
long? PlaySeq,
IMsgBody Body)
{
private static readonly JsonSerializerOptions Options = CreateOptions();
private static readonly HashSet ReservedEnvelopeKeys = new()
{
"uri", "viewerId", "uuid", "bid", "try", "cat", "pubSeq", "playSeq",
};
private static JsonSerializerOptions CreateOptions()
{
var opt = new JsonSerializerOptions
{
// Wire-key casing is bare camelCase via per-field [JsonPropertyName] —
// NOT EmulatedEntrypoint's snake_case policy. The naming-policy line
// that was here previously was dead code (every wire key is explicit).
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
opt.Converters.Add(new JsonStringEnumConverter());
return opt;
}
public static string ToJson(MsgEnvelope env)
{
JsonObject result;
if (env.Body is RawBody raw)
{
// Inbound-echo path: flatten Entries to top-level keys, same as before
// the typed-body refactor.
result = new JsonObject();
foreach (var (k, v) in raw.Entries)
{
if (ReservedEnvelopeKeys.Contains(k))
throw new ArgumentException(
$"RawBody key '{k}' collides with a reserved envelope field. " +
$"Move it to a typed field on MsgEnvelope.",
nameof(env));
result[k] = ToJsonNode(v);
}
}
else
{
// Typed body: serialize via [JsonPropertyName] attributes on the record.
result = (JsonObject)JsonSerializer.SerializeToNode(env.Body, env.Body.GetType(), Options)!;
}
result["uri"] = env.Uri.ToString();
result["viewerId"] = env.ViewerId;
result["uuid"] = env.Uuid;
result["try"] = env.Try;
result["cat"] = (int)env.Cat;
if (env.Bid is not null) result["bid"] = env.Bid;
if (env.PubSeq.HasValue) result["pubSeq"] = env.PubSeq.Value;
if (env.PlaySeq.HasValue) result["playSeq"] = env.PlaySeq.Value;
return result.ToJsonString(Options);
}
///
/// Convert a boxed CLR value (as stored in ) to a JsonNode.
/// Explicit type switch on the runtime type — `JsonValue.Create(object?)` would create
/// a `JsonValueCustomized<object>` that requires a TypeInfoResolver at serialize time
/// (introduced in S.T.Json 8.0 source-gen mode).
///
private static JsonNode? ToJsonNode(object? value) => value switch
{
null => null,
string s => JsonValue.Create(s),
bool b => JsonValue.Create(b),
long l => JsonValue.Create(l),
int i => JsonValue.Create(i),
double d => JsonValue.Create(d),
decimal m => JsonValue.Create(m),
// Inbound-parsed nested objects come through as Dictionary; nested
// arrays as List