neon-sprawl/server/NeonSprawl.Server/Game/Quests/QuestDefinitionCatalogLoade...

387 lines
14 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.Quests;
/// <summary>Loads and validates <c>content/quests/*_quests.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-113).</summary>
public static class QuestDefinitionCatalogLoader
{
private static readonly Lock SchemaLoadLock = new();
private static JsonSchema? _questObjectiveDefSchema;
private static JsonSchema? _questStepDefSchema;
private static JsonSchema? _questDefSchema;
/// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
public static QuestDefinitionCatalog Load(
string questsDirectory,
string questDefSchemaPath,
string questStepDefSchemaPath,
string questObjectiveDefSchemaPath,
IReadOnlySet<string> knownItemIds,
IReadOnlySet<string> knownRecipeIds,
IReadOnlySet<string> knownEncounterIds,
ILogger logger)
{
questsDirectory = Path.GetFullPath(questsDirectory);
questDefSchemaPath = Path.GetFullPath(questDefSchemaPath);
questStepDefSchemaPath = Path.GetFullPath(questStepDefSchemaPath);
questObjectiveDefSchemaPath = Path.GetFullPath(questObjectiveDefSchemaPath);
var errors = new List<string>();
if (!File.Exists(questDefSchemaPath))
errors.Add($"error: missing schema file {questDefSchemaPath}");
if (!File.Exists(questStepDefSchemaPath))
errors.Add($"error: missing schema file {questStepDefSchemaPath}");
if (!File.Exists(questObjectiveDefSchemaPath))
errors.Add($"error: missing schema file {questObjectiveDefSchemaPath}");
if (!Directory.Exists(questsDirectory))
errors.Add($"error: missing directory {questsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
var jsonFiles = Directory.GetFiles(questsDirectory, "*_quests.json", SearchOption.TopDirectoryOnly)
.OrderBy(p => p, StringComparer.Ordinal)
.ToArray();
if (jsonFiles.Length == 0)
errors.Add($"error: no *_quests.json files under {questsDirectory}");
if (errors.Count > 0)
ThrowIfAny(errors);
EnsureQuestSchemasLoaded(questObjectiveDefSchemaPath, questStepDefSchemaPath, questDefSchemaPath);
var defSchema = _questDefSchema!;
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
var questIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
var rows = new Dictionary<string, QuestDefRow>(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 questsNode = rootObj["quests"];
if (questsNode is not JsonArray questsArray)
{
errors.Add($"error: {path}: expected top-level 'quests' array");
continue;
}
for (var i = 0; i < questsArray.Count; i++)
{
var quest = questsArray[i];
if (quest is not JsonObject rowObj)
{
errors.Add($"error: {path}: quests[{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} quests[{i}] (root): schema validation failed");
errors.AddRange(schemaMsgs);
}
var qid = (rowObj["id"] as JsonValue)?.GetValue<string>();
if (qid is not null && eval.IsValid)
{
if (questIdToSourceFile.TryGetValue(qid, out var prevPath))
{
errors.Add($"error: duplicate quest id '{qid}' in {prevPath} and {path}");
continue;
}
var stepParseErrors = TryParseSteps(rowObj, path, i, out var steps, out _, out _);
errors.AddRange(stepParseErrors);
questIdToSourceFile[qid] = path;
rows[qid] = ParseRow(rowObj, steps);
}
}
}
ThrowIfAny(errors);
var e7m1 = PrototypeE7M1QuestCatalogRules.TryGetE7M1GateError(questIdToSourceFile);
if (e7m1 is not null)
{
errors.Add(e7m1);
ThrowIfAny(errors);
}
var prereq = PrototypeE7M1QuestCatalogRules.TryGetPrerequisiteGateError(rows);
if (prereq is not null)
{
errors.Add(prereq);
ThrowIfAny(errors);
}
var crossRef = PrototypeE7M1QuestCatalogRules.TryGetCrossRefError(
rows,
knownItemIds,
knownRecipeIds,
knownEncounterIds);
if (crossRef is not null)
{
errors.Add(crossRef);
ThrowIfAny(errors);
}
var chainTerminal = PrototypeE7M1QuestCatalogRules.TryGetChainTerminalGateError(rows);
if (chainTerminal is not null)
{
errors.Add(chainTerminal);
ThrowIfAny(errors);
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Loaded quest catalog from {QuestsDirectory}: {QuestCount} quest(s) across {CatalogFileCount} JSON catalog file(s).",
questsDirectory,
rows.Count,
jsonFiles.Length);
}
return new QuestDefinitionCatalog(questsDirectory, rows, jsonFiles.Length);
}
private static List<string> TryParseSteps(
JsonObject rowObj,
string path,
int questIndex,
out IReadOnlyList<QuestStepDefRow> steps,
out HashSet<string> stepIdsSeen,
out HashSet<string> objectiveIdsSeen)
{
var errors = new List<string>();
stepIdsSeen = new HashSet<string>(StringComparer.Ordinal);
objectiveIdsSeen = new HashSet<string>(StringComparer.Ordinal);
var parsedSteps = new List<QuestStepDefRow>();
var stepsNode = rowObj["steps"] as JsonArray;
if (stepsNode is null)
{
steps = parsedSteps;
return errors;
}
for (var si = 0; si < stepsNode.Count; si++)
{
if (stepsNode[si] is not JsonObject stepObj)
continue;
var sid = (stepObj["id"] as JsonValue)?.GetValue<string>();
if (sid is not null)
{
if (stepIdsSeen.Contains(sid))
{
errors.Add($"error: {path} quests[{questIndex}] steps[{si}]: duplicate step id '{sid}'");
}
else
{
stepIdsSeen.Add(sid);
}
}
var objectivesNode = stepObj["objectives"] as JsonArray;
if (objectivesNode is null)
continue;
for (var oi = 0; oi < objectivesNode.Count; oi++)
{
if (objectivesNode[oi] is not JsonObject objObj)
continue;
var oid = (objObj["id"] as JsonValue)?.GetValue<string>();
if (oid is not null)
{
if (objectiveIdsSeen.Contains(oid))
{
errors.Add(
$"error: {path} quests[{questIndex}] steps[{si}] objectives[{oi}]: " +
$"duplicate objective id '{oid}' within quest");
}
else
{
objectiveIdsSeen.Add(oid);
}
}
}
}
for (var si = 0; si < stepsNode.Count; si++)
{
if (stepsNode[si] is JsonObject stepObj)
parsedSteps.Add(ParseStep(stepObj));
}
steps = parsedSteps;
return errors;
}
private static QuestDefRow ParseRow(JsonObject rowObj, IReadOnlyList<QuestStepDefRow> steps)
{
var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
var prerequisiteQuestIds = ParseStringArray(rowObj["prerequisiteQuestIds"] as JsonArray);
return new QuestDefRow(id, displayName, prerequisiteQuestIds, steps);
}
private static QuestStepDefRow ParseStep(JsonObject stepObj)
{
var id = (stepObj["id"] as JsonValue)!.GetValue<string>();
var displayName = (stepObj["displayName"] as JsonValue)!.GetValue<string>();
var objectivesNode = stepObj["objectives"] as JsonArray ?? [];
var objectives = new List<QuestObjectiveDefRow>(objectivesNode.Count);
foreach (var node in objectivesNode)
{
if (node is JsonObject objObj)
objectives.Add(ParseObjective(objObj));
}
return new QuestStepDefRow(id, displayName, objectives);
}
private static QuestObjectiveDefRow ParseObjective(JsonObject objObj)
{
var id = (objObj["id"] as JsonValue)!.GetValue<string>();
var kind = (objObj["kind"] as JsonValue)!.GetValue<string>();
string? itemId = null;
int? quantity = null;
string? recipeId = null;
string? encounterId = null;
if (objObj["itemId"] is JsonValue itemValue && itemValue.TryGetValue<string>(out var item))
itemId = item;
if (objObj["quantity"] is JsonValue qtyValue && qtyValue.TryGetValue<int>(out var qty))
quantity = qty;
if (objObj["recipeId"] is JsonValue recipeValue && recipeValue.TryGetValue<string>(out var recipe))
recipeId = recipe;
if (objObj["encounterId"] is JsonValue encounterValue && encounterValue.TryGetValue<string>(out var encounter))
encounterId = encounter;
return new QuestObjectiveDefRow(id, kind, itemId, quantity, recipeId, encounterId);
}
private static IReadOnlyList<string> ParseStringArray(JsonArray? array)
{
if (array is null)
return [];
var values = new List<string>(array.Count);
foreach (var node in array)
{
if (node is JsonValue value && value.TryGetValue<string>(out var s))
values.Add(s);
}
return values;
}
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} quests[{index}] {loc}: {kv.Key} — {kv.Value}");
}
}
/// <summary>Registers objective → step → def in <see cref="SchemaRegistry.Global"/> once per process (NEO-113).</summary>
private static void EnsureQuestSchemasLoaded(
string questObjectiveDefSchemaPath,
string questStepDefSchemaPath,
string questDefSchemaPath)
{
lock (SchemaLoadLock)
{
if (_questDefSchema is not null)
return;
var objectiveSchema = JsonSchema.FromText(File.ReadAllText(questObjectiveDefSchemaPath));
SchemaRegistry.Global.Register(objectiveSchema);
_questObjectiveDefSchema = objectiveSchema;
var stepSchema = JsonSchema.FromText(File.ReadAllText(questStepDefSchemaPath));
SchemaRegistry.Global.Register(stepSchema);
_questStepDefSchema = stepSchema;
var defSchema = JsonSchema.FromText(File.ReadAllText(questDefSchemaPath));
SchemaRegistry.Global.Register(defSchema);
_questDefSchema = defSchema;
}
}
private static void ThrowIfAny(List<string> errors)
{
if (errors.Count == 0)
return;
var sb = new StringBuilder();
sb.AppendLine("Quest catalog validation failed:");
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
sb.AppendLine(e);
throw new InvalidOperationException(sb.ToString().TrimEnd());
}
}