using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Json.Schema;
namespace NeonSprawl.Server.Game.Factions;
/// Loads and validates content/factions/*_factions.json using the same rules as scripts/validate_content.py (NEO-134).
public static class FactionDefinitionCatalogLoader
{
/// Loads catalogs from disk or throws with actionable messages.
public static FactionDefinitionCatalog Load(string factionsDirectory, string schemaPath, ILogger logger)
{
factionsDirectory = Path.GetFullPath(factionsDirectory);
schemaPath = Path.GetFullPath(schemaPath);
var errors = new List();
if (!File.Exists(schemaPath))
errors.Add($"error: missing schema file {schemaPath}");
if (!Directory.Exists(factionsDirectory))
errors.Add($"error: missing directory {factionsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
string[] jsonFiles = [.. Directory.GetFiles(factionsDirectory, "*_factions.json", SearchOption.TopDirectoryOnly)
.OrderBy(p => p, StringComparer.Ordinal)];
if (jsonFiles.Length == 0)
errors.Add($"error: no *_factions.json files under {factionsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
var schema = JsonSchema.FromText(File.ReadAllText(schemaPath));
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
var factionIdToSourceFile = 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 factionsNode = rootObj["factions"];
if (factionsNode is not JsonArray factionsArray)
{
errors.Add($"error: {path}: expected top-level 'factions' array");
continue;
}
for (var i = 0; i < factionsArray.Count; i++)
{
var item = factionsArray[i];
if (item is not JsonObject rowObj)
{
errors.Add($"error: {path}: factions[{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} factions[{i}] (root): schema validation failed");
errors.AddRange(schemaMsgs);
}
var rowSchemaErrors = schemaMsgs.Count;
var fid = (rowObj["id"] as JsonValue)?.GetValue();
if (fid is not null && rowSchemaErrors == 0)
{
if (factionIdToSourceFile.TryGetValue(fid, out var prevPath))
{
errors.Add($"error: duplicate faction id '{fid}' in {prevPath} and {path}");
continue;
}
factionIdToSourceFile[fid] = path;
rows[fid] = ParseRow(rowObj);
}
}
}
ThrowIfAny(errors);
var roster = PrototypeE7M3FactionCatalogRules.TryGetRosterGateError(factionIdToSourceFile);
if (roster is not null)
{
errors.Add(roster);
ThrowIfAny(errors);
}
var standingBand = PrototypeE7M3FactionCatalogRules.TryGetStandingBandGateError(rows);
if (standingBand is not null)
{
errors.Add(standingBand);
ThrowIfAny(errors);
}
var freeze = PrototypeE7M3FactionCatalogRules.TryGetFreezeGateError(rows);
if (freeze is not null)
{
errors.Add(freeze);
ThrowIfAny(errors);
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Loaded faction catalog from {FactionsDirectory}: {FactionCount} faction(s) across {CatalogFileCount} JSON catalog file(s).",
factionsDirectory,
rows.Count,
jsonFiles.Length);
}
return new FactionDefinitionCatalog(factionsDirectory, rows, jsonFiles.Length);
}
private static FactionDefRow ParseRow(JsonObject rowObj)
{
var id = (rowObj["id"] as JsonValue)!.GetValue();
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue();
var minStanding = (rowObj["minStanding"] as JsonValue)!.GetValue();
var maxStanding = (rowObj["maxStanding"] as JsonValue)!.GetValue();
var neutralStanding = (rowObj["neutralStanding"] as JsonValue)!.GetValue();
return new FactionDefRow(id, displayName, minStanding, maxStanding, neutralStanding);
}
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} factions[{index}] {loc}: {kv.Key} — {kv.Value}");
}
}
private static void ThrowIfAny(List errors)
{
if (errors.Count == 0)
return;
var sb = new StringBuilder();
sb.AppendLine("Faction catalog validation failed:");
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
sb.AppendLine(e);
throw new InvalidOperationException(sb.ToString().TrimEnd());
}
}