using PlotLine.Data; using PlotLine.Models; using PlotLine.ViewModels; namespace PlotLine.Services; public interface IPlotLineWorkspaceService { Task GetAsync(int projectId, int? bookId, IEnumerable? plotLineIds, IEnumerable? threadIds, int? scenarioId, bool showSuggestions, bool unattributed); Task GetInspectorAsync(int projectId, int? bookId, int sceneId, int? scenarioId); Task GetManuscriptAsync(int projectId, int? bookId, int sceneId); } public sealed class PlotLineWorkspaceService( IPlotLineWorkspaceRepository workspace, IProjectRepository projects, IBookRepository books, IScenarioRepository scenarios, IStoryContextService storyContext, IManuscriptTextStatisticsRepository manuscriptSources, IPlotHealthEvaluator health) : IPlotLineWorkspaceService { public async Task GetAsync( int projectId, int? bookId, IEnumerable? plotLineIds, IEnumerable? threadIds, int? scenarioId, bool showSuggestions, bool unattributed) { var project = await projects.GetAsync(projectId); if (project is null) { return null; } var projectBooks = (await books.ListByProjectAsync(projectId)).Where(x => !x.IsArchived).ToList(); if (bookId.HasValue && projectBooks.All(x => x.BookID != bookId.Value)) { return null; } var projectScenarios = (await scenarios.ListAsync(projectId)).Where(x => !x.IsArchived).ToList(); var selectedScenario = scenarioId.HasValue ? projectScenarios.FirstOrDefault(x => x.ScenarioID == scenarioId.Value && (!bookId.HasValue || !x.BookID.HasValue || x.BookID == bookId)) : null; if (scenarioId.HasValue && selectedScenario is null) { return null; } var data = await workspace.GetAsync(projectId, bookId, selectedScenario?.ScenarioID); foreach (var line in data.PlotLines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour); var availableIds = data.PlotLines.Select(x => x.PlotLineID).ToHashSet(); var selectedLineIds = (plotLineIds ?? []).Where(availableIds.Contains).Distinct().ToList(); if (!unattributed && selectedLineIds.Count == 0 && data.PlotLines.Count > 0) { selectedLineIds.Add(data.PlotLines.OrderByDescending(x => x.ContributionSceneCount).ThenBy(x => x.SortOrder).First().PlotLineID); } // Reference data identifies scenario omissions and targets outside the chosen book; its positions are never used for health. var referenceData = !unattributed && (bookId.HasValue || selectedScenario is not null) ? await workspace.GetAsync(projectId, null, null) : data; var healthResult = unattributed ? PlotHealthResult.Empty : health.Evaluate(new PlotHealthContext( projectId, bookId ?? selectedScenario?.BookID, selectedScenario?.ScenarioID, selectedLineIds, data, referenceData)); var selectedThreads = (threadIds ?? []).Where(id => data.Threads.Any(x => x.PlotThreadID == id && selectedLineIds.Contains(x.PlotLineID))).Distinct().ToList(); var composedScenes = unattributed ? [] : PlotLineWorkspaceComposer.Compose(data, selectedLineIds, selectedThreads); var suggestionsByScene = showSuggestions ? data.Suggestions.GroupBy(x => x.SceneID).ToDictionary(x => x.Key, x => (IReadOnlyList)x .GroupBy(y => new { y.NarrativeCandidateID, y.ContributionType, y.Evidence }) .Select(y => y.First()).ToList()) : []; return new PlotLineWorkspaceViewModel { Project = project, SelectedBookID = bookId, SelectedScenarioID = selectedScenario?.ScenarioID, SelectedScenarioName = selectedScenario?.ScenarioName, Mode = unattributed ? "Unattributed" : selectedLineIds.Count > 1 ? "Weave" : "Focus", ShowSuggestions = showSuggestions, Books = projectBooks, Scenarios = projectScenarios.Where(x => !bookId.HasValue || !x.BookID.HasValue || x.BookID == bookId).ToList(), PlotLines = data.PlotLines.Select(line => new PlotLineWorkspaceLineViewModel { Line = line, IsSelected = selectedLineIds.Contains(line.PlotLineID), Threads = data.Threads.Where(x => x.PlotLineID == line.PlotLineID).ToList() }).ToList(), SelectedPlotLineIDs = selectedLineIds, SelectedThreadIDs = selectedThreads, Scenes = composedScenes, Health = healthResult, AssociatedSelectedSceneIDs = data.Contributions.Where(x => selectedLineIds.Contains(x.PlotLineID)).Select(x => x.SceneID).ToHashSet(), AssociationScenes = data.AttributionScenes.OrderBy(x => x.NarrativeOrder).ToList(), MapTargets = data.Targets, SuggestedScenes = showSuggestions ? data.AttributionScenes.Where(x => suggestionsByScene.ContainsKey(x.SceneID)).Select(x => new PlotLineWorkspaceSuggestionSceneViewModel { Scene = x, Suggestions = suggestionsByScene[x.SceneID] }).ToList() : [], ProposedOnlyScenes = unattributed ? data.AttributionScenes.Where(x => x.CanonicalPlotLineCount == 0 && x.ProposedCandidateCount > 0).ToList() : [], NoKnownAttributionScenes = unattributed ? data.AttributionScenes.Where(x => x.CanonicalPlotLineCount == 0 && x.ProposedCandidateCount == 0).ToList() : [] }; } public async Task GetInspectorAsync(int projectId, int? bookId, int sceneId, int? scenarioId) { var context = await storyContext.GetForSceneAsync(sceneId, projectId, bookId); if (context?.Scene is null) { return null; } var data = await workspace.GetAsync(projectId, bookId, scenarioId); foreach (var line in data.PlotLines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour); if (data.AttributionScenes.All(x => x.SceneID != sceneId)) { return null; } var memberships = PlotLineWorkspaceComposer.ComposeMemberships(data, data.Contributions.Where(x => x.SceneID == sceneId)); var sceneEventIds = memberships.SelectMany(x => x.Contributions).Select(x => x.ThreadEventID).ToHashSet(); var lineNames = data.PlotLines.ToDictionary(x => x.PlotLineID, x => x.PlotLineName); return new PlotLineWorkspaceInspectorViewModel { ProjectID = projectId, BookID = bookId, Scene = context.Scene, Memberships = memberships, Threads = data.Threads.Where(x => memberships.Any(m => m.Contributions.Any(c => c.PlotThreadID == x.PlotThreadID))).ToList(), Dependencies = data.Dependencies.Where(x => x.SourceSceneID == sceneId || x.TargetSceneID == sceneId).ToList(), Targets = data.Targets.Where(x => sceneEventIds.Contains(x.ThreadEventID)).Select(x => new PlotLineWorkspaceTargetViewModel { SourcePlotLineName = lineNames.GetValueOrDefault(x.SourcePlotLineID, "Plot line"), TargetPlotLineName = lineNames.GetValueOrDefault(x.TargetPlotLineID, "Plot line"), StructuralType = x.StructuralType }).ToList(), Suggestions = data.Suggestions.Where(x => x.SceneID == sceneId) .GroupBy(x => new { x.NarrativeCandidateID, x.ContributionType, x.Evidence }).Select(x => x.First()).ToList() }; } public async Task GetManuscriptAsync(int projectId, int? bookId, int sceneId) { var source = await manuscriptSources.GetSourceBySceneAsync(sceneId); if (source is null || source.ProjectID != projectId || (bookId.HasValue && source.BookID != bookId.Value)) { return null; } return new PlotLineWorkspaceManuscriptViewModel { SceneID = sceneId, SceneTitle = string.IsNullOrWhiteSpace(source.SceneTitle) ? $"Scene {source.SceneNumber:0.##}" : source.SceneTitle, SourceText = source.SourceText, SourceWordCount = source.SourceWordCount }; } } public static class PlotLineWorkspaceComposer { public static IReadOnlyList Compose( PlotLineWorkspaceData data, IReadOnlyCollection selectedLineIds, IReadOnlyCollection? selectedThreadIds = null) { var selectedThreads = selectedThreadIds?.ToHashSet() ?? []; var contributions = data.Contributions .Where(x => selectedLineIds.Contains(x.PlotLineID) && (selectedThreads.Count == 0 || selectedThreads.Contains(x.PlotThreadID))) .GroupBy(x => x.SceneID) .Select(x => x.OrderBy(y => y.NarrativeOrder).ThenBy(y => y.ThreadEventID).ToList()) .OrderBy(x => x[0].NarrativeOrder) .ToList(); var scenes = new List(); PlotLineWorkspaceContributionRow? previous = null; foreach (var sceneContributions in contributions) { var first = sceneContributions[0]; scenes.Add(new PlotLineWorkspaceSceneViewModel { SceneID = first.SceneID, NarrativeOrder = first.NarrativeOrder, GapBefore = previous is null ? 0 : Math.Max(0, first.NarrativeOrder - previous.NarrativeOrder - 1), ChapterGapBefore = previous is null ? 0 : Math.Max(0, (int)Math.Floor(first.ChapterNumber) - (int)Math.Floor(previous.ChapterNumber) - 1), ChapterNumber = first.ChapterNumber, ChapterTitle = first.ChapterTitle, SceneNumber = first.SceneNumber, SceneTitle = first.SceneTitle, Summary = first.SceneSummary, PovCharacterName = first.PovCharacterName, LocationName = first.LocationName, TimeLabel = first.StartDateTime?.ToString("g") ?? first.RelativeTimeText, WarningCount = first.WarningCount, DependencyCount = first.DependencyCount, HasManuscript = first.HasManuscript, StructuralTargetCount = data.Targets.Count(x => sceneContributions.Any(c => c.ThreadEventID == x.ThreadEventID)), Memberships = ComposeMemberships(data, sceneContributions), Connections = data.Dependencies.Where(x => x.SourceSceneID == first.SceneID || x.TargetSceneID == first.SceneID).ToList() }); previous = first; } return scenes; } public static IReadOnlyList ComposeMemberships( PlotLineWorkspaceData data, IEnumerable contributions) { var lineLookup = data.PlotLines.ToDictionary(x => x.PlotLineID); return contributions.GroupBy(x => x.PlotLineID).Select(group => { lineLookup.TryGetValue(group.Key, out var line); return new PlotLineWorkspaceSceneMembershipViewModel { PlotLineID = group.Key, PlotLineName = line?.PlotLineName ?? "Plot line", Colour = line?.Colour ?? "#2f6f63", Contributions = group.OrderByDescending(x => x.ThreadImportance).ThenBy(x => x.ThreadTitle).ThenBy(x => x.ThreadEventID).ToList() }; }).OrderBy(x => lineLookup.TryGetValue(x.PlotLineID, out var line) ? line.SortOrder : int.MaxValue).ToList(); } }