PlotDirector/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs

224 lines
28 KiB
C#

using System.Collections.Concurrent;
using System.Text;
using PlotDirector.Companion.Protocol;
using PlotLine.Models;
using PlotLine.Services.Manuscript;
using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotLine.Services.NativeCompanion;
// Short-lived transfer authorisation, issued only by the authenticated existing import wizard.
// Prose acceptance is durable through IManuscriptScanPreviewStore, not through this dictionary.
public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null,ILogger<NativeManuscriptCapture>? logger=null)
{
private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null,DateTimeOffset Created=default,DateTimeOffset HardExpires=default,string? FailureCode=null,DateTimeOffset RetainUntil=default);
public bool ParagraphEnabled=>configuration?.GetValue<bool>("Features:ParagraphManuscripts")==true;
private readonly ConcurrentDictionary<Guid,Pending> pending=new();
private readonly SemaphoreSlim acceptance=new(1,1);
public async Task<ManuscriptScanState?> Start(int user,int onboarding,int project,int book,bool paragraphs=false)
{
await acceptance.WaitAsync();try{
if(paragraphs&&configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled on this server.");
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();
if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible.");
foreach(var expired in pending.Where(p=>p.Value.FailureCode!=null?p.Value.RetainUntil<=clock.GetUtcNow():p.Value.Hash!=null&&p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _);
var all=presence.Read(user,0).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture&&(!paragraphs||l.Position.CanParagraphSync)).ToArray();
var linked=all.Where(l=>l.Position.BookId==book).ToArray();
var documents=linked.Length>0?linked:all.Where(l=>l.Position.BookId==0).ToArray();
if(linked.Length==0&&documents.Length>0&&all.Any(l=>l.Position.Active&&l.Position.BookId>0&&l.Position.BookId!=book))
throw new InvalidOperationException("Activate the intended unassociated manuscript in Word before importing. The active document belongs to another book.");
if(documents.Length==0)return null;
var active=documents.Where(l=>l.Position.Active).ToArray();
var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry.");
paragraphs=paragraphs||(configuration?.GetValue<bool>("Features:ParagraphManuscripts")==true&&selected.Position.CanParagraphSync);
if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying.");
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later.");
var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value;
pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:paragraphs,Created:clock.GetUtcNow(),HardExpires:clock.GetUtcNow().AddHours(4));
if(!presence.RequestCapture(user,selected,id,book,paragraphs)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");}
return state;
}finally{acceptance.Release();}
}
public async Task<ParagraphPosition?> ResolveParagraphPosition(int user,int book,Guid manuscript,Guid session,long revision,int position){if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)return null;using var scope=scopes.CreateScope();return await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Position(user,book,manuscript,session,revision,position);}
public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();presence.CancelChapterRepairs(user,book);foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}}
public sealed record ParagraphTransfer(Guid RequestId,string State,string? Message=null,string Kind="snapshot");
public ParagraphTransfer? ParagraphTransferStatus(int user,int book,Guid instance,Guid session)
{
var latest=pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Lease.Instance==instance&&p.Value.Lease.Session==session).OrderByDescending(p=>p.Value.Created).FirstOrDefault();
var chapter=presence.ChapterTransfer(user,book,instance,session);if(latest.Value==null||chapter.HasValue&&chapter.Value.Created>latest.Value.Created){return chapter.HasValue?new(chapter.Value.Id,chapter.Value.State,chapter.Value.Message,"chapter"):null;}return new(latest.Key,latest.Value.Hash!=null?"accepted":latest.Value.FailureCode!=null||latest.Value.Expires<=clock.GetUtcNow()?"failed":"pending");
}
private readonly Dictionary<(int,Guid,Guid),DateTimeOffset> autoChecks=[];
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null,Guid? instanceId=null,Guid? sessionId=null,bool fullSnapshot=false)
{
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled.");
await acceptance.WaitAsync();try{
using var scope=scopes.CreateScope();var repository=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>();
var status=await repository.Status(user,book)??throw new InvalidOperationException("Enable paragraph tracking for this book first.");
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("The existing book import is still active. Synchronisation is paused to protect it.");
var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanParagraphSync).ToArray();
if(automatic!=null&&(status.Mode!="OnSave"||documents.Length!=1||!automatic.Position.WordSaved.GetValueOrDefault()||(status.SessionId==automatic.Session&&status.WordRevision==automatic.Position.Revision)))return Guid.Empty;
if(instanceId.HasValue!=sessionId.HasValue)throw new InvalidOperationException("Select a complete Word document session before synchronising.");
var active=documents.Where(l=>l.Position.Active).ToArray();
var selected=instanceId.HasValue?documents.SingleOrDefault(l=>l.Instance==instanceId&&l.Session==sessionId)??throw new InvalidOperationException("The selected Word document is no longer connected. Select it again before synchronising."):automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected."));
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused.");
if(selected.Position.CanChapterSync&&!fullSnapshot)return await scope.ServiceProvider.GetRequiredService<PlotLine.Services.Manuscript.ChapterSyncService>().Repair(user,book,selected.Instance,selected.Session);
if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))return Guid.Empty;
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid();
pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision,Created:clock.GetUtcNow(),HardExpires:clock.GetUtcNow().AddHours(4));
if(!presence.RequestCapture(user,selected,id,book,true,true,status.Revision,status.SnapshotHash)){pending.TryRemove(id,out _);throw new InvalidOperationException("Word changed or is busy. Request a fresh snapshot.");}return id;
}finally{acceptance.Release();}
}
public async Task ObserveParagraphSave(int user,NativeLease lease)
{
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true||!lease.Position.CanParagraphSync||lease.Position.BookId<=0||lease.Position.WordSaved!=true)return;
var key=(user,lease.Instance,lease.Session);lock(autoChecks){var now=clock.GetUtcNow();if(autoChecks.TryGetValue(key,out var after)&&now<after)return;if(autoChecks.Count>=256)autoChecks.Clear();autoChecks[key]=now.AddSeconds(15);}
try{await RequestParagraphSnapshot(user,lease.Position.BookId,automatic:lease);}catch(Exception e)when(e is InvalidOperationException or UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException){/* Paused/unauthorised books never trigger a transfer. */}
}
public Guid[]? AcceptedParagraphIds(int user,Guid request)=>pending.TryGetValue(request,out var value)&&value.User==user?value.Prepared?.NativeParagraphs?.Select(p=>p.Id).ToArray():null;
public Task<ParagraphManuscript> AcceptedParagraphState(int user,Guid id){if(!pending.TryGetValue(id,out var request)||request.User!=user||!request.Sync||request.Hash==null||request.AcceptedSnapshot==null)throw new UnauthorizedAccessException();return Task.FromResult(request.AcceptedSnapshot);}
public async Task<bool> AcceptParagraphSnapshot(int user,string grant,ManuscriptCapture capture)
{
await acceptance.WaitAsync();try{
if(!pending.TryGetValue(capture.RequestId,out var request)||!request.Sync)return false;
ValidateRequest(request,user,grant,capture);
var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture)));
if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Snapshot retry has different contents.");return true;}
using var scope=scopes.CreateScope();var accepted=await scope.ServiceProvider.GetRequiredService<ParagraphManuscriptService>().Snapshot(user,request.Book,capture,request.BaseRevision);
presence.BooksChanged(user);
pending[capture.RequestId]=request with{Hash=hash,AcceptedSnapshot=new ParagraphManuscript{BookId=accepted.BookId,Revision=accepted.Revision,SnapshotHash=accepted.SnapshotHash,Paragraphs=accepted.Paragraphs.Select(p=>new StoryParagraph{Occurrence=new ParagraphOccurrence{Id=p.Occurrence.Id}}).ToList()}};return true;
}finally{acceptance.Release();}
}
public async Task<ManuscriptScanState> Accept(int user,string grant,ManuscriptCapture capture)
{
await acceptance.WaitAsync();try{
if(!pending.TryGetValue(capture.RequestId,out var request))throw Rejected(user,capture.RequestId,"capture_not_active",409,"This Word capture request is no longer active. Return to the existing import and request the capture again.");
if(request.Sync)throw Rejected(user,capture.RequestId,"capture_workflow_mismatch",409,"The capture belongs to another operation. Return to the existing import.");
ValidateRequest(request,user,grant,capture);
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();var onboardingState=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IOnboardingRepository>();
var current=await onboardingState.GetAsync(user);
if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw Rejected(user,capture.RequestId,"capture_wizard_changed",409,"The selected import book or setup changed during capture. Existing accepted data is unchanged; return to the intended import.");
var structure=await access.GetBookStructureAsync(request.Book,user)??throw Rejected(user,capture.RequestId,"capture_book_forbidden",403,"You no longer have access to the selected import book.");
var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture)));
if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Capture identity conflict. Start a new transfer.");return await scans.GetStateAsync(user,request.Onboarding);}
var preview=request.Prepared??Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure);
// Reuse server-minted occurrence IDs if a durable write succeeds but its acknowledgement is lost.
pending[capture.RequestId]=request=request with{Prepared=preview};
var state=await scans.CompleteAsync(user,preview);
pending[capture.RequestId]=request with{Hash=hash};
// Retain request until expiry for idempotent same-ID retransmission; no import is committed here.
return state;
}finally{acceptance.Release();}
}
private CaptureSubmissionRejected Rejected(int user,Guid id,string code,int status,string message)
{
logger?.LogWarning("Native capture rejected. UserID={UserID} RequestID={RequestID} Code={Code}",user,id,code);
return new(code,status,message);
}
private void ValidateRequest(Pending request,int user,string grant,ManuscriptCapture capture)
{
if(request.User!=user||request.Lease.Grant!=grant)throw Rejected(user,capture.RequestId,"capture_authority_mismatch",403,"This capture does not belong to the approved Companion connection.");
if(capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId)throw Rejected(user,capture.RequestId,"capture_document_mismatch",403,"The Word document or session differs from the requested capture. Return to the intended manuscript.");
if(request.Hash==null&&(request.FailureCode!=null||request.Expires<=clock.GetUtcNow()||request.HardExpires<=clock.GetUtcNow()))throw Rejected(user,capture.RequestId,request.FailureCode??"capture_timeout",410,"The Word capture authorisation expired or disconnected before acceptance. Your Word document is unchanged. Request capture again from the existing import.");
if(request.Paragraphs!=capture.ParagraphTracking)throw Rejected(user,capture.RequestId,"capture_capability_changed",409,"The capture capabilities changed. Reconnect Companion and return to the existing import.");
if(capture.Revision!=request.Lease.Position.Revision)throw Rejected(user,capture.RequestId,"capture_revision_changed",409,"Word changed during capture. Save it, then request a fresh capture from the existing import.");
}
public async Task<ManuscriptScanState?> Progress(int user,string grant,Guid id,int percent,Guid instance,Guid session,Guid manuscript,long revision)
{
await acceptance.WaitAsync();try{
var now=clock.GetUtcNow();
if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null||request.FailureCode!=null||request.Expires<=now||request.HardExpires<=now||request.Lease.Instance!=instance||request.Lease.Session!=session||request.Lease.Position.ManuscriptId!=manuscript||request.Lease.Position.Revision!=revision)return null;
// Existing authenticated document heartbeats renew inactivity, never account approval or identity.
pending[id]=request with{Expires=now.AddMinutes(20)<request.HardExpires?now.AddMinutes(20):request.HardExpires};
return request.Sync?null:await scans.ProgressAsync(user,new(){OnboardingID=request.Onboarding,PercentComplete=Math.Clamp(percent,0,100)*9/10,Message="Reading Word manuscript in bounded batches. Keep Word open until PlotDirector acknowledges receipt."});
}finally{acceptance.Release();}
}
public async Task<IReadOnlyList<(int User,ManuscriptScanState State)>> Expire()
{
var failures=new List<(int,ManuscriptScanState)>();
await acceptance.WaitAsync();try{
var now=clock.GetUtcNow();
foreach(var item in pending.ToArray()){
var request=item.Value;
if(request.FailureCode!=null){if(request.RetainUntil<=now)pending.TryRemove(item.Key,out _);continue;}
if(request.Hash!=null)continue;
var connected=presence.Read(request.User,0).Any(l=>l.Grant==request.Lease.Grant&&l.Instance==request.Lease.Instance&&l.Session==request.Lease.Session);
if(request.Expires>now&&request.HardExpires>now&&connected)continue;
var code=request.Expires<=now||request.HardExpires<=now?"capture_timeout":"capture_disconnected";
// Bounded existing request metadata survives briefly for a useful response; no new store or credentials.
pending[item.Key]=request with{FailureCode=code,RetainUntil=now.AddMinutes(20)};
logger?.LogWarning("Native capture ended before acceptance. UserID={UserID} BookID={BookID} RequestID={RequestID} Code={Code} ElapsedSeconds={ElapsedSeconds}",request.User,request.Book,item.Key,code,(now-request.Created).TotalSeconds);
if(request.Sync)continue;
var state=await scans.GetStateAsync(request.User,request.Onboarding);
if(state.ScanID==item.Key)failures.Add((request.User,await scans.FailAsync(request.User,request.Onboarding,code=="capture_timeout"?"Word capture timed out without valid progress. No manuscript was accepted; return to this import to retry.":"Word disconnected before capture acceptance. No manuscript was accepted; return to this import to retry.")));
}
}finally{acceptance.Release();}
return failures;
}
public async Task<bool> Built(int user,Guid previewId,OnboardingManuscriptBuildResult result)
{
var preview=await scans.GetPreviewAsync(user,previewId);if(preview?.Source!="NativeWordCompanion")return false;
using var scope=scopes.CreateScope();await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IManuscriptCaptureRepository>().CompleteBuild(user,previewId);
if(preview.NativeSessionID.HasValue&&preview.NativeRevision.HasValue&&Guid.TryParse(preview.CompanionDocumentIdentifier,out var manuscript)){
var chapterMarkers=result.ChapterMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>(Start:preview.NativeParagraphPositions[i.WordParagraphIndex],Chapter:i.EntityID,Scene:(int?)null));
var boundaries=chapterMarkers.OrderBy(i=>i.Start).ToArray();
var sceneMarkers=result.SceneMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>{var start=preview.NativeParagraphPositions[i.WordParagraphIndex];return(Start:start,Chapter:boundaries.LastOrDefault(c=>c.Start<=start).Chapter,Scene:(int?)i.EntityID);}).Where(i=>i.Chapter>0);
presence.Map(user,preview.BookID,manuscript,preview.NativeSessionID.Value,preview.NativeRevision.Value,preview.NativeDocumentEnd,boundaries.Concat(sceneMarkers).OrderBy(i=>i.Start).ThenBy(i=>i.Scene.HasValue?1:0).ToArray());
}
if(preview.ParagraphTracking){
var paragraphs=scope.ServiceProvider.GetRequiredService<ParagraphManuscriptService>();var bookRow=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IBookRepository>().GetAsync(preview.BookID);
var sources=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IOnboardingBuildRepository>().ListSceneManuscriptSourcesByBookAsync(preview.BookID);
await paragraphs.Initialise(user,preview,sources,bookRow!.ProjectID,"OnSave");
}
return true;
}
public async Task<ManuscriptScanState?> Fail(int user,string grant,Guid id)
{
await acceptance.WaitAsync();try{
if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null;
pending.TryRemove(id,out _);if(request.Sync)return null;var state=await scans.GetStateAsync(user,request.Onboarding);
return state.ScanID!=id?null:state.Status==ManuscriptScanStatuses.Failed?state:await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged.");
}finally{acceptance.Release();}
}
public static ManuscriptScanPreview Build(ManuscriptCapture capture,int user,int onboarding,int project,int book,string title,WordCompanionBookStructureResponse? structure=null)
{
if(capture.End<0||capture.End>16*1024*1024||capture.Paragraphs==null||capture.Paragraphs.Length>200000)throw new ArgumentException("Manuscript exceeds the bounded capture limit.");
var paragraphs=new List<(int Start,int Index,int Outline,string Text,string[] Tags)>();var text=new StringBuilder();int position=0,index=1,start=0,outline=10,totalCharacters=0;string[] tags=[];
foreach(var fragment in capture.Paragraphs){
if(fragment==null||fragment.Text==null||fragment.Text.Length>ProtocolVersion.MaxParagraphCharacters||fragment.Start!=position||fragment.End<=position||fragment.End>capture.End||fragment.End-fragment.Start>ProtocolVersion.MaxParagraphCharacters||fragment.ParagraphIndex!=index||fragment.OutlineLevel is <1 or >10||fragment.MarkerTags==null||fragment.MarkerTags.Length>16||fragment.MarkerTags.Any(t=>t==null||t.Length>128))throw new ArgumentException("Incomplete or invalid Word paragraph stream.");
if(text.Length==0){start=fragment.Start;outline=fragment.OutlineLevel;tags=fragment.MarkerTags;}
totalCharacters+=fragment.Text.Length;if(totalCharacters>16*1024*1024)throw new ArgumentException("Capture text exceeds limit.");
text.Append(fragment.Text);if(text.Length>16*1024*1024)throw new ArgumentException("Paragraph too large.");position=fragment.End;
if(fragment.CompletesParagraph){paragraphs.Add((start,index++,outline,text.ToString(),tags));text.Clear();}
}
if(position!=capture.End||text.Length!=0)throw new ArgumentException("Manuscript transfer is incomplete.");
var chapters=new List<ManuscriptScanChapterPreview>();var scenes=new List<ManuscriptScanScenePreview>();
var starts=new List<int>();
// Same front-heading vocabulary as the established Office.js importer, only before story starts.
for(var i=0;i<paragraphs.Count;i++){var p=paragraphs[i];if(Marker(p.Tags,"PD-CHAPTER-").HasValue||(p.Outline==1&&(starts.Count>0||!FrontMatterHeading(p.Text))))starts.Add(i);}
var hasStoryHeading=starts.Count>0;var opening=hasStoryHeading&&starts[0]>0;
if(paragraphs.Count>0&&(starts.Count==0||starts[0]!=0))starts.Insert(0,0);
for(int c=0;c<starts.Count;c++){
var rows=paragraphs.Skip(starts[c]).Take((c+1<starts.Count?starts[c+1]:paragraphs.Count)-starts[c]).ToArray();var first=rows[0];bool front=opening&&c==0;bool heading=first.Outline==1&&!front;var number=c+1-(opening?1:0);var key="chapter-"+(c+1);var body=rows.Where(p=>!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text));
chapters.Add(new(){IsFrontMatter=front,TemporaryChapterKey=key,ChapterNumber=number,Title=front?"Opening material (not a story chapter)":heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+number:"Manuscript",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()});
foreach(var row in rows.Where(p=>p.Outline==2||Marker(p.Tags,"PD-SCENE-").HasValue))scenes.Add(new(){TemporaryChapterKey=key,TemporarySceneKey="scene-"+(scenes.Count+1),SceneNumberWithinChapter=scenes.Count(s=>s.TemporaryChapterKey==key)+1,Title=row.Text.Trim(),StartPosition=row.Index,ExistingSceneID=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==Marker(row.Tags,"PD-SCENE-"))?.SceneId});
}
var nativeParagraphs=capture.ParagraphTracking?ParagraphReconciliation.Compare([],ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End)).Current:null;
if(nativeParagraphs!=null&&capture.ParagraphIds!=null){if(capture.ParagraphIds.Length!=nativeParagraphs.Length||capture.ParagraphIds.Any(id=>id==Guid.Empty)||capture.ParagraphIds.Distinct().Count()!=nativeParagraphs.Length)throw new ArgumentException("Invalid paragraph occurrence identities.");for(int n=0;n<nativeParagraphs.Length;n++)nativeParagraphs[n].Id=capture.ParagraphIds[n];}
return new(){ParagraphTracking=capture.ParagraphTracking,NativeParagraphs=nativeParagraphs,NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count(c=>!c.IsFrontMatter),SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
}
private static bool FrontMatterHeading(string text)=>new[]{"title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"}.Contains(text.Trim(),StringComparer.OrdinalIgnoreCase);
private static int? Marker(string[] tags,string prefix)=>tags.Where(t=>t.StartsWith(prefix,StringComparison.Ordinal)).Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue);
private static bool Separator(string text)=>text.Trim() is "***" or "* * *" or "#";
private static int Words(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
}
public sealed class NativeCaptureExpiry(NativeManuscriptCapture capture,Microsoft.AspNetCore.SignalR.IHubContext<PlotLine.Hubs.WordCompanionFollowHub> live):BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken){using var timer=new PeriodicTimer(TimeSpan.FromSeconds(15));while(await timer.WaitForNextTickAsync(stoppingToken)){foreach(var failure in await capture.Expire())await Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(live.Clients.Group(PlotLine.Hubs.WordCompanionFollowHub.PresenceGroup(failure.User)),"OnboardingScanFailed",failure.State,stoppingToken);}}
}
public sealed class CaptureSubmissionRejected(string code,int status,string message):UnauthorizedAccessException(message)
{
public string Code {get;}=code;
public int Status {get;}=status;
}