using PlotLine.Services.Writer; using PlotLine.Services.Manuscript; using PlotLine.Models; internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService { private static readonly object gate=new();private static readonly Dictionary rows=[]; public async Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID);if(chapter!=21)context=new(){BookID=12,ChapterID=chapter,Chapter=source.Chapter!,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}} public async Task Save(int actor,ReviewSave r){var source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();var error=WriterReviewService.Validate(r);if(error.Length>0)throw new ArgumentException(error);lock(gate){if(r.Version==0){if(rows.TryGetValue(r.ID,out var existing)){if(existing.UserID==actor&&existing.Observation==r.Observation)return existing;throw new AuthoringConflictException("Observation changed; your text is retained.");}if(source.ContentVersion!=r.ContentVersion)throw new AuthoringConflictException("Accepted chapter changed; your text is retained.");var anchors=WriterReviewService.Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);var row=new ReviewObservation{ID=r.ID,UserID=actor,BookID=r.BookID,ChapterID=r.ChapterID,ContentVersion=r.ContentVersion,ManuscriptID=source.ManuscriptID,SnapshotRevision=source.Revision,StartParagraph=r.StartParagraph,EndParagraph=r.EndParagraph,StartOffset=r.StartOffset,EndOffset=r.EndOffset,AnchorHash=anchors.Length>0?WriterReviewService.Hash(anchors):null,SceneID=anchors.FirstOrDefault()?.SceneID,Observation=r.Observation,Decision=r.Decision,Status=r.Status,Version=1,CreatedUtc=DateTime.UtcNow,UpdatedUtc=DateTime.UtcNow};rows[r.ID]=row;return row;} if(!rows.TryGetValue(r.ID,out var saved)||saved.UserID!=actor||saved.BookID!=r.BookID||saved.ChapterID!=r.ChapterID||saved.Version!=r.Version)throw new AuthoringConflictException("Another window changed this observation; your text is retained.");saved.Observation=r.Observation;saved.Decision=r.Decision;saved.Status=r.Status;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}} }