using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using PlotLine.Data; using PlotLine.Services.NativeCompanion; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize] [Route("Writing")] [ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class WritingController( IStoryContextService storyContext, IRelationshipMapService relationshipMap, IFloorPlanService floorPlans, IWriterWorkspaceService writerWorkspace, ILogger logger,IStoryCalendarService? calendar=null,IWordCompanionRepository? companion=null) : Controller { [HttpGet("Context")] public async Task Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) { ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId; logger.LogInformation( "Opening Writing Context. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}", projectId, bookId, chapterId, sceneId, documentGuid.HasValue); if(!sceneId.HasValue&&bookId.HasValue&&companion!=null) { var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId; } var display = sceneId.HasValue ? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context") : WaitingContextDisplay(projectId, bookId, documentGuid); if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}} var model = new WritingContextPageViewModel { ProjectID = projectId, BookID = bookId, ChapterID = chapterId, SceneID = sceneId, DocumentGuid = documentGuid, Display = display ?? MissingContextDisplay(projectId, bookId, sceneId) }; return View(model); } [HttpGet("Intent")] public async Task Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) { ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId; logger.LogInformation( "Opening Writing Intent. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}", projectId, bookId, chapterId, sceneId, documentGuid.HasValue); if(!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) { var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault(); chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId; } var display = sceneId.HasValue || chapterId.HasValue ? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent") : WaitingIntentDisplay(projectId, bookId, documentGuid); if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue&&!chapterId.HasValue){display.EmptyTitle="No saved writing objective selected";display.EmptyMessage="Choose a saved chapter or scene in PlotDirector. Set its goal/purpose explicitly; this view does not invent or automatically save intent.";}} var model = new WritingIntentPageViewModel { ProjectID = projectId, BookID = bookId, ChapterID = chapterId, SceneID = sceneId, DocumentGuid = documentGuid, Display = display ?? MissingIntentDisplay(projectId, bookId, chapterId, sceneId) }; return View(model); } [HttpGet("Context/Scene")] public async Task ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId) { if (!sceneId.HasValue) { logger.LogWarning("Writing Context partial requested without SceneID. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID}", projectId, bookId, chapterId); return PartialView("~/Views/Writing/_WritingContextContent.cshtml", WaitingContextDisplay(projectId, bookId, null)); } var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); if (model?.HasScene == true) { return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model); } logger.LogWarning("Writing Context could not resolve scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId); return PartialView("~/Views/Writing/_WritingContextContent.cshtml", MissingContextDisplay(projectId, bookId, sceneId)); } [HttpGet("Intent/Scene")] public async Task IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId) { if (!sceneId.HasValue && !chapterId.HasValue) { logger.LogWarning("Writing Intent partial requested without ChapterID or SceneID. ProjectID={ProjectID} BookID={BookID}", projectId, bookId); return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", WaitingIntentDisplay(projectId, bookId, null)); } var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); if (model is not null && (model.HasScene || model.HasChapter)) { return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model); } logger.LogWarning("Writing Intent could not resolve chapter/scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId); return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", MissingIntentDisplay(projectId, bookId, chapterId, sceneId)); } private async Task BuildDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus) { if (!sceneId.HasValue) { return new WritingContextDisplayViewModel { FollowStatus = followStatus }; } var context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId); if (context?.Scene is null) { return null; } var position = context.Position; var relationships = await relationshipMap.GetAsync(position, null, true); var floorPlan = context.Scene.FloorPlanID.HasValue ? await floorPlans.GetEditorAsync(context.Scene.FloorPlanID.Value) : null; var nearby = calendar is not null && context.Scene.StartDateTime.HasValue ? (await calendar.GetAsync(position.ProjectId,position.BookId,null,DateOnly.FromDateTime(context.Scene.StartDateTime.Value)))?.DatedScenes.Where(x=>x.SceneID!=sceneId && x.StartDateTime.HasValue && Math.Abs((x.StartDateTime.Value-context.Scene.StartDateTime.Value).TotalDays)<=3).OrderBy(x=>x.StartDateTime).Take(5).ToArray() ?? [] : []; return new WritingContextDisplayViewModel { NearbyScenes = nearby, Context = context, RelationshipMap = relationships, FloorPlan = floorPlan, FollowStatus = followStatus, SceneOptions = await ContextSceneOptions(context.Scene) }; } private async Task BuildIntentDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus) { StoryContextViewModel? context = null; if (sceneId.HasValue) { context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId); if (context?.Scene is null) { return null; } } var resolvedChapterId = context?.Position.ChapterId ?? chapterId; var chapterWorkflow = resolvedChapterId.HasValue ? await writerWorkspace.GetChapterWorkflowAsync(resolvedChapterId.Value) : null; if (chapterWorkflow is not null) { if (projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value) { return null; } if (bookId.HasValue && chapterWorkflow.Book.BookID != bookId.Value) { return null; } } if (context is null && chapterWorkflow is null) { return null; } return new WritingIntentDisplayViewModel { Context = context, ChapterWorkflow = chapterWorkflow, FollowStatus = followStatus, SceneOptions = context?.Scene is not null ? await ContextSceneOptions(context.Scene) : BuildSceneOptions(chapterWorkflow) }; } [HttpGet("Context/Map")] public async Task ContextMap(int projectId,int bookId,int sceneId,int? mapId,[FromServices] MapRepository maps,[FromServices] IMapStoryService storyMaps,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books) { if(!await permissions.CanAccessProjectAsync(projectId)||(await books.GetAsync(bookId))?.ProjectID!=projectId||companion==null)return NotFound(); var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); var structure=await companion.GetBookStructureAsync(bookId,user); if(structure==null||!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))return NotFound(); var choices=await maps.ListAsync(projectId,user); var selected=mapId.HasValue?choices.FirstOrDefault(m=>m.MapID==mapId):choices.FirstOrDefault(); if(mapId.HasValue&&selected==null)return NotFound(); MapStoryProjection? projection=selected==null?null:await storyMaps.GetAsync(projectId,selected.MapID,user); var position=projection?.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.Position; if(!mapId.HasValue&&position?.FeatureID==null&&position?.DetailMapID is int mapped&&choices.FirstOrDefault(m=>m.MapID==mapped) is {} linked) { selected=linked;projection=await storyMaps.GetAsync(projectId,linked.MapID,user);position=projection?.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.Position; } return PartialView("_WritingContextMap",new WritingContextMapViewModel{ProjectID=projectId,BookID=bookId,SceneID=sceneId,Maps=choices,Document=selected==null?null:await maps.GetAsync(projectId,selected.MapID,user),Story=projection,Position=position}); } [HttpGet("Context/PlotLines")] public async Task ContextPlotLines(int projectId,int bookId,[FromServices] IPlotLineWorkspaceService plots,[FromServices] IProjectAccessService permissions) { if(!await permissions.CanAccessProjectAsync(projectId))return NotFound(); var initial=await plots.GetAsync(projectId,bookId,null,null,null,false,false);if(initial==null)return NotFound(); var model=initial.PlotLines.Count>1?await plots.GetAsync(projectId,bookId,initial.PlotLines.Select(l=>l.Line.PlotLineID),null,null,false,false):initial; return PartialView("_WritingContextPlotLines",model); } [HttpGet("Context/Metrics")] public async Task ContextMetrics(int projectId,int bookId,[FromServices] ITimelineRepository timeline,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books,[FromServices] ISceneRepository sceneMetrics) { if(!await permissions.CanAccessProjectAsync(projectId)||(await books.GetAsync(bookId))?.ProjectID!=projectId)return NotFound(); var data=await timeline.GetByProjectAsync(projectId,bookId,false,[],false); var recorded=await sceneMetrics.ListRecordedMetricsByBookAsync(bookId,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); return data.Project==null?NotFound():PartialView("_WritingContextMetrics",WritingContextMetrics.Build(data,recorded)); } private async Task> ContextSceneOptions(SceneEditViewModel scene) { if(companion==null)return BuildSceneOptions(scene); var structure=await companion.GetBookStructureAsync(scene.Book!.BookID,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); return structure?.Chapters.SelectMany(c=>c.Scenes.Select(s=>new SelectListItem($"{c.Title} ยท {s.Title}",s.SceneId.ToString(),s.SceneId==scene.SceneID))).ToList()??[]; } [HttpPost("Context/Navigate"),ValidateAntiForgeryToken] public async Task NavigateWord(int bookId,int sceneId,Guid? instanceId,Guid? sessionId, [FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence,Guid? navigationId=null,[FromServices] IChapterSyncRepository? chapterPositions=null) { if(!ModelState.IsValid||bookId<=0||sceneId<=0||instanceId.HasValue!=sessionId.HasValue)return BadRequest(new{message="Choose a valid scene and a complete Word document session. No navigation was sent."}); var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); var structure=await access.GetBookStructureAsync(bookId,user);if(structure==null)return Forbid(); var chapter=structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId));if(chapter==null)return NotFound(); var leases=presence.Read(user,bookId).Where(l=>l.Position.WordAvailable).ToArray(); var candidates=instanceId.HasValue&&sessionId.HasValue?leases.Where(l=>l.Instance==instanceId&&l.Session==sessionId).ToArray():leases.Where(l=>l.Position.Active).ToArray(); var lease=candidates.Length==1?candidates[0]:!instanceId.HasValue&&leases.Length==1?leases[0]:null; if(lease==null)return Conflict(new{message="No single connected Word document is selected. Scene navigation remains available here."}); var state=await paragraphs.Get(user,bookId); if(state==null||lease.Position.WordSaved!=true||(!lease.Position.CanChapterSync&&(state.SessionId!=lease.Session||state.WordRevision!=lease.Position.Revision))||state.ManuscriptId!=lease.Position.ManuscriptId)return Conflict(new{message="Word has no current saved paragraph mapping. Synchronise from Word before requesting navigation."}); var target=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.CanonicalId==sceneId&&s.ChapterId==chapter.ChapterId); var first=target==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==target.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault(); if(first?.PositionVerified!=true)return Conflict(new{message="The scene start is unresolved. Saved scene information remains available."}); var commandId=navigationId??Guid.NewGuid();var position=first.Occurrence.Start;var revision=lease.Position.Revision; if(lease.Position.CanChapterSync&&(state.SessionId!=lease.Session||state.WordRevision!=revision)){ var anchor=chapterPositions==null?null:await chapterPositions.SceneStart(user,bookId,sceneId,first.Occurrence.Id,state.ManuscriptId,lease.Session,revision); if(anchor==null||anchor.Revision!=state.Revision||anchor.SceneID!=sceneId||anchor.ChapterID!=chapter.ChapterId)return Conflict(new{message="This chapter has no current verified Word position. Validate or repair it in Word first; saved scene browsing remains available."});position=anchor.StartPosition; }else{ var verified=await paragraphs.Position(user,bookId,state.ManuscriptId,state.SessionId,state.WordRevision,position); if(verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId)return Conflict(new{message="The saved Word mapping changed. Synchronise before navigating."}); } if(HttpContext.RequestAborted.IsCancellationRequested||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,revision,position,requireSaved:true,navigationId:commandId))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."}); logger.LogInformation("Explicit Context navigation accepted Id={NavigationId} Trace={Trace} User={User} Book={Book} Scene={Scene} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",commandId,HttpContext.TraceIdentifier,user,bookId,sceneId,lease.Instance,lease.Session,revision,position); return Ok(new{navigationId=commandId,message="Navigation requested in Word."}); } private static IReadOnlyList BuildSceneOptions(SceneEditViewModel scene) { var options = scene.SceneOptions .Select(x => new SelectListItem(x.Text, x.Value, x.Value == scene.SceneID.ToString())) .ToList(); if (!options.Any(x => x.Value == scene.SceneID.ToString())) { options.Insert(0, new SelectListItem( $"{scene.Book?.BookDisplayTitle ?? "Book"} / Ch {scene.Chapter?.ChapterNumber:g} / Scene {scene.SceneNumber:g}: {scene.SceneTitle}", scene.SceneID.ToString(), true)); } return options .OrderByDescending(x => x.Selected) .ThenBy(x => x.Text) .ToList(); } private static IReadOnlyList BuildSceneOptions(ChapterWorkflowViewModel? chapterWorkflow) { return chapterWorkflow?.Scenes .Select(x => new SelectListItem( $"Scene {x.SceneNumber:g}: {x.SceneTitle}", x.SceneID.ToString())) .OrderBy(x => x.Text) .ToList() ?? []; } private static WritingContextDisplayViewModel WaitingContextDisplay(int? projectId, int? bookId, Guid? documentGuid) => new() { FollowStatus = "No current Word scene received", EmptyTitle = "No current Word scene received", EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Context") }; private static WritingIntentDisplayViewModel WaitingIntentDisplay(int? projectId, int? bookId, Guid? documentGuid) => new() { FollowStatus = "No current Word scene received", EmptyTitle = "No current Word scene received", EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Intent") }; private static WritingContextDisplayViewModel MissingContextDisplay(int? projectId, int? bookId, int? sceneId) => new() { FollowStatus = "Context unavailable", EmptyTitle = "No Story Intelligence context is available", EmptyMessage = $"PlotDirector could not load context for scene {sceneId?.ToString() ?? "unknown"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}." }; private static WritingIntentDisplayViewModel MissingIntentDisplay(int? projectId, int? bookId, int? chapterId, int? sceneId) => new() { FollowStatus = "Intent unavailable", EmptyTitle = "No writing intent is available", EmptyMessage = $"PlotDirector could not load writing intent for chapter {chapterId?.ToString() ?? "unknown"}, scene {sceneId?.ToString() ?? "none"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}." }; private static string MissingScopeMessage(int? projectId, int? bookId, Guid? documentGuid, string screen) { if (!projectId.HasValue || !bookId.HasValue) { return $"{screen} did not receive a project/book from Word Companion. Reopen it from a linked manuscript, or choose a scene manually."; } return $"Waiting for Word Companion to report the current scene for project {projectId}, book {bookId}{(documentGuid.HasValue ? " and this Word document" : "")}."; } }