PlotDirector/PlotLine/Services/ProjectBackupEntityReview.cs

151 lines
9.7 KiB
C#

using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using PlotLine.Models;
namespace PlotLine.Services;
internal static class ProjectBackupEntityReview
{
private sealed record Reference(string Path,string Table,bool Required=false,string? LookupName=null);
internal static string? CanonicalTable(string? module) => module?.ToLowerInvariant() switch
{
"characters"=>"Characters", "locations"=>"Locations", "assets"=>"StoryAssets",
"relationships"=>"CharacterRelationships", "knowledge"=>"CharacterKnowledge", _=>null
};
private static Reference[] References(string module) => module.ToLowerInvariant() switch
{
"characters"=>[new("existingCharacterID","Characters"),new("selectedExistingCharacterID","Characters"),new("existingCharacterOptions[].characterID","Characters",true)],
"locations"=>[new("existingLocationID","Locations"),new("proposedParentLocationID","Locations"),new("existingParentLocationID","Locations"),new("significance.keyScenes[].sceneID","Scenes",true),new("significance.keyScenes[].chapterID","Chapters",true),new("significance.keyScenes[].bookID","Books",true)],
"assets"=>[new("existingAssetID","StoryAssets")],
"relationships"=>[new("characterAID","Characters",true),new("characterBID","Characters",true),new("firstSceneID","Scenes"),new("existingRelationshipID","CharacterRelationships"),new("observations[].sceneID","Scenes",true),new("relationshipTypeID","RelationshipTypes",false,"relationshipType"),new("relationshipStateID","RelationshipStates",false,"relationshipState")],
"knowledge"=>[new("characterID","Characters",true),new("storyAssetID","StoryAssets"),new("existingKnowledgeID","CharacterKnowledge"),new("observations[].sceneID","Scenes",true),new("knowledgeStateID","KnowledgeStates",false,"knowledgeStateName")],
_=>[]
};
private static string? Key(JsonObject node,string name)
{
var keys=node.Select(p=>p.Key).Where(key=>key.Equals(name,StringComparison.OrdinalIgnoreCase)).ToArray();
if(keys.Length>1)throw new JsonException("Review payload has ambiguous property names.");
return keys.FirstOrDefault();
}
private static IEnumerable<(JsonObject Owner,string Key,int ID)> Values(JsonObject root,Reference reference)
{
var parts=reference.Path.Split('.');
IEnumerable<(JsonObject Owner,string Key,int ID)> Visit(JsonObject owner,int index)
{
var arrayPart=parts[index].EndsWith("[]",StringComparison.Ordinal);
var key=Key(owner,arrayPart ? parts[index][..^2] : parts[index]);
if(index==parts.Length-1)
{
if(key is null || owner[key] is null)
{
if(reference.Required)throw new JsonException("Review payload is missing a required entity reference.");
yield break;
}
if(owner[key] is not JsonValue value || !value.TryGetValue<int>(out var id) || id<0 || id==0 && reference.LookupName is null)
throw new JsonException("Review payload has an invalid entity reference.");
yield return(owner,key,id);yield break;
}
if(key is null)yield break;
if(arrayPart)
{
if(owner[key] is not JsonArray array)throw new JsonException("Review payload reference collection must be an array.");
foreach(var item in array)
{
if(item is not JsonObject record)throw new JsonException("Review payload reference records must be objects.");
foreach(var result in Visit(record,index+1))yield return result;
}
}
else if(owner[key] is not null)
{
if(owner[key] is not JsonObject child)throw new JsonException("Review payload reference container must be an object.");
foreach(var result in Visit(child,index+1))yield return result;
}
}
return Visit(root,0);
}
private static JsonObject Payload(string? json) => !string.IsNullOrWhiteSpace(json) && JsonNode.Parse(json) is JsonObject root
? root : throw new JsonException("Review payload must be a JSON object.");
// These formats are generated by the relationship and knowledge import services.
// Other legacy opaque tokens are retained rather than interpreted as arbitrary text.
internal static string? RemapKey(string module,string? key,Func<string,int,int> remap)
{
if(string.IsNullOrEmpty(key))return key;
static int ID(string value)=>int.TryParse(value,out var id) && id>0 ? id : throw new JsonException("Review key has an invalid source identifier.");
if(module.Equals("Knowledge",StringComparison.OrdinalIgnoreCase))
{
var match=Regex.Match(key,@"^(\d+):(.*)$",RegexOptions.CultureInvariant);
return match.Success ? $"{remap("Characters",ID(match.Groups[1].Value))}:{match.Groups[2].Value}" : key;
}
if(!module.Equals("Relationships",StringComparison.OrdinalIgnoreCase))return key;
var scene=Regex.Match(key,@"^scene:(\d+):(\d+)(>|:)(\d+):(.+)$",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant);
if(scene.Success)
{
var a=remap("Characters",ID(scene.Groups[2].Value));var b=remap("Characters",ID(scene.Groups[4].Value));
var pair=scene.Groups[3].Value==">" ? $"{a}>{b}" : $"{Math.Min(a,b)}:{Math.Max(a,b)}";
return $"scene:{remap("Scenes",ID(scene.Groups[1].Value))}:{pair}:{scene.Groups[5].Value}";
}
var legacy=Regex.Match(key,@"^(\d+):(\d+)$",RegexOptions.CultureInvariant);
if(!legacy.Success)return key;
var first=remap("Characters",ID(legacy.Groups[1].Value));var second=remap("Characters",ID(legacy.Groups[2].Value));
return $"{Math.Min(first,second)}:{Math.Max(first,second)}";
}
internal static string? Validate(ProjectBackupExport backup)
{
var data=backup.Data;
var ids=new Dictionary<string,HashSet<int>> {
["Books"]=data.Books.Select(x=>x.BookID).ToHashSet(),["Chapters"]=data.Chapters.Select(x=>x.ChapterID).ToHashSet(),
["Characters"]=data.Characters.Select(x=>x.CharacterID).ToHashSet(),["Locations"]=data.Locations.Select(x=>x.LocationID).ToHashSet(),
["StoryAssets"]=data.StoryAssets.Select(x=>x.StoryAssetID).ToHashSet(),["Scenes"]=data.Scenes.Select(x=>x.SceneID).ToHashSet(),
["CharacterRelationships"]=data.CharacterRelationships.Select(x=>x.CharacterRelationshipID).ToHashSet(),["CharacterKnowledge"]=data.CharacterKnowledge.Select(x=>x.CharacterKnowledgeID).ToHashSet()
};
var generations=data.StoryIntelligenceReviewCandidateGenerations.ToDictionary(x=>x.ReviewCandidateGenerationID);
if(generations.Values.Any(row=>CanonicalTable(row.Module) is null))return "Project backup contains an unsupported review module.";
try
{
int ValidateID(string table,int id)
{
if(!ids[table].Contains(id))throw new JsonException("Review reference is missing or foreign.");
return id;
}
foreach(var row in data.StoryIntelligenceReviewCandidates)
{
var table=CanonicalTable(row.Module);
if(table is null)return "Project backup contains an unsupported review module.";
var generation=generations[row.ReviewCandidateGenerationID];
if(row.ProjectID!=generation.ProjectID || row.BookID!=generation.BookID || !row.Module.Equals(generation.Module,StringComparison.OrdinalIgnoreCase))
return "Project backup candidate does not belong to its review generation.";
foreach(var id in new[]{row.ExistingCanonicalID,row.DecisionCanonicalID})if(id.HasValue)ValidateID(table,id.Value);
if(string.IsNullOrWhiteSpace(row.StableKey))return "Project backup review candidate is missing its stable key.";
RemapKey(row.Module,row.StableKey,ValidateID);RemapKey(row.Module,row.DecisionTargetKey,ValidateID);
var root=Payload(row.CandidatePayloadJson);var key=Key(root,"key");
if(key is null || root[key] is not JsonValue token || !token.TryGetValue<string>(out var payloadKey) || !row.StableKey.Equals(payloadKey,StringComparison.OrdinalIgnoreCase))
return "Project backup candidate payload has a different review key.";
foreach(var reference in References(row.Module))
{
if(reference.LookupName is not null)Key(root,reference.LookupName);
foreach(var value in Values(root,reference))if(ids.ContainsKey(reference.Table))ValidateID(reference.Table,value.ID);
}
}
}
catch(JsonException) { return "Project backup review payload or key contains an invalid, missing or foreign reference."; }
return null;
}
internal static string RemapPayload(string module,string json,Func<string,int,int> remap,Func<string,int,string?,int> remapLookup)
{
var root=Payload(json);
foreach(var reference in References(module))
{
var nameKey=reference.LookupName is null ? null : Key(root,reference.LookupName);
var name=nameKey is not null && root[nameKey] is JsonValue nameValue && nameValue.TryGetValue<string>(out var label) ? label : null;
foreach(var value in Values(root,reference).ToArray())value.Owner[value.Key]=reference.LookupName is null ? remap(reference.Table,value.ID) : remapLookup(reference.Table,value.ID,name);
}
var key=Key(root,"key")!;
root[key]=RemapKey(module,root[key]!.GetValue<string>(),remap);
return root.ToJsonString();
}
}