using System.Data; using System.Security.Cryptography; using System.Text; using Dapper; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services.Manuscript; namespace PlotLine.Services.Writer; public sealed class ReviewObservation { public Guid ID{get;set;}public int UserID{get;set;}public int BookID{get;set;}public int ChapterID{get;set;} public Guid? ManuscriptID{get;set;}public long SnapshotRevision{get;set;}public string ContentVersion{get;set;}=""; public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}public string? AnchorHash{get;set;}public int? SceneID{get;set;} public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";public int Version{get;set;}public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;} public string AnchorState{get;set;}="Chapter"; } public sealed class ReviewSave { public int BookID{get;set;}public int ChapterID{get;set;}public Guid ID{get;set;}public int Version{get;set;} public string ContentVersion{get;set;}="";public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;} public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open"; } public sealed record ReviewPanel(WriterAuthoringPage Intentions,IReadOnlyList Observations,int Page,bool HasMore,string ReferenceMessage); public interface IWriterReviewService { Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null); Task Save(int actor,ReviewSave request); } public sealed class WriterReviewService(ISqlConnectionFactory factory,ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService { public static string Hash(IEnumerable paragraphs){using var buffer=new MemoryStream();using(var writer=new BinaryWriter(buffer,Encoding.UTF8,true))foreach(var p in paragraphs){writer.Write(p.Id.ToByteArray());writer.Write(p.Text);}return Convert.ToHexString(SHA256.HashData(buffer.ToArray()));} public static string Validate(ReviewSave r)=>r.ID==Guid.Empty||r.Version<0?"Choose a valid observation.":r.Status is not("Open" or "Working" or "Resolved")?"Choose a valid observation state.":string.IsNullOrWhiteSpace(r.Observation)?"Record what you noticed before saving.":r.Observation.Length>10000||(r.Decision?.Length??0)>10000?"Keep each observation and decision within 10,000 characters.":""; public static ReaderParagraph[] Anchor(ManuscriptReaderModel model,Guid? first,Guid? last,int? start,int? end){ if(first==null&&last==null&&start==null&&end==null)return []; var rows=model.Paragraphs.ToArray();var from=Array.FindIndex(rows,p=>p.Id==first);var to=Array.FindIndex(rows,p=>p.Id==last); if(from<0||torows[from].Text.Length||end>rows[to].Text.Length||from==to&&end Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){ if(page<1||page>100000)throw new ArgumentException("Choose a valid observations page.");var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException(); var selected=source.ContentVersion==version?source.Paragraphs.SingleOrDefault(p=>p.Id==paragraph):null; int? selectedScene=selected?.SceneID; if(selected!=null&&endParagraph.HasValue){var all=source.Paragraphs.ToArray();var first=Array.FindIndex(all,p=>p.Id==selected.Id);var last=Array.FindIndex(all,p=>p.Id==endParagraph);if(lastp.SceneID!=selectedScene))selectedScene=null;} WriterAuthoringPage context; try{context=await intentions.Read(actor,book,chapter,selectedScene);} catch(Exception e)when(selectedScene.HasValue&&(e is KeyNotFoundException||e is Microsoft.Data.SqlClient.SqlException {Number:51000})){selectedScene=null;context=await intentions.Read(actor,book,chapter,null);} using var db=factory.CreateConnection();var rows=(await db.QueryAsync("dbo.WriterReview_Observations",new{Action="list",UserID=actor,BookID=book,ChapterID=chapter,Page=page},commandType:CommandType.StoredProcedure)).ToArray();foreach(var row in rows)row.AnchorState=AnchorState(row,source); return new(context,rows.Take(50).ToArray(),page,rows.Length>50,selectedScene!=null?"Scene context comes from accepted paragraph assignments.":paragraph.HasValue?"No current verified scene assignment for this passage. Chapter intentions remain available.":"Chapter intentions; choose a recorded passage for verified scene context."); } public async Task Save(int actor,ReviewSave r){ var error=Validate(r);if(error.Length>0)throw new ArgumentException(error); ManuscriptReaderModel? source=null;ReaderParagraph[] rows=[]; if(r.Version==0){source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();if(r.ContentVersion!=source.ContentVersion)throw new AuthoringConflictException("The accepted chapter changed. Your observation text is retained. Refresh the manuscript before choosing its reference again.");rows=Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);} int? scene=rows.Length>0&&rows[0].SceneID.HasValue&&rows.All(p=>p.SceneID==rows[0].SceneID)?rows[0].SceneID:null; using var db=factory.CreateConnection();try{return await db.QuerySingleAsync("dbo.WriterReview_Observations",new{Action=r.Version==0?"create":"update",UserID=actor,r.BookID,r.ChapterID,r.ID,r.Version,ManuscriptID=source?.ManuscriptID,SnapshotRevision=source?.Revision,ContentVersion=source?.ContentVersion,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset,AnchorHash=rows.Length>0?Hash(rows):null,SceneID=scene,r.Observation,r.Decision,r.Status},commandType:CommandType.StoredProcedure);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){throw new AuthoringConflictException("The observation or accepted manuscript changed. Your text is retained. Reload the recorded observations before retrying.",e);} } }