261 lines
9.3 KiB
C#
261 lines
9.3 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using Json.Schema;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace NeonSprawl.Server.Game.Encounters;
|
|
|
|
/// <summary>Loads and validates <c>content/reward-tables/*_reward_tables.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-101).</summary>
|
|
public static class RewardTableDefinitionCatalogLoader
|
|
{
|
|
/// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
|
|
public static RewardTableDefinitionCatalog Load(
|
|
string rewardTablesDirectory,
|
|
string rewardTableSchemaPath,
|
|
string rewardGrantRowSchemaPath,
|
|
IReadOnlySet<string> knownItemIds,
|
|
ILogger logger)
|
|
{
|
|
rewardTablesDirectory = Path.GetFullPath(rewardTablesDirectory);
|
|
rewardTableSchemaPath = Path.GetFullPath(rewardTableSchemaPath);
|
|
rewardGrantRowSchemaPath = Path.GetFullPath(rewardGrantRowSchemaPath);
|
|
|
|
var errors = new List<string>();
|
|
|
|
if (!File.Exists(rewardTableSchemaPath))
|
|
errors.Add($"error: missing schema file {rewardTableSchemaPath}");
|
|
|
|
if (!File.Exists(rewardGrantRowSchemaPath))
|
|
errors.Add($"error: missing schema file {rewardGrantRowSchemaPath}");
|
|
|
|
if (!Directory.Exists(rewardTablesDirectory))
|
|
errors.Add($"error: missing directory {rewardTablesDirectory}");
|
|
|
|
if (errors.Count > 0)
|
|
ThrowIfAny(errors);
|
|
|
|
var jsonFiles = Directory.GetFiles(rewardTablesDirectory, "*_reward_tables.json", SearchOption.TopDirectoryOnly)
|
|
.OrderBy(p => p, StringComparer.Ordinal)
|
|
.ToArray();
|
|
if (jsonFiles.Length == 0)
|
|
errors.Add($"error: no *_reward_tables.json files under {rewardTablesDirectory}");
|
|
|
|
if (errors.Count > 0)
|
|
ThrowIfAny(errors);
|
|
|
|
var grantRowSchema = JsonSchema.FromText(File.ReadAllText(rewardGrantRowSchemaPath));
|
|
SchemaRegistry.Global.Register(grantRowSchema);
|
|
var tableSchema = JsonSchema.FromText(File.ReadAllText(rewardTableSchemaPath));
|
|
SchemaRegistry.Global.Register(tableSchema);
|
|
|
|
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
|
|
|
|
var rewardTableIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
var rows = new Dictionary<string, RewardTableDefRow>(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<int>(out var schemaVersion) ||
|
|
schemaVersion != 1)
|
|
{
|
|
var got = schemaVersionNode?.ToJsonString() ?? "null";
|
|
errors.Add($"error: {path}: expected schemaVersion 1, got {got}");
|
|
continue;
|
|
}
|
|
|
|
var rewardTablesNode = rootObj["rewardTables"];
|
|
if (rewardTablesNode is not JsonArray rewardTablesArray)
|
|
{
|
|
errors.Add($"error: {path}: expected top-level 'rewardTables' array");
|
|
continue;
|
|
}
|
|
|
|
for (var i = 0; i < rewardTablesArray.Count; i++)
|
|
{
|
|
var rewardTable = rewardTablesArray[i];
|
|
if (rewardTable is not JsonObject rowObj)
|
|
{
|
|
errors.Add($"error: {path}: rewardTables[{i}] must be an object");
|
|
continue;
|
|
}
|
|
|
|
var eval = tableSchema.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} rewardTables[{i}] (root): schema validation failed");
|
|
|
|
errors.AddRange(schemaMsgs);
|
|
}
|
|
|
|
var rowSchemaErrors = schemaMsgs.Count;
|
|
|
|
var rid = (rowObj["id"] as JsonValue)?.GetValue<string>();
|
|
if (rid is not null && rowSchemaErrors == 0)
|
|
{
|
|
if (rewardTableIdToSourceFile.TryGetValue(rid, out var prevPath))
|
|
{
|
|
errors.Add($"error: duplicate reward table id '{rid}' in {prevPath} and {path}");
|
|
continue;
|
|
}
|
|
|
|
rewardTableIdToSourceFile[rid] = path;
|
|
CrossCheckFixedGrants(rowObj, path, i, knownItemIds, errors);
|
|
rows[rid] = ParseRow(rowObj);
|
|
}
|
|
}
|
|
}
|
|
|
|
ThrowIfAny(errors);
|
|
|
|
var e5m3 = PrototypeE5M3RewardTableCatalogRules.TryGetE5M3GateError(rewardTableIdToSourceFile);
|
|
if (e5m3 is not null)
|
|
{
|
|
errors.Add(e5m3);
|
|
ThrowIfAny(errors);
|
|
}
|
|
|
|
var grantContent = PrototypeE5M3RewardTableCatalogRules.TryGetGrantContentGateError(rows);
|
|
if (grantContent is not null)
|
|
{
|
|
errors.Add(grantContent);
|
|
ThrowIfAny(errors);
|
|
}
|
|
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation(
|
|
"Loaded reward table catalog from {RewardTablesDirectory}: {RewardTableCount} reward table(s) across {CatalogFileCount} JSON catalog file(s).",
|
|
rewardTablesDirectory,
|
|
rows.Count,
|
|
jsonFiles.Length);
|
|
}
|
|
|
|
return new RewardTableDefinitionCatalog(rewardTablesDirectory, rows, jsonFiles.Length);
|
|
}
|
|
|
|
private static void CrossCheckFixedGrants(
|
|
JsonObject rowObj,
|
|
string path,
|
|
int tableIndex,
|
|
IReadOnlySet<string> knownItemIds,
|
|
List<string> errors)
|
|
{
|
|
if (rowObj["fixedGrants"] is not JsonArray grantsArray)
|
|
return;
|
|
|
|
var seenGrantItemIds = new HashSet<string>(StringComparer.Ordinal);
|
|
for (var j = 0; j < grantsArray.Count; j++)
|
|
{
|
|
if (grantsArray[j] is not JsonObject grantObj)
|
|
continue;
|
|
|
|
var itemId = (grantObj["itemId"] as JsonValue)?.GetValue<string>();
|
|
if (itemId is null)
|
|
continue;
|
|
|
|
if (!seenGrantItemIds.Add(itemId))
|
|
{
|
|
errors.Add(
|
|
$"error: {path} rewardTables[{tableIndex}].fixedGrants[{j}]: duplicate itemId '{itemId}'");
|
|
}
|
|
|
|
if (!knownItemIds.Contains(itemId))
|
|
{
|
|
errors.Add(
|
|
$"error: {path} rewardTables[{tableIndex}].fixedGrants[{j}]: itemId '{itemId}' is not in item catalogs");
|
|
}
|
|
}
|
|
}
|
|
|
|
private static RewardTableDefRow ParseRow(JsonObject rowObj)
|
|
{
|
|
var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
|
|
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
|
|
var fixedGrants = ParseGrantRows(rowObj["fixedGrants"] as JsonArray);
|
|
|
|
return new RewardTableDefRow(id, displayName, fixedGrants);
|
|
}
|
|
|
|
private static IReadOnlyList<RewardGrantRow> ParseGrantRows(JsonArray? array)
|
|
{
|
|
if (array is null)
|
|
return [];
|
|
|
|
var rows = new List<RewardGrantRow>(array.Count);
|
|
foreach (var node in array)
|
|
{
|
|
if (node is not JsonObject grantObj)
|
|
continue;
|
|
|
|
var itemId = (grantObj["itemId"] as JsonValue)!.GetValue<string>();
|
|
var quantity = (grantObj["quantity"] as JsonValue)!.GetValue<int>();
|
|
rows.Add(new RewardGrantRow(itemId, quantity));
|
|
}
|
|
|
|
return rows;
|
|
}
|
|
|
|
private static List<string> CollectSchemaMessages(EvaluationResults eval, string filePath, int index)
|
|
{
|
|
var sink = new List<string>();
|
|
AppendSchemaMessages(eval, filePath, index, sink);
|
|
return sink;
|
|
}
|
|
|
|
private static void AppendSchemaMessages(EvaluationResults r, string filePath, int index, List<string> 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} rewardTables[{index}] {loc}: {kv.Key} — {kv.Value}");
|
|
}
|
|
}
|
|
|
|
private static void ThrowIfAny(List<string> errors)
|
|
{
|
|
if (errors.Count == 0)
|
|
return;
|
|
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("Reward table catalog validation failed:");
|
|
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
|
|
sb.AppendLine(e);
|
|
|
|
throw new InvalidOperationException(sb.ToString().TrimEnd());
|
|
}
|
|
}
|