PlotDirector/PlotLine/Services/ProjectBackupNarrative.cs

105 lines
6.8 KiB
C#

using PlotLine.Models;
namespace PlotLine.Services;
internal static class ProjectBackupNarrative
{
internal sealed record EventSource(int? RunID,int CandidateID,int? CandidateEventID,string? EventKey,int? EvidenceSceneID,int? EvidenceSortOrder);
private sealed class SourceIndex
{
internal readonly Dictionary<(int Reference,string Key),List<(EventSource Link,int? AcceptedID)>> Events=[];
internal readonly Dictionary<(int Reference,string Key),List<EventSource>> Evidence=[];
internal SourceIndex(ProjectBackupExport backup)
{
foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvents)
{
var key=(row.NarrativeCandidateEventID,$"{row.WholeBookPlotSynthesisRunID}:{row.NarrativeCandidateID}:{row.EventKey}");
if(!Events.TryGetValue(key,out var matches))Events[key]=matches=[];
matches.Add((new(row.WholeBookPlotSynthesisRunID,row.NarrativeCandidateID,row.NarrativeCandidateEventID,row.EventKey,null,null),row.AcceptedThreadEventID));
}
var candidates=backup.Data.StoryIntelligenceNarrativeCandidates.ToDictionary(row=>row.NarrativeCandidateID);
foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvidence)
{
var candidate=candidates[row.NarrativeCandidateID];
var key=(candidate.NarrativeCandidateID,$"{candidate.WholeBookPlotSynthesisRunID}:{candidate.NarrativeCandidateID}:{row.SceneID}:{row.SortOrder}");
if(!Evidence.TryGetValue(key,out var matches))Evidence[key]=matches=[];
matches.Add(new(candidate.WholeBookPlotSynthesisRunID,candidate.NarrativeCandidateID,null,null,row.SceneID,row.SortOrder));
}
}
}
private static List<EventSource> Sources(SourceIndex index,ThreadEvent canonical)
{
if(!string.Equals(canonical.Source,WholeBookPlotSynthesisSources.WholeBook,StringComparison.OrdinalIgnoreCase)
|| !canonical.SourceReferenceID.HasValue || canonical.SourceKey is null)return [];
var key=(canonical.SourceReferenceID.Value,canonical.SourceKey);
var events=index.Events.GetValueOrDefault(key) ?? [];
var accepted=events.Where(row=>row.AcceptedID==canonical.ThreadEventID).ToArray();
if(accepted.Length==1)return [accepted[0].Link];
return events.Select(row=>row.Link).Concat(index.Evidence.GetValueOrDefault(key) ?? []).Distinct().ToList();
}
internal static Dictionary<int,EventSource> CaptureSources(ProjectBackupExport backup)
{
var links=new Dictionary<int,EventSource>();
var index=new SourceIndex(backup);
foreach(var row in backup.Data.ThreadEvents)
{
var matches=Sources(index,row);
if(matches.Count==1)links[row.ThreadEventID]=matches[0];
}
return links;
}
internal static string? ValidatePortableSources(ProjectBackupExport backup)
{
// Older backups did not carry this graph; their copies keep the established detached-history behaviour.
if(backup.Data.StoryIntelligenceNarrativeCandidates.Count==0 && backup.Data.StoryIntelligenceNarrativeCandidateEvents.Count==0)return null;
var index=new SourceIndex(backup);
foreach(var row in backup.Data.ThreadEvents.Where(row=>string.Equals(row.Source,WholeBookPlotSynthesisSources.WholeBook,StringComparison.OrdinalIgnoreCase) && row.SourceReferenceID.HasValue))
if(Sources(index,row).Count!=1)return "A narrative event source is missing or ambiguous in this backup. Its source identity cannot safely be copied; same-project restore retains the original history.";
return null;
}
internal static string? Validate(ProjectBackupExport backup)
{
var rows=backup.Data.StoryIntelligenceNarrativeCandidates.ToDictionary(row=>row.NarrativeCandidateID);
var runs=backup.Data.WholeBookPlotSynthesisRuns.ToDictionary(row=>row.WholeBookPlotSynthesisRunID);
var seeds=backup.Data.AuthorPlotSeeds.ToDictionary(row=>row.AuthorPlotSeedID);
var chapters=backup.Data.Chapters.ToDictionary(row=>row.ChapterID,row=>row.BookID);
var sceneBooks=backup.Data.Scenes.ToDictionary(row=>row.SceneID,row=>chapters[row.ChapterID]);
foreach(var row in rows.Values)
{
if(row.WholeBookPlotSynthesisRunID.HasValue && runs[row.WholeBookPlotSynthesisRunID.Value].BookID!=row.BookID)
return "A narrative candidate belongs to a different book from its synthesis run.";
if(row.AuthorPlotSeedID.HasValue && seeds[row.AuthorPlotSeedID.Value].BookID!=row.BookID)
return "A narrative candidate references another book's author seed.";
foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID})
if(target.HasValue && rows[target.Value].BookID!=row.BookID)return "A narrative parent or merge target belongs to another book.";
if(row.ParentNarrativeCandidateID.HasValue && !string.IsNullOrEmpty(row.ParentCandidateKey)
&& !row.ParentCandidateKey.Equals(rows[row.ParentNarrativeCandidateID.Value].CandidateKey,StringComparison.OrdinalIgnoreCase))
return "A narrative parent key does not match its candidate reference.";
}
foreach(var evidence in backup.Data.StoryIntelligenceNarrativeCandidateEvidence)
if(sceneBooks[evidence.SceneID]!=rows[evidence.NarrativeCandidateID].BookID)return "Narrative evidence references a scene in another book.";
foreach(var item in backup.Data.StoryIntelligenceNarrativeCandidateEvents)
{
var parent=rows[item.NarrativeCandidateID];
if(sceneBooks[item.SceneID]!=parent.BookID)return "A narrative candidate event references another book's scene.";
if(item.WholeBookPlotSynthesisRunID.HasValue && runs[item.WholeBookPlotSynthesisRunID.Value].BookID!=parent.BookID)
return "A narrative candidate event references another book's synthesis run.";
}
// Iterative topological check avoids recursion on large or malicious parent/merge chains.
var incoming=rows.Keys.ToDictionary(id=>id,_=>0);
foreach(var row in rows.Values)foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID})if(target.HasValue)incoming[target.Value]++;
var ready=new Queue<int>(incoming.Where(pair=>pair.Value==0).Select(pair=>pair.Key));var visited=0;
while(ready.TryDequeue(out var id))
{
visited++;var row=rows[id];
foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID})if(target.HasValue && --incoming[target.Value]==0)ready.Enqueue(target.Value);
}
return visited==rows.Count ? null : "The narrative parent or merge graph contains a cycle.";
}
}