using PlotLine.Models; namespace PlotLine.Services.Manuscript; // Recovery uses the existing typed graph maps. Occurrence/scene/evidence GUIDs survive; live leases do not. public static class ParagraphRecovery { public static void Validate(ProjectBackupExport graph) { if(graph.Recovery==null){if(graph.FormatVersion=="1.5")throw new ArgumentException("Paragraph recovery state is missing.");return;} var states=graph.Recovery.ParagraphManuscripts; if(graph.FormatVersion=="1.5"&&states==null)throw new ArgumentException("Paragraph recovery state is missing from this backup."); if(states==null)return; if(graph.FormatVersion!="1.5"||states.Any(s=>s==null))throw new ArgumentException("Paragraph recovery requires project format 1.5."); if(states.Select(s=>s.BookId).Distinct().Count()!=states.Count)throw new ArgumentException("Duplicate paragraph manuscripts."); foreach(var state in states){ if(state.Paragraphs==null||state.Scenes==null||state.Chapters==null||state.Evidence==null||state.Undo==null||state.EventPositions==null||state.Paragraphs.Any(p=>p?.Occurrence?.Text==null)||state.Scenes.Any(s=>s==null)||state.Evidence.Any(e=>e==null||e.OriginalText==null||e.ConfirmedText==null||e.CurrentText==null)||state.Chapters.Any(c=>c==null)||state.EventPositions.Any(e=>e==null)||state.Undo.Any(l=>l==null||l.Scenes==null||l.Chapters==null||l.EventPositions==null||l.Assignments==null||l.Scenes.Any(s=>s==null)||l.Chapters.Any(c=>c==null)||l.EventPositions.Any(e=>e==null)||l.Assignments.Any(a=>a==null)))throw new ArgumentException("Paragraph recovery is incomplete."); if(state.ChapterCheckpoints==null||state.ChapterCheckpoints.Any(c=>c==null||c.Algorithm!=PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.Version||!state.Chapters.Any(h=>h.CanonicalId==c.ChapterId&&h.HeadingId==c.HeadingId)))throw new ArgumentException("Chapter checkpoint recovery references are invalid or unsupported."); ParagraphManuscriptEngine.Validate(state); if(state.Evidence.Any(e=>e.State is not ("Verified" or "Needs review" or "Missing"))||state.Evidence.GroupBy(e=>(e.EventKind,e.EventId)).Any(g=>g.Count(e=>e.Primary)>1))throw new ArgumentException("Paragraph evidence state or primary passage is invalid."); int end=0;for(int n=0;n16*1024*1024)throw new ArgumentException("Paragraph positions are not contiguous.");end=p.End;} if(state.Version!=1||state.ManuscriptId==Guid.Empty||state.ProjectId!=graph.Project?.ProjectID||!graph.Data.Books.Any(b=>b.BookID==state.BookId))throw new ArgumentException("Paragraph manuscript scope is invalid."); bool Chapter(int id)=>graph.Data.Chapters.Any(c=>c.ChapterID==id&&c.BookID==state.BookId); bool Scene(int id)=>graph.Data.Scenes.Any(s=>s.SceneID==id&&Chapter(s.ChapterID)); bool Event(ManuscriptEventOption e)=>e.Kind switch{"Knowledge"=>graph.Data.CharacterKnowledge.Any(k=>k.CharacterKnowledgeID==e.Id&&Scene(k.SceneID)),"Relationship"=>graph.Data.RelationshipEvents.Any(r=>r.RelationshipEventID==e.Id&&Scene(r.SceneID)),_=>false}; void Layout(IEnumerable scenes,IEnumerable chapters,IEnumerable events){if(scenes.Any(s=>!Chapter(s.ChapterId)||(s.CanonicalId>0&&!Scene(s.CanonicalId)))||chapters.Any(c=>c.CanonicalId>0&&!Chapter(c.CanonicalId))||events.Any(e=>!Event(e)||!Scene(e.SceneId)))throw new ArgumentException("Paragraph recovery has an unresolved chapter, scene or event reference.");} Layout(state.Scenes,state.Chapters,state.EventPositions);foreach(var layout in state.Undo)Layout(layout.Scenes,layout.Chapters,layout.EventPositions); if(state.Paragraphs.Any(p=>p.ChapterId.HasValue&&!Chapter(p.ChapterId.Value))||state.Evidence.Any(e=>!Event(new(){Kind=e.EventKind,Id=e.EventId})||(e.DerivedSceneId>0&&!Scene(e.DerivedSceneId.Value))))throw new ArgumentException("Paragraph evidence belongs to another book."); var ids=state.Paragraphs.Select(p=>p.Occurrence.Id).ToHashSet();var sceneIds=state.Scenes.Select(s=>s.Id).ToHashSet(); if(state.Undo.Any(l=>l.Assignments.Any(a=>!ids.Contains(a.ParagraphId)||(a.ChapterId.HasValue&&!Chapter(a.ChapterId.Value))||(a.SceneId.HasValue&&!sceneIds.Contains(a.SceneId.Value)))))throw new ArgumentException("Paragraph undo state has unresolved identities."); } } public static void Remap(ProjectBackupExport graph,Func id) { foreach(var state in graph.Recovery.ParagraphManuscripts??[]){ state.BookId=id("Books",state.BookId);state.ProjectId=graph.Project!.ProjectID; int EventId(string kind,int value)=>id(kind=="Knowledge"?"CharacterKnowledge":kind=="Relationship"?"RelationshipEvents":throw new ArgumentException("Unknown evidence type."),value); void Layout(IEnumerable scenes,IEnumerable chapters,IEnumerable events){foreach(var s in scenes){if(s.CanonicalId>0)s.CanonicalId=id("Scenes",s.CanonicalId);s.ChapterId=id("Chapters",s.ChapterId);}foreach(var c in chapters)if(c.CanonicalId>0)c.CanonicalId=id("Chapters",c.CanonicalId);foreach(var e in events){e.Id=EventId(e.Kind,e.Id);e.SceneId=id("Scenes",e.SceneId);}} Layout(state.Scenes,state.Chapters,state.EventPositions); foreach(var p in state.Paragraphs)if(p.ChapterId.HasValue)p.ChapterId=id("Chapters",p.ChapterId.Value); foreach(var e in state.Evidence){e.EventId=EventId(e.EventKind,e.EventId);if(e.DerivedSceneId>0)e.DerivedSceneId=id("Scenes",e.DerivedSceneId.Value);} foreach(var layout in state.Undo){Layout(layout.Scenes,layout.Chapters,layout.EventPositions);foreach(var a in layout.Assignments)if(a.ChapterId.HasValue)a.ChapterId=id("Chapters",a.ChapterId.Value);} if(state.ChapterCheckpoints.Count>0){foreach(var checkpoint in state.ChapterCheckpoints)checkpoint.ChapterId=id("Chapters",checkpoint.ChapterId); var historical=state.ChapterCheckpoints.ToDictionary(c=>c.ChapterId,c=>c.LastSuccessfulSyncUtc);state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,state.Revision).ToList();foreach(var checkpoint in state.ChapterCheckpoints){checkpoint.LastSuccessfulSyncUtc=historical.GetValueOrDefault(checkpoint.ChapterId);checkpoint.Status="Not yet checked";checkpoint.Message="Restored source checkpoint; this installation has not validated live Word positions.";}} Detach(state); } } public static void VerifyStored(ProjectBackupExport expected,ProjectBackupExport actual,IEnumerable books) { var scope=books.ToHashSet();var left=(expected.Recovery.ParagraphManuscripts??[]).Where(s=>scope.Contains(s.BookId)).ToArray();var right=(actual.Recovery.ParagraphManuscripts??[]).Where(s=>scope.Contains(s.BookId)).ToArray(); if(left.Length!=right.Length)throw new InvalidOperationException("Paragraph recovery verification failed; nothing was committed."); foreach(var source in left){var saved=right.SingleOrDefault(s=>s.BookId==source.BookId);var canonical=ParagraphManuscriptEngine.Clone(source);Detach(canonical);if(saved==null||System.Text.Json.JsonSerializer.Serialize(canonical)!=System.Text.Json.JsonSerializer.Serialize(saved))throw new InvalidOperationException("Restored paragraph identities, groupings or evidence differ; nothing was committed.");} } public static void Detach(ParagraphManuscript state){state.SessionId=Guid.Empty;state.WordRevision=-1;state.LastRequestId=Guid.Empty;if(state.Mode!="Off")state.Mode="Manual";} }