using System.Security.Claims; using ImportPreview = PlotDirector.Companion.Protocol.ImportPreview; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotDirector.Companion.Protocol; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] public sealed class NativeCompanionWorkflowController(IWordCompanionRepository access,IBookRepository books,IWordCompanionService companion,IStoryContextService context,IWriterWorkspaceService writer,IStoryIntelligenceClient ai,ISubscriptionService subscriptions):ControllerBase { private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("connection")] public async Task Connection() { var entitled=(await subscriptions.CanUseFeatureAsync(UserId,SubscriptionFeature.StoryIntelligence)).Allowed; var config=ai.GetConfigurationStatus();DateTime.TryParse(User.FindFirstValue("NativeCompanion.Expires"),null,System.Globalization.DateTimeStyles.AdjustToUniversal,out var expiry); return Ok(new ConnectionHealth{Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=expiry,Ai=!entitled?"not-entitled":config.ApiKeyConfigured&&!string.IsNullOrWhiteSpace(config.ChapterStructureModel)?"configured":"not-configured",Explanation="Authenticated server check. AI configuration is known; provider availability is only proven by an explicit analysis request."}); } [HttpGet("books/{bookId:int}/workspace")] public async Task Workspace(int bookId,int? chapterId,int? sceneId) { var structure=await access.GetBookStructureAsync(bookId,UserId);if(structure==null)return Forbid(); var book=await books.GetAsync(bookId);if(book==null)return NotFound(); var parent=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):chapterId.HasValue?structure.Chapters.FirstOrDefault(c=>c.ChapterId==chapterId):null; if((sceneId.HasValue||chapterId.HasValue)&&(parent==null||(chapterId.HasValue&&parent.ChapterId!=chapterId)))return NotFound(); var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId):null; if(sceneId.HasValue&&saved?.Scene==null)return NotFound(); var workflow=parent!=null?await writer.GetChapterWorkflowAsync(parent.ChapterId):null; if(workflow!=null&&(workflow.Book.BookID!=bookId||workflow.Project.ProjectID!=book.ProjectID))return Forbid(); string Cut(string? s,int max=2000)=>string.IsNullOrWhiteSpace(s)?"":s.Length>max?s[..max]:s; var goal=workflow?.Goal; var scope=$"projectId={book.ProjectID}&bookId={bookId}"+(parent!=null?$"&chapterId={parent.ChapterId}":"")+(sceneId.HasValue?$"&sceneId={sceneId}":"")+"&pinned=true"; return Ok(new SavedWorkspace{BookId=bookId,ProjectId=book.ProjectID,ChapterId=parent?.ChapterId,SceneId=sceneId,Title=Cut(book.BookDisplayTitle,200)+(parent!=null?" / "+Cut(parent.Title,200):"")+(saved?.Scene!=null?" / "+Cut(saved.Scene.SceneTitle,200):""), Context=Cut(saved?.Scene?.Summary??workflow?.Chapter?.Summary??book.ShortDescription??book.Description), Intent=Cut(string.Join("\n",new[]{saved?.Scene?.ScenePurposeNotes,goal?.GoalSummary,goal?.EmotionalGoal,goal?.ReaderTakeaway,goal?.MustInclude}.Where(s=>!string.IsNullOrWhiteSpace(s)))), State=sceneId.HasValue?"saved-scene":parent!=null?"saved-chapter":"saved-book",BookPath=$"/Books/Details/{bookId}",ContextPath="/Writing/Context?"+scope,IntentPath="/Writing/Intent?"+scope}); } [HttpPost("import-preview"),RequestSizeLimit(160*1024)] public async Task Preview(ImportPreviewRequest input) { if(!(await subscriptions.CanUseFeatureAsync(UserId,SubscriptionFeature.Import)).Allowed)return Forbid(); if(await access.GetBookStructureAsync(input.BookId,UserId)==null)return Forbid(); var book=await books.GetAsync(input.BookId);if(book==null)return NotFound(); try { var plan=NativeImportPreview.Build(input,book.ProjectID); var check=await companion.AnalyseManuscriptAsync(new(){ProjectId=book.ProjectID,BookId=input.BookId,DocumentGuid=input.ManuscriptId,ChapterCount=plan.Chapters.Count,SceneCount=plan.Chapters.Sum(c=>c.Scenes.Count),WordCount=0}); if(check==null)return Forbid(); return Ok(new ImportPreview{RequestId=input.RequestId,State=check.LinkedChapterCount>0?"already-linked":check.RequiresReplaceConfirmation?"existing-content":check.CanImport?"validated-preview":"rejected",Chapters=plan.Chapters.Count,Scenes=plan.Chapters.Sum(c=>c.Scenes.Count),ExistingChapters=check.ExistingChapterCount,ExistingScenes=check.ExistingSceneCount, Message=check.Message+" Native commit is unavailable: the established import also owns prose sources, persistent binding, marker/save acknowledgement and partial-build recovery. This preview creates or replaces nothing. Selected counts are structural; prose word counts are not uploaded. Continue the established book import in PlotDirector; these native choices are not automatically transferred.",BookPath=$"/Books/Details/{input.BookId}",CommitAvailable=false}); } catch(ArgumentException e){return BadRequest(new ImportPreview{RequestId=input.RequestId,State="rejected",Message=e.Message});} } }