using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Json.Schema; using Microsoft.Extensions.Logging; namespace NeonSprawl.Server.Game.Npc; /// Loads and validates content/npc-behaviors/*_npc_behaviors.json using the same rules as scripts/validate_content.py (NEO-88). public static class NpcBehaviorDefinitionCatalogLoader { /// Loads catalogs from disk or throws with actionable messages. public static NpcBehaviorDefinitionCatalog Load(string npcBehaviorsDirectory, string schemaPath, ILogger logger) { npcBehaviorsDirectory = Path.GetFullPath(npcBehaviorsDirectory); schemaPath = Path.GetFullPath(schemaPath); var errors = new List(); if (!File.Exists(schemaPath)) errors.Add($"error: missing schema file {schemaPath}"); if (!Directory.Exists(npcBehaviorsDirectory)) errors.Add($"error: missing directory {npcBehaviorsDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); string[] jsonFiles = [.. Directory.GetFiles(npcBehaviorsDirectory, "*_npc_behaviors.json", SearchOption.TopDirectoryOnly) .OrderBy(p => p, StringComparer.Ordinal)]; if (jsonFiles.Length == 0) errors.Add($"error: no *_npc_behaviors.json files under {npcBehaviorsDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); var schema = JsonSchema.FromText(File.ReadAllText(schemaPath)); var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List }; var behaviorIdToSourceFile = 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 npcBehaviorsNode = rootObj["npcBehaviors"]; if (npcBehaviorsNode is not JsonArray npcBehaviorsArray) { errors.Add($"error: {path}: expected top-level 'npcBehaviors' array"); continue; } for (var i = 0; i < npcBehaviorsArray.Count; i++) { var behavior = npcBehaviorsArray[i]; if (behavior is not JsonObject rowObj) { errors.Add($"error: {path}: npcBehaviors[{i}] must be an object"); continue; } var eval = schema.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} npcBehaviors[{i}] (root): schema validation failed"); errors.AddRange(schemaMsgs); } var rowSchemaErrors = schemaMsgs.Count; var bid = (rowObj["id"] as JsonValue)?.GetValue(); if (bid is not null && rowSchemaErrors == 0) { if (behaviorIdToSourceFile.TryGetValue(bid, out var prevPath)) { errors.Add($"error: duplicate npc behavior id '{bid}' in {prevPath} and {path}"); continue; } behaviorIdToSourceFile[bid] = path; rows[bid] = ParseRow(rowObj); } } } ThrowIfAny(errors); var e5m2 = PrototypeE5M2NpcBehaviorCatalogRules.TryGetE5M2GateError(behaviorIdToSourceFile); if (e5m2 is not null) { errors.Add(e5m2); ThrowIfAny(errors); } var numeric = PrototypeE5M2NpcBehaviorCatalogRules.TryGetNumericGateError(rows); if (numeric is not null) { errors.Add(numeric); ThrowIfAny(errors); } if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( "Loaded NPC behavior catalog from {NpcBehaviorsDirectory}: {BehaviorCount} behavior(s) across {CatalogFileCount} JSON catalog file(s).", npcBehaviorsDirectory, rows.Count, jsonFiles.Length); } return new NpcBehaviorDefinitionCatalog(npcBehaviorsDirectory, rows, jsonFiles.Length); } private static NpcBehaviorDefRow ParseRow(JsonObject rowObj) { var id = (rowObj["id"] as JsonValue)!.GetValue(); var displayName = (rowObj["displayName"] as JsonValue)!.GetValue(); var archetypeKind = (rowObj["archetypeKind"] as JsonValue)!.GetValue(); var maxHp = (rowObj["maxHp"] as JsonValue)!.GetValue(); var aggroRadius = (rowObj["aggroRadius"] as JsonValue)!.GetValue(); var leashRadius = (rowObj["leashRadius"] as JsonValue)!.GetValue(); var telegraphWindupSeconds = (rowObj["telegraphWindupSeconds"] as JsonValue)!.GetValue(); var attackDamage = (rowObj["attackDamage"] as JsonValue)!.GetValue(); var attackCooldownSeconds = (rowObj["attackCooldownSeconds"] as JsonValue)!.GetValue(); var attackAbilityId = (rowObj["attackAbilityId"] as JsonValue)!.GetValue(); return new NpcBehaviorDefRow( id, displayName, archetypeKind, maxHp, aggroRadius, leashRadius, telegraphWindupSeconds, attackDamage, attackCooldownSeconds, attackAbilityId); } 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} npcBehaviors[{index}] {loc}: {kv.Key} — {kv.Value}"); } } private static void ThrowIfAny(List errors) { if (errors.Count == 0) return; var sb = new StringBuilder(); sb.AppendLine("NPC behavior catalog validation failed:"); foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal)) sb.AppendLine(e); throw new InvalidOperationException(sb.ToString().TrimEnd()); } }