using PlotDirector.Companion.Protocol.Manuscript; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services.NativeCompanion; namespace PlotLine.Services.Manuscript; public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscripts,IChapterSyncRepository checkpoints,IWordCompanionRepository access,ParagraphManuscriptService reconciliation,NativePresenceStore presence,TimeProvider clock) { private void RequireFeature(){if(!reconciliation.Enabled)throw new InvalidOperationException("Paragraph synchronisation is not enabled on this server.");} public async Task Manifest(int user,int book,Guid session,long wordRevision) { RequireFeature(); if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException(); var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available."); var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision); var manifest=new ChapterManifest(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{ var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash); return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status}; }).ToArray()}; var lease=presence.Read(user,book).SingleOrDefault(l=>l.Session==session&&l.Position.Revision==wordRevision&&l.Position.CanChapterSync); if(lease!=null){var count=manifest.Chapters.Count(c=>c.State=="Synchronised");presence.RecordChapterProgress(user,book,lease.Instance,session,wordRevision,new(){Total=manifest.Chapters.Length,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,lease.Instance,session,wordRevision),State="Checking",Message=$"{count}/{manifest.Chapters.Length} chapter mappings accepted for this session."});} return manifest; } public async Task Finish(int user,string grant,int book,ChapterFinish completion) { RequireFeature(); var lease=presence.Read(user,book).SingleOrDefault(l=>l.Grant==grant&&l.Instance==completion.InstanceId&&l.Session==completion.SessionId&&l.Position.Revision==completion.WordRevision&&l.Position.CanChapterSync&&l.Position.WordSaved==true)??throw new InvalidOperationException("The live document changed before completion."); if(completion.OperationId!=Guid.Empty&&!presence.CanRepairChapter(user,lease,completion.OperationId))throw new UnauthorizedAccessException(); var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; completion is paused and accepted checkpoints are retained."); var manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision); if(completion.HasIssues&&manifest.Chapters.Length>0){var ids=(completion.ReviewChapterIds??[]).Where(id=>manifest.Chapters.Any(c=>c.ChapterId==id)).Distinct().Take(256).ToArray();if(ids.Length==0)ids=[manifest.Chapters[0].ChapterId];foreach(var id in ids)await checkpoints.FlagReview(user,book,id,manifest.Revision);manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);} var accepted=manifest.Chapters.Count(c=>c.State=="Synchronised");var complete=accepted==manifest.Chapters.Length&&accepted>0&&!completion.HasIssues; var progress=new ChapterSyncProgress{Total=manifest.Chapters.Length,Checked=manifest.Chapters.Length,Matching=accepted,Repaired=presence.RepairedChapters(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision),NeedsReview=complete?0:Math.Max(1,manifest.Chapters.Length-accepted),State=complete?"Synchronised":"Needs review",Message=complete?$"All {accepted} chapter mappings are accepted for this Word session.":$"{accepted}/{manifest.Chapters.Length} chapters accepted; remaining structure needs review. Successfully accepted repairs are retained."}; presence.RecordChapterProgress(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision,progress);return progress; } public async Task Repair(int user,int book,Guid? instance,Guid? session,long? expectedWordRevision=null) { RequireFeature(); var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("The accepted snapshot is missing; finish the existing import, do not reimport an already indexed book."); if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active. Accepted checkpoints are preserved."); if(instance.HasValue!=session.HasValue)throw new InvalidOperationException("Choose a complete Word session."); var live=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanChapterSync&&l.Position.WordSaved==true).ToArray(); var selected=instance.HasValue?live.SingleOrDefault(l=>l.Instance==instance&&l.Session==session):live.Count(l=>l.Position.Active)==1?live.Single(l=>l.Position.Active):live.Length==1?live[0]:null; if(selected==null)throw new InvalidOperationException("Open and save the intended manuscript with a chapter-capable Companion, then select its document connection."); if(expectedWordRevision.HasValue&&selected.Position.Revision!=expectedWordRevision)throw new InvalidOperationException("Word changed before the explicit repair request arrived. Request again from the current document."); if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This document has a different manuscript identity. No existing import was changed."); var source=await manuscripts.Get(user,book)??throw new InvalidOperationException("No accepted source snapshot.");if(ChapterCheckpointEngine.Parts(source).Length==0)throw new InvalidOperationException("No reversible chapter boundaries are recorded. Use the existing bounded full snapshot reader or review structure; the import does not need to be recreated."); var id=Guid.NewGuid();if(!presence.RequestChapterRepair(user,selected,id))throw new InvalidOperationException("Word is busy with another request. Accepted chapter checkpoints are preserved.");return id; } public async Task Accept(int user,string grant,int book,ChapterObservation proof) { if(proof==null||proof.Paragraphs==null||proof.Paragraphs.Length==0||proof.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||proof.Paragraphs.Any(p=>p==null))throw new ArgumentException("Complete bounded chapter evidence is required."); RequireFeature(); if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException(); var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("No accepted manuscript index."); if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; chapter acceptance is paused."); var lease=presence.Read(user,book).SingleOrDefault(l=>l.Instance==proof.InstanceId&&l.Session==proof.SessionId&&l.Grant==grant&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==proof.ManuscriptId&&l.Position.Revision==proof.WordRevision); if(lease==null)throw new InvalidOperationException("Word document closed, changed, became unsaved or was disconnected; no stale checkpoint was accepted."); var permitted=status.Mode=="OnSave"||presence.CanRepairChapter(user,lease,proof.OperationId); var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing accepted snapshot."); var source=ChapterCheckpointEngine.Build(state,state.Revision).SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown accepted chapter."); var changed=source.ContentHash!=proof.ContentHash; if(changed){ if(!permitted||proof.Paragraphs.Any(p=>p.Text==null))return new(){State="Changed",ChapterId=proof.ChapterId,Revision=state.Revision,AllowText=permitted,Message=permitted?"Changed chapter; submit this chapter only for existing paragraph reconciliation.":"Changed chapter. Use Synchronise or Repair to authorise chapter reconciliation; no prose was uploaded."}; if(presence.Read(user,book).Count(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==proof.ManuscriptId)>1)throw new InvalidOperationException("Competing Word copies are connected to this book. Close the other copy before reconciling changed prose; existing mappings are preserved."); state=await reconciliation.ReconcileChapter(user,book,proof);proof.BaseRevision=state.Revision; } // Native adoption is explicit repair only; ordinary hash checks cannot mint trust. proof.Reconcile=presence.CanRepairChapter(user,lease,proof.OperationId); var validated=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime); await checkpoints.Accept(user,book,proof,validated); if(changed||validated.Bindings.Length>0)presence.RecordChapterRepair(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision,proof.ChapterId); await Manifest(user,book,proof.SessionId,proof.WordRevision); return new(){Accepted=true,State=validated.Checkpoint.Message.Contains("order needs review")?"Needs review":"Synchronised",ChapterId=proof.ChapterId,Revision=state.Revision,Message=validated.Checkpoint.Message}; } }