using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Json.Schema;
using Microsoft.Extensions.Logging;
namespace NeonSprawl.Server.Game.Items;
/// Loads and validates content/items/*_items.json using the same rules as scripts/validate_content.py (NEO-51).
public static class ItemDefinitionCatalogLoader
{
/// Loads catalogs from disk or throws with actionable messages.
public static ItemDefinitionCatalog Load(string itemsDirectory, string schemaPath, ILogger logger)
{
itemsDirectory = Path.GetFullPath(itemsDirectory);
schemaPath = Path.GetFullPath(schemaPath);
var errors = new List();
if (!File.Exists(schemaPath))
errors.Add($"error: missing schema file {schemaPath}");
if (!Directory.Exists(itemsDirectory))
errors.Add($"error: missing directory {itemsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
string[] jsonFiles = [.. Directory.GetFiles(itemsDirectory, "*_items.json", SearchOption.TopDirectoryOnly)
.OrderBy(p => p, StringComparer.Ordinal)];
if (jsonFiles.Length == 0)
errors.Add($"error: no *_items.json files under {itemsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
var schema = JsonSchema.FromText(File.ReadAllText(schemaPath));
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
var itemIdToSourceFile = new Dictionary(StringComparer.Ordinal);
var idToRole = new Dictionary(StringComparer.Ordinal);
var idToSlotKind = new Dictionary(StringComparer.Ordinal);
var idToStackMax = 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 itemsNode = rootObj["items"];
if (itemsNode is not JsonArray itemsArray)
{
errors.Add($"error: {path}: expected top-level 'items' array");
continue;
}
for (var i = 0; i < itemsArray.Count; i++)
{
var item = itemsArray[i];
if (item is not JsonObject rowObj)
{
errors.Add($"error: {path}: items[{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} items[{i}] (root): schema validation failed");
errors.AddRange(schemaMsgs);
}
var rowSchemaErrors = schemaMsgs.Count;
var iid = (rowObj["id"] as JsonValue)?.GetValue();
if (iid is not null && rowSchemaErrors == 0)
{
if (itemIdToSourceFile.TryGetValue(iid, out var prevPath))
{
errors.Add($"error: duplicate item id '{iid}' in {prevPath} and {path}");
continue;
}
itemIdToSourceFile[iid] = path;
var role = (rowObj["prototypeRole"] as JsonValue)?.GetValue();
if (role is not null)
idToRole[iid] = role;
var slotKind = (rowObj["inventorySlotKind"] as JsonValue)?.GetValue();
if (slotKind is not null)
idToSlotKind[iid] = slotKind;
if (rowObj["stackMax"] is JsonValue stackMaxValue &&
stackMaxValue.TryGetValue(out var stackMax))
{
idToStackMax[iid] = stackMax;
}
rows[iid] = ParseRow(rowObj);
}
}
}
ThrowIfAny(errors);
var slice1 = PrototypeSlice1ItemCatalogRules.TryGetSlice1GateError(
itemIdToSourceFile,
idToRole,
idToSlotKind,
idToStackMax);
if (slice1 is not null)
{
errors.Add(slice1);
ThrowIfAny(errors);
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Loaded item catalog from {ItemsDirectory}: {ItemCount} item(s) across {CatalogFileCount} JSON catalog file(s).",
itemsDirectory,
rows.Count,
jsonFiles.Length);
}
return new ItemDefinitionCatalog(itemsDirectory, rows, jsonFiles.Length);
}
private static ItemDefRow ParseRow(JsonObject rowObj)
{
var id = (rowObj["id"] as JsonValue)!.GetValue();
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue();
var prototypeRole = (rowObj["prototypeRole"] as JsonValue)!.GetValue();
var stackMax = (rowObj["stackMax"] as JsonValue)!.GetValue();
var inventorySlotKind = (rowObj["inventorySlotKind"] as JsonValue)!.GetValue();
string? rarity = null;
if (rowObj["rarity"] is JsonValue rarityValue)
rarity = rarityValue.GetValue();
string? bindPolicy = null;
if (rowObj["bindPolicy"] is JsonValue bindPolicyValue)
bindPolicy = bindPolicyValue.GetValue();
int? durabilityMax = null;
if (rowObj["durabilityMax"] is JsonValue durabilityMaxValue &&
durabilityMaxValue.TryGetValue(out var dmax))
{
durabilityMax = dmax;
}
return new ItemDefRow(id, displayName, prototypeRole, stackMax, inventorySlotKind, rarity, bindPolicy, durabilityMax);
}
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} items[{index}] {loc}: {kv.Key} — {kv.Value}");
}
}
private static void ThrowIfAny(List errors)
{
if (errors.Count == 0)
return;
var sb = new StringBuilder();
sb.AppendLine("Item catalog validation failed:");
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
sb.AppendLine(e);
throw new InvalidOperationException(sb.ToString().TrimEnd());
}
}