using System.Security.Cryptography; using System.Text; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services.Manuscript; public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading,int? SceneID=null); public sealed class ManuscriptReaderModel { public PlotLine.Services.Writer.WriterContext WorkingContext => new PlotLine.Services.Writer.WriterContext(Book.ProjectID, Book.BookID) .Select(PlotLine.Services.Writer.WriterFocusRole.Reader, new(Book.ProjectID, Book.BookID, Chapter?.ChapterID)); public long Revision { get; init; } = -1; public bool FocusReading { get; set; } public bool IntegratedReview {get;set;} public bool ReadingMode {get;set;} public Guid? ManuscriptID {get;init;} public string ContentVersion => Fingerprint(Paragraphs,ManuscriptID); public static string Fingerprint(IReadOnlyList paragraphs,Guid? manuscript=null) { using var buffer = new MemoryStream(); using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true)) { writer.Write(manuscript.GetValueOrDefault().ToByteArray()); writer.Write(paragraphs.Count); foreach (var paragraph in paragraphs) { writer.Write(paragraph.Id.ToByteArray()); writer.Write(paragraph.Text); writer.Write(paragraph.IsHeading); writer.Write(paragraph.SceneID??0); } } return Convert.ToHexString(SHA256.HashData(buffer.GetBuffer().AsSpan(0, (int)buffer.Length))); } public required Book Book { get; init; } public required IReadOnlyList Chapters { get; init; } public Chapter? Chapter { get; init; } public int? PreviousId { get; init; } public int? NextId { get; init; } public IReadOnlyList Paragraphs { get; init; } = []; public DateTime? LastSuccessfulSyncUtc { get; init; } public DateTime? SnapshotCapturedUtc { get; init; } } // Read only: deliberately bypasses the manuscript workspace, which may bootstrap tracking. public sealed class ManuscriptReaderService( IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters, PlotLine.Services.Writer.WriterWordService? wordMetadata=null, ISqlConnectionFactory? navigationFactory=null) { public async Task CanRead(int user, int bookId, int? chapterId) { if (navigationFactory is null) return await Read(user, bookId, chapterId) is not null; using var connection = navigationFactory.CreateConnection(); return await Dapper.SqlMapper.QuerySingleAsync(connection, "dbo.ManuscriptReader_CanRead", new { UserID = user, BookID = bookId, ChapterID = chapterId }, commandType: System.Data.CommandType.StoredProcedure); } public async Task Read(int user, int bookId, int? chapterId) { // This existing stored procedure checks active ProjectUserAccess before returning any data, // even when no paragraph snapshot exists. Never fetch book metadata before this check. var state = await manuscripts.Get(user, bookId); var book = await books.GetAsync(bookId); if (book is null || book.IsArchived) return null; var ordered = (await chapters.ListByBookAsync(bookId)).Where(c => !c.IsArchived).ToArray(); var selected = chapterId.HasValue ? ordered.FirstOrDefault(c => c.ChapterID == chapterId) : ordered.FirstOrDefault(); if (chapterId.HasValue && selected is null) return null; return Project(book, ordered, selected, state); } public async Task Check(int user, int bookId, int chapterId, long knownRevision, string knownVersion) { // Status transfers only metadata. Accepted prose changes always advance Revision; checkpoint // validation without changed prose may update metadata in place, which needs no rerender. var status = await manuscripts.Status(user, bookId); var book = await books.GetAsync(bookId); var chapter = await chapters.GetAsync(chapterId); if (book is null || book.IsArchived || chapter is null || chapter.IsArchived || chapter.BookID != bookId) return null; var revision = status?.Revision ?? -1; if (revision == knownRevision) { var metadata=wordMetadata==null?null:await wordMetadata.Metadata(user,bookId,chapterId);return new(revision,false,knownVersion,metadata?.ChapterAcceptedUtc,metadata?.SnapshotUtc); } var model = await Read(user, bookId, chapterId); return model is null ? null : new(model.Revision, model.ContentVersion != knownVersion, model.ContentVersion,model.LastSuccessfulSyncUtc,model.SnapshotCapturedUtc); } public static ManuscriptReaderModel Project(Book book, IReadOnlyList ordered, Chapter? selected, ParagraphManuscript? state) { var index = selected is null ? -1 : ordered.ToList().FindIndex(c => c.ChapterID == selected.ChapterID); var heading = state?.Chapters.FirstOrDefault(c => c.CanonicalId == selected?.ChapterID)?.HeadingId; // Accepted assignments, not live Word positions, govern reading. Position verification may // expire or need review without invalidating the last committed prose. IEnumerable source = state?.Paragraphs.Where(p => selected is not null && (p.ChapterId == selected.ChapterID || p.Occurrence.Id == heading)) ?? []; if (state is not null && selected is not null) { try { // Exact accepted heading windows also retain unassigned blank paragraphs and // scene separators. Excluded sections have their own canonical-zero boundary. var part = ChapterCheckpointEngine.Parts(state).FirstOrDefault(p => p.Chapter.CanonicalId == selected.ChapterID); if (part is not null && !part.Rows.Any(p => p.ChapterId > 0 && p.ChapterId != selected.ChapterID)) source = part.Rows; } catch (InvalidOperationException) { // Older accepted snapshots can lack reversible heading windows. Use only their // explicit chapter assignments; never guess boundaries from prose or Word offsets. } } var rows = source.OrderBy(p => p.Occurrence.Ordinal) .Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6, state?.Scenes.FirstOrDefault(s=>s.Id==p.SceneId&&!s.Retired&&s.CanonicalId>0&&s.ChapterId==selected?.ChapterID)?.CanonicalId)) .ToArray(); var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID); return new() { Revision = state?.Revision ?? -1, ManuscriptID=state?.ManuscriptId, Book = book, Chapters = ordered, Chapter = selected, Paragraphs = rows, PreviousId = index > 0 ? ordered[index - 1].ChapterID : null, NextId = index >= 0 && index + 1 < ordered.Count ? ordered[index + 1].ChapterID : null, LastSuccessfulSyncUtc = checkpoint?.LastSuccessfulSyncUtc > DateTime.MinValue ? checkpoint.LastSuccessfulSyncUtc : null, SnapshotCapturedUtc = state?.UpdatedUtc > DateTime.MinValue ? state.UpdatedUtc : null }; } } public sealed record ReaderChange(long Revision, bool Changed, string Version,DateTime? LastSuccessfulSyncUtc=null,DateTime? SnapshotCapturedUtc=null);