31 lines
2.9 KiB
C#

using PlotDirector.Companion.Protocol;
using PlotLine.Models;
namespace PlotLine.Services.NativeCompanion;
// Only constructs a read-only plan. Canonical import remains owned by the existing application.
public static class NativeImportPreview
{
public static WordCompanionManuscriptImportRequest Build(ImportPreviewRequest input,int project)
{
if(input.SessionId==Guid.Empty||input.SnapshotId==Guid.Empty||input.ManuscriptId==Guid.Empty||input.Items==null||input.Items.Length is <1 or >80)throw new ArgumentException("Select a bounded set of chapter/scene rows from one current snapshot.");
if(input.Items.Any(s=>s==null||s.Kind is not ("Chapter" or "Scene")||s.Start<0||string.IsNullOrWhiteSpace(s.Title)||s.Title.Length>200||s.Reason?.Length>600))throw new ArgumentException("A selected row has no valid title/range or is an error row.");
if(input.Items.GroupBy(s=>(s.Kind,s.Start)).Any(g=>g.Count()>1))throw new ArgumentException("Duplicate or competing boundaries selected. Choose one local/AI boundary at each position.");
var chapters=input.Items.Where(s=>s.Kind=="Chapter").OrderBy(s=>s.Start).ToArray();
if(chapters.Length==0||chapters.Any(c=>c.End<=c.Start)||chapters.Zip(chapters.Skip(1)).Any(pair=>pair.First.End>pair.Second.Start))throw new ArgumentException("Select nonoverlapping chapter ranges.");
var selectedScenes=input.Items.Where(s=>s.Kind=="Scene").OrderBy(s=>s.Start).ToArray();
if(selectedScenes.Any(s=>s.End<=s.Start))throw new ArgumentException("Scene ranges must have a positive length.");
if(selectedScenes.Any(s=>chapters.Count(c=>s.Start>=c.Start&&s.Start<c.End)!=1))throw new ArgumentException("Each scene needs its selected parent chapter.");
foreach(var chapter in chapters)
{
var scenes=selectedScenes.Where(s=>s.Start>=chapter.Start&&s.Start<chapter.End).ToArray();
if(scenes.Length==0)throw new ArgumentException("Choose scenes for every selected chapter; no placeholder scene is invented.");
for(var i=0;i<scenes.Length;i++)if(scenes[i].End>chapter.End||(i+1<scenes.Length&&scenes[i].End>scenes[i+1].Start))throw new ArgumentException("Scene ranges overlap or extend outside their chapter. Review competing local/AI choices.");
}
var request=new WordCompanionManuscriptImportRequest{ProjectId=project,BookId=input.BookId,DocumentGuid=input.ManuscriptId,ReplacePlanned=false,
Chapters=chapters.Select((c,i)=>new WordCompanionManuscriptImportChapterRequest{Title=c.Title,SortOrder=i+1,WordCount=0,
Scenes=selectedScenes.Where(s=>s.Start>=c.Start&&s.Start<c.End).Select((s,j)=>new WordCompanionManuscriptImportSceneRequest{Title=s.Title,SortOrder=j+1,WordCount=0}).ToArray()}).ToArray()};
if(!WordCompanionService.ValidImportStructure(request))throw new ArgumentException("The existing importer rejected this structure.");
return request;
}
}