PlotDirector/PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs

188 lines
23 KiB
C#

using System.Text.Json;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Models;
namespace PlotLine.Services.Manuscript;
// One reconciliation engine; the existing capture transport supplies value snapshots, never COM objects.
public static class ParagraphManuscriptEngine
{
public static ParagraphManuscript Bootstrap(int book,int project,Guid manuscript,IReadOnlyList<ParagraphOccurrence> rows,IReadOnlyList<ParagraphBootstrapScene> scenes)
{
if(manuscript==Guid.Empty||book<=0)throw new ArgumentException("A persistent manuscript and book are required.");
var state=new ParagraphManuscript{BookId=book,ProjectId=project,ManuscriptId=manuscript};
state.Scenes=scenes.Select(s=>new ParagraphScene{CanonicalId=s.SceneId,ChapterId=s.ChapterId,Title=s.Title,NeedsRefinement=s.NeedsRefinement}).ToList();
var comparison=ParagraphReconciliation.Compare([],rows);
if(rows.All(p=>p.Id!=Guid.Empty)&&rows.Select(p=>p.Id).Distinct().Count()==rows.Count)for(int i=0;i<rows.Count;i++)comparison.Current[i].Id=rows[i].Id;
foreach(var p in comparison.Current){var source=scenes.LastOrDefault(s=>p.Ordinal+1>=s.Start&&p.Ordinal+1<=s.End);var scene=source==null?null:state.Scenes.First(s=>s.CanonicalId==source.SceneId);
state.Paragraphs.Add(new(){Occurrence=p,ChapterId=scene?.ChapterId,SceneId=p.Outline==1?null:scene?.Id,Story=scene!=null&&p.Outline!=1,PositionVerified=scene!=null});}
foreach(var chapter in scenes.GroupBy(s=>s.ChapterId)){
var first=chapter.Min(s=>s.Start)-1;var heading=state.Paragraphs.LastOrDefault(p=>p.Occurrence.Ordinal<=first&&p.Occurrence.Outline==1);
state.Chapters.Add(new(){CanonicalId=chapter.Key,HeadingId=heading?.Occurrence.Id??Guid.Empty,Title=heading?.Occurrence.Text.Trim()??"Chapter"});
}
foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){var chapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==p.Occurrence.Id);p.ChapterId=chapter?.CanonicalId;p.PositionVerified=p.ChapterId>0;}
state.SnapshotHash=Hash(rows);state.UpdatedUtc=DateTime.UtcNow;Validate(state);return state;
}
public static string Hash(IReadOnlyList<ParagraphOccurrence> rows)=>ParagraphReconciliation.SnapshotFingerprint(rows);
public static ParagraphManuscript Clone(ParagraphManuscript state)=>JsonSerializer.Deserialize<ParagraphManuscript>(JsonSerializer.Serialize(state))!;
public static void Reconcile(ParagraphManuscript state,IReadOnlyList<ParagraphOccurrence> rows)
{
var comparison=ParagraphReconciliation.Compare(state.Paragraphs.Select(p=>p.Occurrence).ToArray(),rows);var old=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var next=comparison.Current;
RefineChapterIdentities(state,rows,next);
var index=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
var chapterHeadings=state.Chapters.Where(c=>index.ContainsKey(c.HeadingId)).ToDictionary(c=>c.HeadingId);
if(state.Chapters.Any(c=>c.CanonicalId==0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("An excluded manuscript section boundary cannot be reliably identified. Review the Word structure before synchronising; no saved manuscript was changed.");
if(state.Chapters.Any(c=>c.CanonicalId>0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("A saved chapter boundary cannot be reliably identified. Review the Word chapter structure before synchronising; no saved manuscript was changed.");
var excludedAt=new bool[next.Length];bool excluded=false;
var chapterAt=new int?[next.Length];int? currentChapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==Guid.Empty)?.CanonicalId;
for(int n=0;n<next.Length;n++){if(chapterHeadings.TryGetValue(next[n].Id,out var binding)){excluded=binding.CanonicalId==0;currentChapter=excluded?null:binding.CanonicalId;}else if(next[n].Outline==1){currentChapter=null;excluded=false;}chapterAt[n]=currentChapter;excludedAt[n]=excluded;}
var oldGroups=state.Paragraphs.Where(p=>p.SceneId.HasValue).GroupBy(p=>p.SceneId!.Value).ToDictionary(g=>g.Key,g=>g.ToArray());
var starts=new List<(int At,ParagraphScene Scene,bool Verified)>();
foreach(var scene in state.Scenes.Where(s=>!s.Retired)){
var prior=oldGroups.GetValueOrDefault(scene.Id)??[];if(prior.Length==0){scene.NeedsRefinement=true;continue;}
if(index.TryGetValue(prior[0].Occurrence.Id,out var at)){
// A moved scene-start paragraph alone is not proof that the whole scene moved.
var positions=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
var complete=positions.Length==prior.Length&&positions[^1]-positions[0]+1==positions.Length;
if(complete&&chapterAt[positions[0]].HasValue&&positions.All(pos=>chapterAt[pos]==chapterAt[positions[0]]))scene.ChapterId=chapterAt[positions[0]]!.Value;
var verified=at==positions[0]&&(prior.Length==1||complete||!next[at].WasMoved);
if(!verified&&!complete){var remaining=positions.Where(pos=>!next[pos].WasMoved).ToArray();if(remaining.Length>0)at=remaining[0];scene.NeedsRefinement=true;}
starts.Add((at,scene,verified));
}else{
var surviving=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
scene.NeedsRefinement=true;
if(surviving.Length>0)starts.Add((surviving[0],scene,false));
}
}
// A scene boundary is applicable only inside its own recognised chapter.
var chapterStarts=starts.Where(s=>chapterAt[s.At]==s.Scene.ChapterId).GroupBy(s=>s.Scene.ChapterId)
.ToDictionary(g=>g.Key,g=>g.OrderBy(s=>s.At).ToArray());
var activeScenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id);
var current=new List<StoryParagraph>();var boundaryIndices=new Dictionary<int,int>();
foreach(var p in next){
var chapter=chapterAt[p.Ordinal];var candidates=chapter.HasValue?chapterStarts.GetValueOrDefault(chapter.Value)??[]:[];
int boundaryIndex=chapter.HasValue?boundaryIndices.GetValueOrDefault(chapter.Value,-1):-1;
while(boundaryIndex+1<candidates.Length&&candidates[boundaryIndex+1].At<=p.Ordinal)boundaryIndex++;
if(chapter.HasValue)boundaryIndices[chapter.Value]=boundaryIndex;
var boundary=boundaryIndex>=0?candidates[boundaryIndex]:default;var scene=boundary.Scene;
if(scene==null&&p.Outline!=1&&chapter.HasValue){
// Retain a surviving occurrence's own assignment before making any local proposal.
if(old.TryGetValue(p.Id,out var prior)&&prior.ChapterId==chapter&&prior.SceneId.HasValue&&activeScenes.TryGetValue(prior.SceneId.Value,out var saved)&&saved.ChapterId==chapter)scene=saved;
else if(candidates.Length>0)scene=candidates[0].Scene;
if(scene!=null)scene.NeedsRefinement=true;
}
var story=!excludedAt[p.Ordinal]&&p.Outline!=1&&scene!=null;
current.Add(new(){Occurrence=p,Story=story,SceneId=story?scene!.Id:null,ChapterId=chapter,
PositionVerified=(p.Outline==1&&chapter>0)||(story&&boundary.Scene?.Id==scene?.Id&&boundary.Verified&&p.Resolution!="Ambiguous")});
}
// No local anchor/evidence means unresolved prose in its chapter, never inheritance from another chapter.
foreach(var scene in state.Scenes.Where(s=>!s.Retired))if(current.Any(p=>p.SceneId==scene.Id&&!p.PositionVerified))scene.NeedsRefinement=true;
state.Paragraphs=current;var hash=Hash(rows);if(hash!=state.SnapshotHash)state.Undo.Clear();state.SnapshotHash=hash;state.UpdatedUtc=DateTime.UtcNow;RefreshEvidence(state);Validate(state);
}
private static void RefineChapterIdentities(ParagraphManuscript state,IReadOnlyList<ParagraphOccurrence> incoming,ParagraphOccurrence[] next)
{
// Heading identities establish hard comparison windows. Repeated prose in another chapter
// cannot compete with a local occurrence or prevent a locally evidenced single rewrite.
var prior=state.Paragraphs.Select(p=>p.Occurrence).ToArray();
var oldIndex=prior.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
var oldTextCounts=prior.GroupBy(p=>p.Text,StringComparer.Ordinal).ToDictionary(g=>g.Key,g=>g.Count(),StringComparer.Ordinal);
var newTextPositions=incoming.Select((p,i)=>(p.Text,p.Outline,i)).GroupBy(p=>p.Text,StringComparer.Ordinal).Where(g=>g.Count()==1).ToDictionary(g=>g.Key,g=>g.Single(),StringComparer.Ordinal);
foreach(var chapter in state.Chapters.Where(c=>c.HeadingId!=Guid.Empty))if(oldIndex.TryGetValue(chapter.HeadingId,out var at)){
var heading=prior[at];if(heading.Outline!=1||oldTextCounts[heading.Text]!=1||!newTextPositions.TryGetValue(heading.Text,out var match)||match.Outline!=1)continue;
// An exact, unique Word heading is still the boundary when new prose was inserted on both sides.
var found=next[match.i];found.Id=heading.Id;found.PreviousText=heading.Text;found.Change="Unchanged";found.Resolution="Unique chapter heading";
}
var newIndex=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
var headings=state.Chapters.Select(c=>c.HeadingId).Where(id=>id!=Guid.Empty).ToHashSet();
var incomingText=incoming.Select(p=>p.Text).ToHashSet(StringComparer.Ordinal);
foreach(var chapter in state.Chapters.Where(c=>c.HeadingId!=Guid.Empty)){
if(!oldIndex.TryGetValue(chapter.HeadingId,out var a)||!newIndex.TryGetValue(chapter.HeadingId,out var b))continue;
int oldEnd=a+1,newEnd=b+1;while(oldEnd<prior.Length&&prior[oldEnd].Outline!=1&&!headings.Contains(prior[oldEnd].Id))oldEnd++;while(newEnd<next.Length&&next[newEnd].Outline!=1&&!headings.Contains(next[newEnd].Id))newEnd++;
var previous=prior[a..oldEnd];var local=ParagraphReconciliation.Compare(previous,incoming.Skip(b).Take(newEnd-b).ToArray()).Current;
// The recognised chapter heading is the left anchor, even if its only local neighbour changed.
local[0]=next[b];var positions=previous.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
var used=local.Where(p=>positions.ContainsKey(p.Id)).Select(p=>p.Id).ToHashSet();
for(int n=1;n+1<local.Length;n++)if(!positions.ContainsKey(local[n].Id)&&positions.TryGetValue(local[n-1].Id,out var left)&&positions.TryGetValue(local[n+1].Id,out var right)&&right==left+2&&!used.Contains(previous[left+1].Id)){
var original=previous[left+1];if(local[n].Text!=original.Text&&incomingText.Contains(original.Text))continue;
local[n].Id=original.Id;local[n].PreviousText=original.Text;local[n].Change=local[n].Text==original.Text?"Unchanged":"Modified";local[n].Resolution="Chapter-bound occurrence; review";used.Add(original.Id);
}
for(int n=0;n<local.Length;n++){local[n].Ordinal=b+n;next[b+n]=local[n];}
}
if(next.Select(p=>p.Id).Distinct().Count()!=next.Length)throw new InvalidOperationException("Chapter occurrence identities are ambiguous. No saved manuscript was changed.");
for(int n=0;n<next.Length;n++){next[n].Ordinal=n;next[n].PreviousId=n>0?next[n-1].Id:null;next[n].NextId=n+1<next.Length?next[n+1].Id:null;}
}
private static ParagraphLayout Layout(ParagraphManuscript state)=>new(){Chapters=state.Chapters.Select(c=>new ParagraphChapter{CanonicalId=c.CanonicalId,HeadingId=c.HeadingId,Title=c.Title}).ToList(),SnapshotHash=state.SnapshotHash,EventPositions=state.EventPositions.Select(e=>new ManuscriptEventOption{Kind=e.Kind,Id=e.Id,SceneId=e.SceneId,Description=e.Description}).ToList(),Scenes=state.Scenes.Select(s=>new ParagraphScene{Id=s.Id,CanonicalId=s.CanonicalId,ChapterId=s.ChapterId,Title=s.Title,Retired=s.Retired,MergedInto=s.MergedInto,NeedsRefinement=s.NeedsRefinement}).ToList(),Assignments=state.Paragraphs.Select(p=>new ParagraphAssignment{ParagraphId=p.Occurrence.Id,ChapterId=p.ChapterId,SceneId=p.SceneId,PositionVerified=p.PositionVerified}).ToList()};
private static void Remember(ParagraphManuscript state){var limit=Math.Clamp(100000/Math.Max(1,state.Paragraphs.Count),1,12);while(state.Undo.Count>=limit)state.Undo.RemoveAt(0);state.Undo.Add(Layout(state));}
public static void ConfirmGrouping(ParagraphManuscript state,Guid sceneId)
{
var scene=state.Scenes.Single(s=>s.Id==sceneId&&!s.Retired);var rows=state.Paragraphs.Where(p=>p.SceneId==sceneId&&p.Story).ToArray();if(rows.Length==0)throw new ArgumentException("No surviving scene paragraphs to confirm.");
if(rows.Any(p=>p.ChapterId!=scene.ChapterId))throw new ArgumentException("A scene grouping cannot cross chapter boundaries.");
Remember(state);foreach(var p in rows){p.PositionVerified=true;p.ChapterId=scene.ChapterId;}scene.NeedsRefinement=false;
foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1&&p.Occurrence.Ordinal>=rows[0].Occurrence.Ordinal-1&&p.Occurrence.Ordinal<=rows[^1].Occurrence.Ordinal&&state.Chapters.All(c=>c.HeadingId!=p.Occurrence.Id)))state.Chapters.Add(new(){CanonicalId=scene.ChapterId,HeadingId=heading.Occurrence.Id,Title=heading.Occurrence.Text.Trim()});
RefreshEvidence(state);Validate(state);
}
public static void Split(ParagraphManuscript state,Guid paragraph,string title)
{
var p=state.Paragraphs.SingleOrDefault(p=>p.Occurrence.Id==paragraph&&p.Story)??throw new ArgumentException("Choose a story paragraph.");var source=state.Scenes.Single(s=>s.Id==p.SceneId&&!s.Retired);
var group=state.Paragraphs.Where(x=>x.SceneId==source.Id).ToArray();if(group[0]==p)throw new ArgumentException("The paragraph already begins a scene.");if(string.IsNullOrWhiteSpace(title)||title.Length>200)throw new ArgumentException("Enter a scene title of up to 200 characters.");
Remember(state);var created=new ParagraphScene{ChapterId=source.ChapterId,Title=title.Trim()};state.Scenes.Add(created);foreach(var row in group.Where(x=>x.Occurrence.Ordinal>=p.Occurrence.Ordinal)){row.SceneId=created.Id;row.PositionVerified=true;}source.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
}
public static void MoveBoundary(ParagraphManuscript state,Guid rightScene,Guid firstParagraph)
{
var right=state.Scenes.SingleOrDefault(s=>s.Id==rightScene&&!s.Retired)??throw new ArgumentException("Scene no longer exists.");
var ordered=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(ordered,g=>g.Key==rightScene);if(i<=0)throw new ArgumentException("Choose an adjacent scene boundary.");
var left=state.Scenes.Single(s=>s.Id==ordered[i-1].Key);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("A boundary cannot cross chapters.");
var rows=ordered[i-1].Concat(ordered[i]).OrderBy(p=>p.Occurrence.Ordinal).ToArray();var cut=Array.FindIndex(rows,p=>p.Occurrence.Id==firstParagraph);if(cut<=0||cut>=rows.Length)throw new ArgumentException("Keep at least one paragraph in each scene.");
Remember(state);for(int n=0;n<rows.Length;n++){rows[n].SceneId=n<cut?left.Id:right.Id;rows[n].PositionVerified=true;}left.NeedsRefinement=right.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
}
public static void Merge(ParagraphManuscript state,Guid leftScene,Guid rightScene)
{
var groups=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(groups,g=>g.Key==leftScene);if(i<0||i+1>=groups.Length||groups[i+1].Key!=rightScene)throw new ArgumentException("Only adjacent scenes can be merged.");
var left=state.Scenes.Single(s=>s.Id==leftScene&&!s.Retired);var right=state.Scenes.Single(s=>s.Id==rightScene&&!s.Retired);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("Scenes belong to different chapters.");
Remember(state);foreach(var p in state.Paragraphs.Where(p=>p.SceneId==rightScene)){p.SceneId=leftScene;p.PositionVerified=true;}right.Retired=true;right.MergedInto=left.Id;foreach(var e in state.EventPositions.Where(e=>e.SceneId==right.CanonicalId))e.SceneId=left.CanonicalId;left.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
}
public static void Undo(ParagraphManuscript state)
{
if(state.Undo.Count==0)throw new InvalidOperationException("No structure change to undo.");var previous=state.Undo[^1];if(previous.SnapshotHash!=state.SnapshotHash)throw new InvalidOperationException("Word changed. This earlier layout cannot safely be restored.");
state.Undo.RemoveAt(state.Undo.Count-1);foreach(var extra in state.Scenes.Where(s=>previous.Scenes.All(p=>p.Id!=s.Id))){extra.Retired=true;previous.Scenes.Add(extra);}state.Scenes=previous.Scenes;state.Chapters=previous.Chapters;state.EventPositions=previous.EventPositions;var assignments=previous.Assignments.ToDictionary(p=>p.ParagraphId);foreach(var p in state.Paragraphs){var a=assignments[p.Occurrence.Id];p.SceneId=a.SceneId;p.ChapterId=a.ChapterId;p.PositionVerified=a.PositionVerified;}RefreshEvidence(state);Validate(state);
}
public static StoryEvidence Anchor(ParagraphManuscript state,string kind,int eventId,bool primary,int from,int to,int? startOffset,int? endOffset)
{
if(kind is not ("Knowledge" or "Relationship")||eventId<=0)throw new ArgumentException("Choose a saved event.");var rows=state.Paragraphs.Where(p=>p.Occurrence.Ordinal>=from&&p.Occurrence.Ordinal<=to).ToArray();
if(rows.Length==0||to<from||rows.Length!=to-from+1||rows.Any(p=>!p.Story||!p.PositionVerified))throw new ArgumentException("Choose a reliably mapped story passage.");
var evidence=new StoryEvidence{EventKind=kind,EventId=eventId,Primary=primary,StartParagraph=rows[0].Occurrence.Id,EndParagraph=rows[^1].Occurrence.Id,StartOffset=startOffset,EndOffset=endOffset};
evidence.CurrentText=Text(state,evidence)??throw new ArgumentException("Passage offsets are outside the selected text.");if(evidence.CurrentText.Length==0||evidence.CurrentText.Length>100000)throw new ArgumentException("Choose a passage of up to 100,000 characters.");
evidence.OriginalText=evidence.ConfirmedText=evidence.CurrentText;if(primary)foreach(var old in state.Evidence.Where(e=>e.EventKind==kind&&e.EventId==eventId))old.Primary=false;
state.Evidence.Add(evidence);state.Undo.Clear();RefreshEvidence(state);evidence.OriginalPosition=evidence.CurrentPosition;return evidence;
}
public static void Confirm(ParagraphManuscript state,Guid evidence)
{
var item=state.Evidence.Single(e=>e.Id==evidence);var text=Text(state,item)??throw new ArgumentException("Relink missing evidence first.");
var start=state.Paragraphs.Single(p=>p.Occurrence.Id==item.StartParagraph);if(!start.PositionVerified)throw new ArgumentException("Resolve the scene boundary before confirming evidence.");item.ConfirmedText=text;state.Undo.Clear();RefreshEvidence(state);
}
public static string? Text(ParagraphManuscript state,StoryEvidence anchor,IReadOnlyDictionary<Guid,int>? positions=null)
{
int a=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.StartParagraph):positions.GetValueOrDefault(anchor.StartParagraph,-1),b=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.EndParagraph):positions.GetValueOrDefault(anchor.EndParagraph,-1);if(a<0||b<a)return null;
var rows=state.Paragraphs.Skip(a).Take(b-a+1).ToArray();int start=anchor.StartOffset??0,end=anchor.EndOffset??rows[^1].Occurrence.Text.Length;
if(start<0||start>rows[0].Occurrence.Text.Length||end<0||end>rows[^1].Occurrence.Text.Length||(rows.Length==1&&end<start))return null;
return rows.Length==1?rows[0].Occurrence.Text.Substring(start,end-start):rows[0].Occurrence.Text[start..]+string.Concat(rows.Skip(1).Take(rows.Length-2).Select(p=>p.Occurrence.Text))+rows[^1].Occurrence.Text[..end];
}
public static void RefreshEvidence(ParagraphManuscript state)
{
var positions=state.Paragraphs.Select((p,i)=>(p.Occurrence.Id,i)).ToDictionary(p=>p.Id,p=>p.i);var byId=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var scenes=state.Scenes.ToDictionary(s=>s.Id);
foreach(var e in state.Evidence){var current=Text(state,e,positions);var paragraph=byId.GetValueOrDefault(e.StartParagraph);if(e.CurrentScene!=paragraph?.SceneId){e.PreviousScene=e.CurrentScene;e.PreviousPosition=e.CurrentPosition;}
e.CurrentText=current??"";e.CurrentScene=paragraph?.SceneId;e.CurrentPosition=paragraph==null?"Paragraph missing":$"Paragraph {paragraph.Occurrence.Ordinal+1} · { (paragraph.SceneId.HasValue&&scenes.TryGetValue(paragraph.SceneId.Value,out var scene)?scene.Title:"Scene needs review") }";
e.State=current==null?"Missing":current!=e.ConfirmedText||paragraph?.PositionVerified!=true||!RangeVerified(state,e,positions)?"Needs review":"Verified";
e.DerivedSceneId=e.State=="Verified"&&e.CurrentScene.HasValue?scenes[e.CurrentScene.Value].CanonicalId:null;
}
}
private static bool RangeVerified(ParagraphManuscript state,StoryEvidence evidence,IReadOnlyDictionary<Guid,int> positions){int a=positions.GetValueOrDefault(evidence.StartParagraph,-1),b=positions.GetValueOrDefault(evidence.EndParagraph,-1);return a>=0&&b>=a&&state.Paragraphs.Skip(a).Take(b-a+1).All(p=>p.PositionVerified);}
public static void Validate(ParagraphManuscript state)
{
if(state.Paragraphs.Count>100000||state.Evidence.Count>10000||state.Scenes.Count>10000||state.Evidence.Sum(e=>(long)e.OriginalText.Length+e.ConfirmedText.Length+e.CurrentText.Length)>8*1024*1024)throw new ArgumentException("Manuscript structure exceeds limits.");
if(state.Evidence.Any(e=>e.Id==Guid.Empty)||state.Evidence.Select(e=>e.Id).Distinct().Count()!=state.Evidence.Count)throw new ArgumentException("Duplicate or empty evidence identities.");
if(state.Paragraphs.Any(p=>p.Occurrence.Id==Guid.Empty)||state.Scenes.Any(s=>s.Id==Guid.Empty)||state.Paragraphs.Select(p=>p.Occurrence.Id).Distinct().Count()!=state.Paragraphs.Count||state.Scenes.Select(s=>s.Id).Distinct().Count()!=state.Scenes.Count)throw new ArgumentException("Duplicate manuscript identities.");
var scenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id);if(state.Paragraphs.Any(p=>p.Story&&(!p.SceneId.HasValue||!scenes.ContainsKey(p.SceneId.Value))))throw new ArgumentException("Every story paragraph must belong to one current scene.");
if(state.Paragraphs.Any(p=>p.SceneId.HasValue&&scenes.TryGetValue(p.SceneId.Value,out var scene)&&p.ChapterId!=scene.ChapterId))throw new ArgumentException("A paragraph scene assignment cannot cross chapter boundaries.");
var completed=new HashSet<Guid>();Guid? last=null;foreach(var p in state.Paragraphs.Where(p=>p.Story)){if(p.SceneId!=last){if(p.SceneId.HasValue&&completed.Contains(p.SceneId.Value))throw new ArgumentException("Scene groups must be contiguous.");if(last.HasValue)completed.Add(last.Value);last=p.SceneId;}}
}
}