using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Json.Schema; using Microsoft.Extensions.Logging; namespace NeonSprawl.Server.Game.Crafting; /// Loads and validates content/recipes/*_recipes.json using the same rules as scripts/validate_content.py (NEO-66). public static class RecipeDefinitionCatalogLoader { /// Loads catalogs from disk or throws with actionable messages. public static RecipeDefinitionCatalog Load( string recipesDirectory, string recipeDefSchemaPath, string recipeIoRowSchemaPath, IReadOnlySet knownItemIds, IReadOnlySet knownSkillIds, ILogger logger) { recipesDirectory = Path.GetFullPath(recipesDirectory); recipeDefSchemaPath = Path.GetFullPath(recipeDefSchemaPath); recipeIoRowSchemaPath = Path.GetFullPath(recipeIoRowSchemaPath); var errors = new List(); if (!File.Exists(recipeDefSchemaPath)) errors.Add($"error: missing schema file {recipeDefSchemaPath}"); if (!File.Exists(recipeIoRowSchemaPath)) errors.Add($"error: missing schema file {recipeIoRowSchemaPath}"); if (!Directory.Exists(recipesDirectory)) errors.Add($"error: missing directory {recipesDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); var jsonFiles = Directory.GetFiles(recipesDirectory, "*_recipes.json", SearchOption.TopDirectoryOnly) .OrderBy(p => p, StringComparer.Ordinal) .ToArray(); if (jsonFiles.Length == 0) errors.Add($"error: no *_recipes.json files under {recipesDirectory}"); if (errors.Count > 0) ThrowIfAny(errors); var ioSchema = CatalogSchemaRegistry.GetOrRegisterFromFile(recipeIoRowSchemaPath); var defSchema = CatalogSchemaRegistry.GetOrRegisterFromFile(recipeDefSchemaPath); var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List }; var recipeIdToSourceFile = new Dictionary(StringComparer.Ordinal); var idToRecipeKind = new Dictionary(StringComparer.Ordinal); var idToRequiredSkillId = 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 recipesNode = rootObj["recipes"]; if (recipesNode is not JsonArray recipesArray) { errors.Add($"error: {path}: expected top-level 'recipes' array"); continue; } for (var i = 0; i < recipesArray.Count; i++) { var recipe = recipesArray[i]; if (recipe is not JsonObject rowObj) { errors.Add($"error: {path}: recipes[{i}] must be an object"); continue; } var eval = defSchema.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} recipes[{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 (recipeIdToSourceFile.TryGetValue(rid, out var prevPath)) { errors.Add($"error: duplicate recipe id '{rid}' in {prevPath} and {path}"); continue; } recipeIdToSourceFile[rid] = path; var recipeKind = (rowObj["recipeKind"] as JsonValue)?.GetValue(); if (recipeKind is not null) idToRecipeKind[rid] = recipeKind; var requiredSkillId = (rowObj["requiredSkillId"] as JsonValue)?.GetValue(); if (requiredSkillId is not null) { idToRequiredSkillId[rid] = requiredSkillId; if (!knownSkillIds.Contains(requiredSkillId)) { errors.Add( $"error: {path} recipes[{i}]: requiredSkillId '{requiredSkillId}' " + $"is not a known SkillDef id (known: [{string.Join(", ", knownSkillIds.Order(StringComparer.Ordinal).Select(s => "'" + s + "'"))}])"); } } CrossCheckIoRows(rowObj, path, i, "inputs", knownItemIds, errors); CrossCheckIoRows(rowObj, path, i, "outputs", knownItemIds, errors); rows[rid] = ParseRow(rowObj); } } } ThrowIfAny(errors); var slice3 = PrototypeSlice3RecipeCatalogRules.TryGetSlice3GateError( recipeIdToSourceFile, idToRecipeKind, idToRequiredSkillId); if (slice3 is not null) { errors.Add(slice3); ThrowIfAny(errors); } if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( "Loaded recipe catalog from {RecipesDirectory}: {RecipeCount} recipe(s) across {CatalogFileCount} JSON catalog file(s).", recipesDirectory, rows.Count, jsonFiles.Length); } return new RecipeDefinitionCatalog(recipesDirectory, rows, jsonFiles.Length); } private static void CrossCheckIoRows( JsonObject rowObj, string path, int recipeIndex, string ioKey, IReadOnlySet knownItemIds, List errors) { if (rowObj[ioKey] is not JsonArray ioArray) return; for (var j = 0; j < ioArray.Count; j++) { if (ioArray[j] is not JsonObject ioRow) continue; var itemId = (ioRow["itemId"] as JsonValue)?.GetValue(); if (itemId is not null && !knownItemIds.Contains(itemId)) { errors.Add( $"error: {path} recipes[{recipeIndex}].{ioKey}[{j}]: itemId '{itemId}' is not in item catalogs"); } } } private static RecipeDefRow ParseRow(JsonObject rowObj) { var id = (rowObj["id"] as JsonValue)!.GetValue(); var displayName = (rowObj["displayName"] as JsonValue)!.GetValue(); var recipeKind = (rowObj["recipeKind"] as JsonValue)!.GetValue(); var requiredSkillId = (rowObj["requiredSkillId"] as JsonValue)!.GetValue(); var inputs = ParseIoRows(rowObj["inputs"] as JsonArray); var outputs = ParseIoRows(rowObj["outputs"] as JsonArray); int? requiredSkillLevel = null; if (rowObj["requiredSkillLevel"] is JsonValue levelValue && levelValue.TryGetValue(out var level)) { requiredSkillLevel = level; } string? stationTag = null; if (rowObj["stationTag"] is JsonValue stationTagValue) stationTag = stationTagValue.GetValue(); return new RecipeDefRow(id, displayName, recipeKind, requiredSkillId, inputs, outputs, requiredSkillLevel, stationTag); } private static IReadOnlyList ParseIoRows(JsonArray? array) { if (array is null) return []; var rows = new List(array.Count); foreach (var node in array) { if (node is not JsonObject ioObj) continue; var itemId = (ioObj["itemId"] as JsonValue)!.GetValue(); var quantity = (ioObj["quantity"] as JsonValue)!.GetValue(); rows.Add(new RecipeIoRow(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} recipes[{index}] {loc}: {kv.Key} — {kv.Value}"); } } private static void ThrowIfAny(List errors) { if (errors.Count == 0) return; var sb = new StringBuilder(); sb.AppendLine("Recipe catalog validation failed:"); foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal)) sb.AppendLine(e); throw new InvalidOperationException(sb.ToString().TrimEnd()); } }