using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ChapterAgentTests
{
public static async Task Run()
{
var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://chapters.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection();
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();handler.Manuscript=Guid.NewGuid();long sequence=0;
sessions.Attach(instance,lease,chapters:true,nativeChapterText:true,nativeChapterPositions:true,liveChapterText:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
Message Send(Message message){message.WordInstanceId=instance;message.SessionId=session;message.Revision=1;message.Sequence=++sequence;return tray.Exchange(instance,message,sessions.Apply(lease,message),lease);}
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic chapter manuscript.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);
try{
AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);}
Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot");
Check(tray.ChapterProgressForDisplay(session) is {Matching:0,Total:1} progress&&progress.Message.StartsWith("0 verified ยท 1 pending"),"Checking progress reports committed acceptances, never a queued chapter number");
var text="Chapter 1\rExact prose\r";var xml="Chapter 1Exact prose";
void Frames(AdapterCommand read,bool exact=false){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});if(exact){var evidence=ChapterFingerprint.ReadXml(xml,text);Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="ids-exact",Start=0,OperationMessage=string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")))});}Send(new(){Kind="chapter-end",SnapshotId=read.Id});}
Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});
Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action="text",OperationMessage=text});
Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action="live-text",OperationMessage="000000010000000A00000001000000020000000C0000000A"});
Send(new(){Kind="chapter-end",SnapshotId=command.Id});
await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0);
Check(handler.Bodies.All(b=>JsonSerializer.Deserialize(b,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.All(p=>p.Text==null)),"Unchanged chapter uploads hashes and native identity evidence, not manuscript prose");
Check(tray.ChapterDiagnostics(session).Contains("Reads live/XML=1/0"),"Reopened unchanged chapter validates without any XML frame");
Check(!handler.Paths.Any(p=>p.Contains("manuscript-capture")),"Chapter lifecycle does not invoke the full manuscript capture endpoint");
var before=handler.Validations;for(int n=0;n<100;n++){var response=Send(new(){Kind="selection",Start=12,End=12,WordSaved=true});Check(response.Command?.Kind!="navigate","Passive selection never returns a navigation command");}await Task.Delay(650);Check(handler.Validations==before,"Repeated cursor events reuse accepted current-session chapter validation");
Check(tray.Documents.Single().Status.Contains("accepted"),"Chapter completion is reported only after server acceptance");
var chunkReply=Send(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="xml",Start=0,OperationMessage="late"});Check(!chunkReply.ChapterStatusProvided,"Chapter chunks do not schedule repeated ribbon updates or invalidate Word during extraction");
Frames(command!);await Task.Delay(100);Check(handler.Validations==before,"Delayed duplicate chapter frames cannot resubmit an accepted operation");
var oldSession=session;session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Second synthetic document.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
AdapterCommand? second=null;for(int n=0;n<200&&second==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")second=pending;await Task.Delay(20);}
Check(second?.Kind=="chapter-check"&&second.SessionId==session,"A second Word document has independent chapter work and cannot inherit the first session's trust");
Send(new(){Kind="close"});Frames(second!);await Task.Delay(100);Check(handler.Validations==before,"Closing a document rejects late extraction frames and preserves already accepted chapters");session=oldSession;
handler.LegacyManifest = true;
session = Guid.NewGuid();
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy indexed fixture.docx"}]});
tray.SelectBook(session,3,false);
Send(new(){Kind="active"});
Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
await Until(() => tray.ChapterProgressForDisplay(session)?.State == "Needs review");
Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("native chapter identities"), "Unindexed legacy identity displays actionable review instead of a zero-count scan");
Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind != "chapter-check" && handler.Validations == before, "No automatic chapter read is queued when every legacy heading lacks a native ID");
handler.LegacyManifest=false;handler.NativeGap=true;
session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Native picture span fixture.docx"}]});
tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
AdapterCommand? physicalRead=null;for(int n=0;n<200&&physicalRead==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")physicalRead=pending;await Task.Delay(20);}
Check(physicalRead?.NativeChapterPositions==true,"Native geometry reading is enabled only by the server manifest's support");
var nativeRows=new[]{new ChapterParagraph{NativeId="00000001",Length=10,WordLength=10,Outline=1},new ChapterParagraph{NativeId="00000002",Length=12,WordLength=13,Outline=10,Anchors=[new(){Offset=0,ShapeId=59,ShapeType=13}]}};
Send(new(){Kind="chapter-begin",SnapshotId=physicalRead!.Id,BookId=3,Start=0,End=23,DocumentEnd=23,WordSaved=true});
Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="text",Start=0,OperationMessage=text});
Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="xml",Start=0,OperationMessage=xml.Replace("Exact prose","Exact prose")});
Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="positions",Start=0,OperationMessage=ChapterWordPositions.Encode(nativeRows)});
Send(new(){Kind="chapter-end",SnapshotId=physicalRead.Id});
await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Synchronised");
var physicalProof=JsonSerializer.Deserialize(handler.Bodies.Last(),new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
Check(physicalProof.End==23&&physicalProof.Paragraphs.Sum(p=>p.Length)==22&&physicalProof.PositionHash==ChapterWordPositions.Hash(physicalProof.Paragraphs)&&physicalProof.Paragraphs.All(p=>p.Text==null),"Agent preserves native Word spans, exact text lengths and geometry hash without uploading unchanged prose");
handler.NativeGap=false;handler.StructuralFailure=true;
session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="One structural chapter under review.docx"}]});
tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=22,End=22,WordSaved=true});
AdapterCommand? unsupportedRead=null;for(int n=0;n<200&&unsupportedRead==null;n++){var pending=Send(new(){Kind="selection",Start=22,End=22,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")unsupportedRead=pending;await Task.Delay(20);}
Check(unsupportedRead?.Chapter?.Start==22&&tray.ChapterProgressForDisplay(session)?.Matching==1,"Structural review starts with the other chapter already durably accepted");
var beforeUnsupported=handler.Validations;
Send(new(){Kind="chapter-begin",SnapshotId=unsupportedRead!.Id,BookId=3,Start=22,End=45,DocumentEnd=45,WordSaved=true});
Send(new(){Kind="adapter-result",SnapshotId=unsupportedRead.Id,OperationMessage="Unsupported floating shape type 6 at Word position 22."});
await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Needs review");
Check(tray.ChapterProgressForDisplay(session)?.Matching==1&&tray.ChapterProgressForDisplay(session)!.Message.Contains("shape type 6")&&handler.Validations==beforeUnsupported,"Unsupported final structure completes under review without rereading or revoking the accepted chapter");
Check(Send(new(){Kind="selection",Start=22,End=22,WordSaved=true}).Command?.Kind!="chapter-check","Stationary observations do not restart an unsupported structural chapter");
handler.StructuralFailure=false;
handler.LegacyManifest = false; handler.RejectValidation = true;
session = Guid.NewGuid();
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Rejected chapter fixture.docx"}]});
tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
AdapterCommand? rejectedRead=null;for(int n=0;n<200&&rejectedRead==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")rejectedRead=pending;await Task.Delay(20);}
Check(rejectedRead!=null,"Rejected-chapter fixture starts a bounded read");Frames(rejectedRead!,true);
await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Needs review");
Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("Synthetic storage refusal"),"Specific server rejection survives completion and is displayed to the author");
var rejectedCount=handler.Validations;
for(int n=0;n<20;n++)Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind!="chapter-check","Stationary cursor does not restart a rejected chapter");
await Task.Delay(650);Check(handler.Validations==rejectedCount,"Rejected chapter waits for an explicit retry rather than reading Word repeatedly");
session = oldSession;
var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated");
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="live-text",OperationMessage="000000010000000A00000001"}).Status=="invalid-chapter-frame","Live chapter evidence requires separate capability negotiation");
legacySessions.Attach(instance,lease,chapters:true);Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy native IDs"}]});
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="ids-exact",OperationMessage="000000010000000A"}).Status=="invalid-chapter-frame","Native text certification requires its separately negotiated capability");
legacySessions.Attach(instance,lease,chapters:true,nativeChapterText:true);Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy text certification"}]});
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="positions",OperationMessage="[]"}).Status=="invalid-chapter-frame","Native physical position evidence requires its separately negotiated capability");
}finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}}
}
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
private static async Task Until(Func condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");}
private sealed class Handler:HttpMessageHandler
{
public Guid Manuscript;public bool LegacyManifest,RejectValidation,NativeGap,StructuralFailure;public int Validations,Finishes;public List Bodies=[];public List Paths=[];
protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancel)
{
var path=request.RequestUri!.AbsolutePath;Paths.Add(path);HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)});
if(path.EndsWith("/presence")){var value=await request.Content!.ReadFromJsonAsync(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);}
if(path.EndsWith("/chapter-sync")&&StructuralFailure)return Json(new ChapterManifest{NativePositionsSupported=true,BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId="00000001",Start=0,End=22,State="Synchronised"},new(){ChapterId=11,HeadingNativeId="00000003",Start=22,End=45}]});
if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{NativePositionsSupported=true,BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId=LegacyManifest?"":"00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=NativeGap?23:22,ParagraphCount=2}]});
if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;if(RejectValidation)return Json(new ChapterSyncReply{State="Failed",ChapterId=10,Revision=1,Message="Synthetic storage refusal: retry the chapter."});return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});}
if(path.EndsWith("/finish")){Finishes++;if(StructuralFailure)return Json(new ChapterSyncProgress{Total=2,Matching=1,State="Needs review",Message="One chapter accepted."});if(RejectValidation)return Json(new ChapterSyncProgress{Total=1,Matching=0,State="Needs review",Message="No chapters accepted."});return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});}
return Json(new{});
}
}
}