using System.Diagnostics;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ChapterRangeVerificationTests
{
public static string Xml(int chapter,string text)
{
var heading=$"Chapter {chapter}\r";
var body=System.Security.SecurityElement.Escape(text.Substring(heading.Length).TrimEnd('\r'));
return $"Chapter {chapter}{body}";
}
public static void Run()
{
void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
var text="Chapter 0\rBody text\r";var xml=Xml(0,text);
var rows=ChapterFingerprint.ReadXml(xml,text);
var baseline=new ChapterManifestItem{Algorithm=ChapterFingerprint.Version,DurableAccepted=true,HeadingNativeId=rows[0].NativeId,ContentHash=ChapterFingerprint.Content(rows.Select(p=>p.Text!)),IdentityHash=ChapterFingerprint.Identity(rows),ParagraphCount=2};
Check(ChapterRangeVerification.Content(text)==baseline.ContentHash,"Range-only fingerprint uses the accepted paragraph-delimited algorithm");
Check(ChapterRangeVerification.Compare(text,xml,baseline,"")==ChapterRangeResult.Matching,"Complete unchanged XML identity evidence avoids the native paragraph walk");
using(var wire=new MemoryStream())
{
FrameCodec.WriteAsync(wire,new Message{Command=new AdapterCommand{Kind="chapter-check",RangeBaseline=baseline,ObserveOnly=true,RecheckRevision=true}},default).GetAwaiter().GetResult();
wire.Position=0;var decoded=FrameCodec.ReadAsync(wire,default).GetAwaiter().GetResult();
Check(decoded.Command is {ObserveOnly:true,RecheckRevision:true,RangeBaseline:not null}&&decoded.Command.RangeBaseline.IdentityHash==baseline.IdentityHash,"Range baselines and read-only flags survive the actual native IPC codec");
}
var compact=ChapterRangeVerification.Check(text,xml,baseline,"").IdentityFrames;
Check(ChapterFingerprint.Identity(ChapterFingerprint.ReadLiveText(text,compact))==baseline.IdentityHash,"Locally verified XML emits the existing compact identity frames without transmitting XML");
Check(ChapterRangeVerification.Compare(text.Replace("Body","Edit"),xml,baseline,"")==ChapterRangeResult.Changed,"A same-length text edit is found without length or saved-state changes");
Check(ChapterRangeVerification.Compare(text,xml.Replace("00000002","000000FF"),baseline,"")==ChapterRangeResult.Changed,"Identical prose with replaced native identity is a changed chapter");
Check(ChapterRangeVerification.Compare(text,xml.Replace(" w14:paraId='00000002'",""),baseline,"")==ChapterRangeResult.RequiresDetailed,"Missing exported native identities require detailed verification rather than guessed checkpoint reuse");
Check(ChapterRangeVerification.Compare(text,xml.Replace("Body","Body"),baseline,"")==ChapterRangeResult.RequiresDetailed,"Floating drawing evidence retains the qualified native anchor reader");
foreach(var element in new[]{"tbl","fldChar","ins","del","footnoteReference","object","altChunk"})
Check(ChapterRangeVerification.Compare(text,xml.Replace("",$""),baseline,"")==ChapterRangeResult.RequiresDetailed,$"Structural {element} cannot take the lightweight reuse path");
Check(ChapterRangeVerification.Compare(text,xml,baseline,"000000FF")==ChapterRangeResult.Changed,"Changed chapter order and boundaries cannot retain range evidence");
baseline.PositionHash=new string('A',64);
Check(ChapterRangeVerification.Compare(text,xml,baseline,"")==ChapterRangeResult.RequiresDetailed,"Native geometry gaps always retain measured position validation");
var values=Enumerable.Range(0,48).Select(i=>$"Chapter {i}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray();
var expected=values.Select((value,i)=>ChapterFingerprint.Content([$"Chapter {i}\r",value[($"Chapter {i}\r").Length..]])).ToArray();
var matches=new bool[48];var watch=Stopwatch.StartNew();
for(var i=0;i<48;i++)matches[i]=ChapterRangeVerification.Content(values[i])==expected[i];
watch.Stop();
for(var i=0;i<48;i++)Check(matches[i],"Scale range fingerprint preserves exact chapter content "+i);
Console.WriteLine($"MEASURE range fingerprint CPU only: 48 chapters, {values.Sum(p=>p.Length)} UTF-16 units, {watch.Elapsed.TotalMilliseconds:F1}ms. Text was preallocated in memory. Range.Text extraction, Word XML export and Word UI responsiveness NOT measured.");
}
}