using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize] [Route("intelligence-review")] public sealed class IntelligenceReviewController( IOnboardingStoryIntelligenceService onboarding, IOnboardingStoryIntelligenceBatchStore batches, ICurrentUserService user, IStoryIntelligenceExceptionReviewService review, ILogger logger) : Controller { private static bool Supported(string module) => module is "Knowledge" or "Relationships" or "Assets"; [HttpGet("")] public async Task Index(Guid batchId, string module, string scope = "Attention", int page = 1) { if (!Supported(module)) return NotFound(); var frame = await onboarding.GetReviewCentreAsync(batchId); if (frame is null) return NotFound(); if (!frame.CharacterGateSatisfied || !frame.SceneAnalysisComplete || frame.HasActiveRuns) return RedirectToAction("StoryIntelligenceReviewCentre", "Onboarding", new { batchId }); scope = scope is "Attention" or "Optional" or "Tracked" or "Unassessed" or "All" ? scope : "Attention"; var all = (await review.ListAsync(frame.BookID, module)).Select(StoryIntelligenceReviewEntry.From).ToList(); var selected = all.Where(x => scope == "All" || (scope == "Tracked" ? x.Row.DecisionStatus == "AutoAccepted" || (x.Row.DecisionStatus == "Reviewed" && x.Row.DecisionAction != "Ignore") : x.Pending && x.Row.ReviewPriority == scope)).ToList(); var pageCount = Math.Max(1, (int)Math.Ceiling(selected.Count / 25d)); page = Math.Clamp(page, 1, pageCount); var items = selected.Skip((page - 1) * 25).Take(25).ToList(); var pairs = items.Select(x => x.PairKey).ToHashSet(); return View(new StoryIntelligenceExceptionReviewViewModel { BatchID = batchId, BookID = frame.BookID, ProjectID = frame.ProjectID, Module = module, Scope = scope, Page = page, PageCount = pageCount, Summary = frame.ReviewSummaries.FirstOrDefault(x => x.Module == module) ?? new() { Module = module }, Items = items, History = module == "Relationships" ? all.Where(x => pairs.Contains(x.PairKey)).OrderBy(x => x.Observations.FirstOrDefault()?.ChapterNumber) .ThenBy(x => x.Observations.FirstOrDefault()?.SceneNumber).ThenBy(x => x.Observations.FirstOrDefault()?.SortOrder).ToList() : [] }); } [HttpPost("assess")] [ValidateAntiForgeryToken] public async Task Assess(Guid batchId, string module) { if (!Supported(module) || !user.UserId.HasValue) return NotFound(); var frame = await onboarding.GetReviewCentreAsync(batchId); var batch = await batches.GetAsync(user.UserId.Value, batchId); if (frame is null || batch is null) return NotFound(); if (!frame.CharacterGateSatisfied || !frame.SceneAnalysisComplete || frame.HasActiveRuns) return BadRequest("Finish analysis and character identity review before updating priorities."); try { await review.ReassessAsync(batch, module); TempData["ReviewMessage"] = "Priorities updated from saved scene evidence. Supported observations are tracked automatically; your decisions are preserved."; } catch (Exception ex) { logger.LogError(ex, "Review reassessment failed for book {BookID}, module {Module}", batch.BookID, module); TempData["ReviewError"] = "The update could not finish. Completed assessments are saved safely; retry to continue."; } return RedirectToAction(nameof(Index), new { batchId, module }); } }