using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Json.Schema;
using Microsoft.Extensions.Logging;
namespace NeonSprawl.Server.Game.Skills;
/// Loads and validates content/skills/*.json using the same rules as scripts/validate_content.py (NEO-34).
public static class SkillDefinitionCatalogLoader
{
/// Loads catalogs from disk or throws with actionable messages.
public static SkillDefinitionCatalog Load(string skillsDirectory, string schemaPath, ILogger logger)
{
skillsDirectory = Path.GetFullPath(skillsDirectory);
schemaPath = Path.GetFullPath(schemaPath);
var errors = new List();
if (!File.Exists(schemaPath))
errors.Add($"error: missing schema file {schemaPath}");
if (!Directory.Exists(skillsDirectory))
errors.Add($"error: missing directory {skillsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
var jsonFiles = Directory.GetFiles(skillsDirectory, "*.json", SearchOption.TopDirectoryOnly)
.OrderBy(p => p, StringComparer.Ordinal)
.ToArray();
if (jsonFiles.Length == 0)
errors.Add($"error: no JSON files under {skillsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
var schema = JsonSchema.FromText(File.ReadAllText(schemaPath));
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
var skillIdToSourceFile = new Dictionary(StringComparer.Ordinal);
var skillIdToCategory = 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;
}
var skillsNode = root?["skills"];
if (skillsNode is not JsonArray skillsArray)
{
errors.Add($"error: {path}: expected top-level 'skills' array");
continue;
}
for (var i = 0; i < skillsArray.Count; i++)
{
var item = skillsArray[i];
if (item is not JsonObject rowObj)
{
errors.Add($"error: {path}: skills[{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} skills[{i}] (root): schema validation failed");
errors.AddRange(schemaMsgs);
}
var rowSchemaErrors = schemaMsgs.Count;
var sid = (rowObj["id"] as JsonValue)?.GetValue();
if (sid is not null && rowSchemaErrors == 0)
{
if (skillIdToSourceFile.TryGetValue(sid, out var prevPath))
{
errors.Add($"error: duplicate skill id '{sid}' in {prevPath} and {path}");
continue;
}
skillIdToSourceFile[sid] = path;
var category = (rowObj["category"] as JsonValue)?.GetValue();
if (category is not null)
skillIdToCategory[sid] = category;
rows[sid] = ParseRow(rowObj);
}
}
}
ThrowIfAny(errors);
var slice1 = PrototypeSlice1SkillCatalogRules.TryGetSlice1GateError(skillIdToSourceFile, skillIdToCategory);
if (slice1 is not null)
{
errors.Add(slice1);
ThrowIfAny(errors);
}
logger.LogInformation(
"Loaded skill catalog from {SkillsDirectory}: {SkillCount} skill(s) across {CatalogFileCount} JSON catalog file(s).",
skillsDirectory,
rows.Count,
jsonFiles.Length);
return new SkillDefinitionCatalog(skillsDirectory, rows, jsonFiles.Length);
}
private static SkillDefRow ParseRow(JsonObject rowObj)
{
var id = (rowObj["id"] as JsonValue)!.GetValue();
var category = (rowObj["category"] as JsonValue)!.GetValue();
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue();
var kindsArray = rowObj["allowedXpSourceKinds"] as JsonArray
?? throw new InvalidOperationException("allowedXpSourceKinds missing");
var kinds = new List();
foreach (var n in kindsArray)
{
if (n is JsonValue v)
kinds.Add(v.GetValue());
}
return new SkillDefRow(id, category, displayName, kinds);
}
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} skills[{index}] {loc}: {kv.Key} — {kv.Value}");
}
}
private static void ThrowIfAny(List errors)
{
if (errors.Count == 0)
return;
var sb = new StringBuilder();
sb.AppendLine("Skill catalog validation failed:");
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
sb.AppendLine(e);
throw new InvalidOperationException(sb.ToString().TrimEnd());
}
}