using System.Security.Cryptography; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using PlotDirector.Companion.Protocol; using PlotLine.Data; namespace PlotLine.Services.NativeCompanion; // Historical offsets are usable only with authenticated source content and its original live session. // Word revisions are local to an open session; a reopened/copy document cannot inherit this proof. public sealed class NativeReviewNavigation(IDataProtectionProvider protection) { public const string Unavailable = "The original Word position can no longer be verified. Review decisions remain available; resubmit the chapter from Word to establish a current position."; private readonly IDataProtector source = protection.CreateProtector("NativeImport.Source.v1"); public NativeLease[] Candidates(int author, NativeReview row, AiChapterResult result, IEnumerable leases) { var matching = leases.Where(l => l.Session == row.SourceSession).Take(2).ToArray(); return matching.Length == 1 && Current(author, row, result, matching[0]) ? matching : []; } public bool Current(int author, NativeReview row, AiChapterResult result, NativeLease lease) { if (result.Scenes == null || result.Scenes.Length == 0 || row.BookID <= 0 || row.UserID != author || lease.User != author || lease.Instance == Guid.Empty || row.SourceSession is not Guid session || session == Guid.Empty || session != lease.Session || row.SourceRevision is not long revision || revision < 0 || revision != result.DocumentRevision || lease.Position.Revision != revision || lease.Position.BookId != row.BookID || lease.Position.ManuscriptId != row.ManuscriptID || row.ManuscriptID == Guid.Empty || !lease.Position.WordAvailable || lease.Position.WordSaved != true || !lease.Position.CanAcknowledgeNavigation || string.IsNullOrEmpty(row.EncryptedSource)) return false; try { var capture = JsonSerializer.Deserialize(source.Unprotect(row.EncryptedSource)); if (capture == null || capture.SessionId != session || capture.Revision != revision || capture.BookId != row.BookID || capture.ManuscriptId != row.ManuscriptID || capture.ChapterStart != row.ChapterStart || capture.ChapterEnd != row.ChapterEnd) return false; NativeChapterMapping.Build(capture); var hash = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { capture.ChapterStart, capture.ChapterEnd, capture.Paragraphs }))); return hash == row.ContentHash && result.Scenes.All(scene => scene.Start >= capture.ChapterStart && scene.End <= capture.ChapterEnd && scene.End > scene.Start && capture.Paragraphs.Any(p => p.Start == scene.Start) && capture.Paragraphs.Any(p => p.End == scene.End)); } catch (Exception e) when (e is CryptographicException or JsonException or ArgumentException) { return false; } } }