using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging.Abstractions; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Manuscript; using PlotDirector.Companion.Protocol.Manuscript; internal static class ManuscriptReaderTests { internal static readonly Chapter[] Chapters = [ new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" }, new() { ChapterID = 22, BookID = 12, ChapterNumber = 2, ChapterTitle = "Arrival" }, new() { ChapterID = 23, BookID = 12, ChapterNumber = 3, ChapterTitle = "Unwritten" } ]; internal static ParagraphManuscript Snapshot() { var heading = Guid.NewGuid(); return new() { BookId = 12, UpdatedUtc = new DateTime(2026, 11, 13, 10, 11, 12, DateTimeKind.Utc), Chapters = [new() { CanonicalId = 21, HeadingId = heading }], ChapterCheckpoints = [new() { ChapterId = 21, LastSuccessfulSyncUtc = new DateTime(2026, 11, 13, 10, 12, 13, DateTimeKind.Utc) }], Paragraphs = [ new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 2, Text = "Second paragraph.\r", Outline = 10 } }, new() { ChapterId = 21, Story = false, Occurrence = new() { Id = heading, Ordinal = 0, Text = "The crossing\r", Outline = 1 } }, new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 1, Text = "First paragraph: & plain text.\r", Outline = 10 } }, new() { ChapterId = 22, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 3, Text = "Another chapter only.\r", Outline = 10 } }, new() { ChapterId = null, Story = false, Occurrence = new() { Ordinal = 4, Text = "Excluded section." } } ] }; } internal static ManuscriptReaderService FixtureService(Func? snapshot = null) { var repository = NativeWorkflowTests.Proxy((name, args) => { if (name != "Get") throw new Exception("Reader attempted manuscript mutation: " + name); if ((int)args![0]! != 4 || (int)args[1]! != 12) throw new UnauthorizedAccessException(); return Task.FromResult(snapshot is null ? Snapshot() : snapshot()); }); var books = NativeWorkflowTests.Proxy((name, _) => name == "GetAsync" ? Task.FromResult(new() { BookID = 12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name)); var chapters = NativeWorkflowTests.Proxy((name, _) => name == "ListByBookAsync" ? Task.FromResult>(Chapters) : throw new Exception(name)); return new(repository, books, chapters); } public static async Task Run() { void Check(bool value, string message) { if (!value) throw new Exception(message); } var state = Snapshot(); var service = FixtureService(() => state); var first = (await service.Read(4, 12, null))!; Check(first.Chapters.Count == 3 && first.Chapter!.ChapterID == 21, "Book context and canonical chapter ordering"); Check(first.PreviousId is null && first.NextId == 22, "First chapter navigation"); Check(first.Paragraphs.Select(p => p.Text).SequenceEqual(state.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(3).Select(p => p.Occurrence.Text)), "Exact accepted paragraph order, heading and boundaries"); Check(first.Paragraphs.All(p => p.Id != Guid.Empty), "Paragraph identities retained internally"); Check(first.LastSuccessfulSyncUtc == state.ChapterCheckpoints[0].LastSuccessfulSyncUtc && first.SnapshotCapturedUtc == state.UpdatedUtc, "Distinct exact timestamp sources"); var last = (await service.Read(4, 12, 23))!; Check(last.PreviousId == 22 && last.NextId is null && last.Paragraphs.Count == 0, "Last chapter navigation and empty state"); Check(await service.Read(4, 12, 999) is null, "Cross-book or unknown chapter rejected"); try { await service.Read(5, 12, 21); throw new Exception("Foreign account retrieved manuscript"); } catch (UnauthorizedAccessException) { } try { await service.Read(4, 13, 21); throw new Exception("Foreign book retrieved manuscript"); } catch (UnauthorizedAccessException) { } var windows = Snapshot(); windows.Paragraphs = windows.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(4).ToList(); windows.Chapters.Add(new() { CanonicalId = 22, HeadingId = windows.Paragraphs[3].Occurrence.Id }); windows.Paragraphs.Insert(2, new() { Occurrence = new() { Id = Guid.NewGuid(), Text = " ", Ordinal = 1 } }); var complete = ManuscriptReaderService.Project(first.Book, Chapters, Chapters[0], windows); Check(complete.Paragraphs.Count == 4 && complete.Paragraphs.Any(p => p.Text == " "), "Heading windows preserve unassigned blank paragraphs and scene separators"); var pending = ParagraphManuscriptEngine.Clone(state); pending.Paragraphs[2].Occurrence.Text = "Pending change"; Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text != "Pending change", "Uncommitted or rejected submissions cannot enter Reader"); state = pending; Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text == "Pending change", "Next read sees newly committed snapshot without cache"); var empty = await FixtureService(() => null).Read(4, 12, 21); Check(empty!.Paragraphs.Count == 0 && empty.SnapshotCapturedUtc is null, "Missing accepted snapshot remains empty without bootstrap"); var user = NativeWorkflowTests.Proxy((_, _) => 5); var controller = new ManuscriptReaderController(service, user, NullLogger.Instance) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } }; Check(await controller.Index(12, 21) is NotFoundResult, "Controller does not leak unauthorised book existence"); Check(typeof(ManuscriptReaderController).IsDefined(typeof(AuthorizeAttribute), true), "Reader requires authentication"); var cache = (ResponseCacheAttribute)System.Attribute.GetCustomAttribute(typeof(ManuscriptReaderController), typeof(ResponseCacheAttribute))!; Check(cache.NoStore && cache.Location == ResponseCacheLocation.None, "Private manuscript responses cannot be cached"); Check(controller.Response.Headers["X-Robots-Tag"] == "noindex, nofollow, noarchive", "Manuscript indexing disabled"); Console.WriteLine("PASS Manuscript Reader: scoped read-only retrieval, ordering, navigation, empty snapshot, accepted updates, pending isolation and accurate timestamps"); } }