using System.Text; using System.Text.RegularExpressions; using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; // Incremental, local structural review. No server identities, AI or import decisions. // Keeps a bounded paragraph prefix and suggestions, not a second manuscript copy. public sealed class DocumentAnalysis(bool collectSuggestions = true) { private const int Limit = 8192; private readonly List suggestions = []; private readonly StringBuilder prefix = new(240); private static readonly Regex ChapterLabel = new(@"^(chapter|part|book)\s+(\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten)(\b|:)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50)); private static readonly Regex NumberOnly = new(@"^(\d{1,3}|[IVXLCDM]{1,8})[.:]?$", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50)); private bool inWord; private int words, paragraphs, paragraphStart, paragraphLength, outline; private string[] tags = []; private bool truncated; private int documentEnd; private StructureSuggestion? chapter; public int Count => suggestions.Count; public int WordCount => words; public void Add(ParagraphFragment fragment) { if (paragraphLength == 0) { paragraphStart=fragment.Start; outline=fragment.OutlineLevel; tags=fragment.MarkerTags; } if(prefix.Length<240)prefix.Append(fragment.Text.AsSpan(0,Math.Min(fragment.Text.Length,240-prefix.Length))); paragraphLength += fragment.Text.Length; foreach(var character in fragment.Text) { var next=!char.IsWhiteSpace(character) && character!='\a'; if(next&&!inWord)words++; inWord=next; } documentEnd=fragment.End; if(!fragment.CompletesParagraph)return; paragraphs++; inWord=false; if (!collectSuggestions) { prefix.Clear(); paragraphLength=0; tags=[]; return; } var text=prefix.ToString().Trim('\r','\n','\a',' ','\t'); var chapter=StructuralParser.MarkerId(tags,"PD-CHAPTER-").HasValue; var scene=StructuralParser.MarkerId(tags,"PD-SCENE-").HasValue; if(chapter||(outline==1&&text.Length>0))Suggest("Chapter",text,"Strong",chapter?"Existing PlotDirector chapter marker":"Word heading level 1"); if(scene||(outline==2&&text.Length>0))Suggest("Scene",text,"Strong",scene?"Existing PlotDirector scene marker":"Word heading level 2; review whether this is a scene"); if(!chapter&&!scene&&outline>2&¶graphLength<=240&&text.Length>0) { if(ChapterLabel.IsMatch(text))Suggest("Chapter",text,"Possible","Chapter/part/book label; confirm hierarchy"); else if(NumberOnly.IsMatch(text))Suggest("Chapter",text,"Uncertain","Standalone number may be a heading or ordinary text"); else if(text.Replace(" ","") is "***" or "---" or "###" or "#" or "⁂") Suggest("Scene",text,"Possible","Visible separator; may be decorative"); } prefix.Clear();paragraphLength=0;tags=[]; } private void Suggest(string kind,string text,string confidence,string reason) { if(suggestions.Count==Limit){truncated=true;return;} var suggestion=new StructureSuggestion{Heading1=outline==1,Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason,Origin=reason.StartsWith("Existing PlotDirector")?"Existing marker":"Local structure"}; if(kind=="Chapter"){if(chapter!=null)chapter.End=paragraphStart;chapter=suggestion;} if(chapter!=null){suggestion.ChapterStart=chapter.Start;suggestion.ChapterTitle=chapter.Title;} suggestions.Add(suggestion); } public AnalysisPage Page(int offset) { if(offset<0||offset>suggestions.Count)throw new ArgumentOutOfRangeException(nameof(offset)); if(chapter!=null)chapter.End=documentEnd; var chapters=suggestions.Where(s=>s.Kind=="Chapter").ToDictionary(s=>s.Start); foreach(var item in suggestions.Skip(offset).Take(ProtocolVersion.AnalysisPageSize))if(chapters.TryGetValue(item.ChapterStart,out var parent))item.ChapterEnd=parent.End; return new AnalysisPage{Offset=offset,Total=suggestions.Count,WordCount=words,ParagraphCount=paragraphs, ChapterCount=suggestions.Count(s=>s.Kind=="Chapter"),SceneCount=suggestions.Count(s=>s.Kind=="Scene"),Truncated=truncated, Notice=words==0?"No manuscript words found.":"Local suggestions only. Unmarked prose may contain undetected scenes. Nothing has been imported or changed.", Items=suggestions.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()}; } }