using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Json.Schema; using Microsoft.Extensions.Logging; namespace NeonSprawl.Server.Game.Encounters; /// Loads and validates content/reward-tables/*_reward_tables.json using the same rules as scripts/validate_content.py (NEO-101). public static class RewardTableDefinitionCatalogLoader { /// Loads catalogs from disk or throws with actionable messages. public static RewardTableDefinitionCatalog Load( string rewardTablesDirectory, string rewardTableSchemaPath, string rewardGrantRowSchemaPath, IReadOnlySet knownItemIds, ILogger logger) { rewardTablesDirectory = Path.GetFullPath(rewardTablesDirectory); rewardTableSchemaPath = Path.GetFullPath(rewardTableSchemaPath); rewardGrantRowSchemaPath = Path.GetFullPath(rewardGrantRowSchemaPath); var errors = new List(); if (!File.Exists(rewardTableSchemaPath)) errors.Add($"error: missing schema file {rewardTableSchemaPath}"); if (!File.Exists(rewardGrantRowSchemaPath)) errors.Add($"error: missing schema file {rewardGrantRowSchemaPath}"); if (!Directory.Exists(rewardTablesDirectory)) errors.Add($"error: missing directory {rewardTablesDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); var jsonFiles = Directory.GetFiles(rewardTablesDirectory, "*_reward_tables.json", SearchOption.TopDirectoryOnly) .OrderBy(p => p, StringComparer.Ordinal) .ToArray(); if (jsonFiles.Length == 0) errors.Add($"error: no *_reward_tables.json files under {rewardTablesDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); var grantRowSchema = JsonSchema.FromText(File.ReadAllText(rewardGrantRowSchemaPath)); SchemaRegistry.Global.Register(grantRowSchema); var tableSchema = JsonSchema.FromText(File.ReadAllText(rewardTableSchemaPath)); SchemaRegistry.Global.Register(tableSchema); var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List }; var rewardTableIdToSourceFile = new Dictionary(StringComparer.Ordinal); var rows = new Dictionary(StringComparer.Ordinal); foreach (var path in jsonFiles) { JsonNode? root; try { root = JsonNode.Parse(File.ReadAllText(path)); } catch (JsonException ex) { errors.Add($"error: {path}: invalid JSON: {ex.Message}"); continue; } if (root is not JsonObject rootObj) { errors.Add($"error: {path}: expected JSON object at root"); continue; } var schemaVersionNode = rootObj["schemaVersion"]; if (schemaVersionNode is not JsonValue schemaVersionValue || !schemaVersionValue.TryGetValue(out var schemaVersion) || schemaVersion != 1) { var got = schemaVersionNode?.ToJsonString() ?? "null"; errors.Add($"error: {path}: expected schemaVersion 1, got {got}"); continue; } var rewardTablesNode = rootObj["rewardTables"]; if (rewardTablesNode is not JsonArray rewardTablesArray) { errors.Add($"error: {path}: expected top-level 'rewardTables' array"); continue; } for (var i = 0; i < rewardTablesArray.Count; i++) { var rewardTable = rewardTablesArray[i]; if (rewardTable is not JsonObject rowObj) { errors.Add($"error: {path}: rewardTables[{i}] must be an object"); continue; } var eval = tableSchema.Evaluate(rowObj, evalOptions); var schemaMsgs = CollectSchemaMessages(eval, path, i).OrderBy(m => m, StringComparer.Ordinal).ToList(); if (!eval.IsValid) { if (schemaMsgs.Count == 0) schemaMsgs.Add($"error: {path} rewardTables[{i}] (root): schema validation failed"); errors.AddRange(schemaMsgs); } var rowSchemaErrors = schemaMsgs.Count; var rid = (rowObj["id"] as JsonValue)?.GetValue(); if (rid is not null && rowSchemaErrors == 0) { if (rewardTableIdToSourceFile.TryGetValue(rid, out var prevPath)) { errors.Add($"error: duplicate reward table id '{rid}' in {prevPath} and {path}"); continue; } rewardTableIdToSourceFile[rid] = path; CrossCheckFixedGrants(rowObj, path, i, knownItemIds, errors); rows[rid] = ParseRow(rowObj); } } } ThrowIfAny(errors); var e5m3 = PrototypeE5M3RewardTableCatalogRules.TryGetE5M3GateError(rewardTableIdToSourceFile); if (e5m3 is not null) { errors.Add(e5m3); ThrowIfAny(errors); } var grantContent = PrototypeE5M3RewardTableCatalogRules.TryGetGrantContentGateError(rows); if (grantContent is not null) { errors.Add(grantContent); ThrowIfAny(errors); } if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( "Loaded reward table catalog from {RewardTablesDirectory}: {RewardTableCount} reward table(s) across {CatalogFileCount} JSON catalog file(s).", rewardTablesDirectory, rows.Count, jsonFiles.Length); } return new RewardTableDefinitionCatalog(rewardTablesDirectory, rows, jsonFiles.Length); } private static void CrossCheckFixedGrants( JsonObject rowObj, string path, int tableIndex, IReadOnlySet knownItemIds, List errors) { if (rowObj["fixedGrants"] is not JsonArray grantsArray) return; var seenGrantItemIds = new HashSet(StringComparer.Ordinal); for (var j = 0; j < grantsArray.Count; j++) { if (grantsArray[j] is not JsonObject grantObj) continue; var itemId = (grantObj["itemId"] as JsonValue)?.GetValue(); if (itemId is null) continue; if (!seenGrantItemIds.Add(itemId)) { errors.Add( $"error: {path} rewardTables[{tableIndex}].fixedGrants[{j}]: duplicate itemId '{itemId}'"); } if (!knownItemIds.Contains(itemId)) { errors.Add( $"error: {path} rewardTables[{tableIndex}].fixedGrants[{j}]: itemId '{itemId}' is not in item catalogs"); } } } private static RewardTableDefRow ParseRow(JsonObject rowObj) { var id = (rowObj["id"] as JsonValue)!.GetValue(); var displayName = (rowObj["displayName"] as JsonValue)!.GetValue(); var fixedGrants = ParseGrantRows(rowObj["fixedGrants"] as JsonArray); return new RewardTableDefRow(id, displayName, fixedGrants); } private static IReadOnlyList ParseGrantRows(JsonArray? array) { if (array is null) return []; var rows = new List(array.Count); foreach (var node in array) { if (node is not JsonObject grantObj) continue; var itemId = (grantObj["itemId"] as JsonValue)!.GetValue(); var quantity = (grantObj["quantity"] as JsonValue)!.GetValue(); rows.Add(new RewardGrantRow(itemId, quantity)); } return rows; } private static List CollectSchemaMessages(EvaluationResults eval, string filePath, int index) { var sink = new List(); AppendSchemaMessages(eval, filePath, index, sink); return sink; } private static void AppendSchemaMessages(EvaluationResults r, string filePath, int index, List sink) { if (r.HasDetails) { foreach (var d in r.Details!) AppendSchemaMessages(d, filePath, index, sink); } if (!r.HasErrors) return; foreach (var kv in r.Errors!) { var loc = r.InstanceLocation?.ToString(); if (string.IsNullOrEmpty(loc) || loc == "#") loc = "(root)"; sink.Add($"error: {filePath} rewardTables[{index}] {loc}: {kv.Key} — {kv.Value}"); } } private static void ThrowIfAny(List errors) { if (errors.Count == 0) return; var sb = new StringBuilder(); sb.AppendLine("Reward table catalog validation failed:"); foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal)) sb.AppendLine(e); throw new InvalidOperationException(sb.ToString().TrimEnd()); } }