using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using PlotDirector.Companion.Protocol; using PlotLine.Data; namespace PlotLine.Services.NativeCompanion; public sealed record NativeImportItem(Guid ReviewID,int Version,string Key,string Hash,string Title,int Start,int End,NativeImportScene[] Scenes); public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int? StartParagraph,int? EndParagraph,int Words); public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket,string BookTitle="",int ProjectID=0); public sealed record NativeImportTicket(int User,int Book,Guid[] Reviews,int[] Versions,DateTime Expires,Guid Operation); public sealed class NativeImportResult {public int ProjectID{get;set;}public string BookTitle{get;set;}="";public int BookID{get;set;}public int Skipped{get;set;}public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";} public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions,IBookRepository? books=null) { private readonly IDataProtector ticket=protection.CreateProtector("NativeImport.Confirmation.v1"); private readonly IDataProtector source=protection.CreateProtector("NativeImport.Source.v1"); public string Protect(AiChapterRequest request)=>source.Protect(JsonSerializer.Serialize(request)); public async Task Preview(int user,int book,Guid[] ids,Guid? operation=null) { if(!(await subscriptions.CanUseFeatureAsync(user,Models.SubscriptionFeature.Import)).Allowed)throw new UnauthorizedAccessException("Import is not available on this account."); var structure=await access.GetBookStructureAsync(book,user)??throw new UnauthorizedAccessException("Book access denied."); if(ids.Length is <1 or >100||ids.Distinct().Count()!=ids.Length)throw new ArgumentException("Select up to 100 different chapter reviews."); var metadata=books==null?null:await books.GetAsync(book); var items=new List();var conflicts=new List();var skipped=0;Guid manuscript=Guid.Empty;var versions=new List(); foreach(var id in ids){var row=await reviews.Get(user,id)??throw new ArgumentException("A review expired or is unavailable.");if(row.BookID!=book)throw new UnauthorizedAccessException("Reviews must belong to this book.");versions.Add(row.Version); if(manuscript==Guid.Empty)manuscript=row.ManuscriptID;if(manuscript!=row.ManuscriptID)throw new ArgumentException("Select chapters from one manuscript."); var result=JsonSerializer.Deserialize(row.ResultJson)!;var decisions=string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!; var approved=decisions.Where(d=>d.State=="approved").OrderBy(d=>d.Index).ToArray();skipped+=result.Scenes.Length-approved.Length; if(approved.Length==0){conflicts.Add($"{result.ChapterTitle}: no approved scenes. Save review decisions first.");continue;} if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Reconnect the Companion, enable encrypted import capture in browser approval, and explicitly resubmit this chapter.");continue;} var capture=JsonSerializer.Deserialize(source.Unprotect(row.EncryptedSource))!;NativeChapterMapping.Build(capture); if(Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))!=row.ContentHash)throw new ArgumentException("Source content no longer matches this review."); if(capture.ManuscriptId!=row.ManuscriptID||capture.BookId!=book||capture.ChapterStart!=row.ChapterStart||capture.ChapterEnd!=row.ChapterEnd)throw new ArgumentException("Source identity mismatch."); var title=string.IsNullOrWhiteSpace(result.ChapterTitle)?"Chapter":result.ChapterTitle;var key="native:"+manuscript.ToString("N")+":"+row.ChapterStart; // Captures use chapter-relative paragraph indices. Do not mislabel them as // whole-document Word paragraph positions; native navigation uses absolute ranges. var scenes=new List();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,null,null,Count(text)));} items.Add(new(row.ReviewID,row.Version,key,row.ContentHash,title,row.ChapterStart,row.ChapterEnd,scenes.ToArray())); } var imported=await imports.List(user,book);var pending=new List();foreach(var item in items.OrderBy(i=>i.Start)){ var prior=imported.FirstOrDefault(p=>p.ChapterKey==item.Key);if(prior!=null){if(prior.ContentHash==item.Hash&&prior.ReviewVersion==item.Version){skipped+=item.Scenes.Length;continue;}conflicts.Add(item.Title+": already imported with different content/decisions; existing scenes will not be overwritten.");continue;} if(imported.Any(p=>p.DocumentGuid==manuscript&&p.ChapterStartstring.Equals(c.Title.Trim(),item.Title.Trim(),StringComparison.OrdinalIgnoreCase)))conflicts.Add(item.Title+": an existing chapter has this title. Resolve the match before importing; no replacement is performed."); if(pending.Any(p=>p.Start Commit(int user,string confirmation) { NativeImportTicket saved;try{saved=JsonSerializer.Deserialize(ticket.Unprotect(confirmation))!;}catch(Exception e)when(e is CryptographicException or JsonException or ArgumentException){throw new ArgumentException("Invalid import confirmation.");} if(saved.User!=user||saved.Expires0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){BookID=saved.Book,Skipped=plan.Skipped,AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."}; var result=await imports.Commit(user,saved.Operation,plan);result.BookID=saved.Book;result.ProjectID=plan.ProjectID;result.BookTitle=plan.BookTitle;result.Skipped=plan.Skipped;return result; } private static int Count(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length; }