using System.Globalization; using System.Text.RegularExpressions; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services; public interface IMapStoryService { Task GetAsync(int projectId, int mapId, int userId, int? scenarioId = null); } public sealed class MapStoryService(IMapStoryRepository repository, IPlotLineWorkspaceRepository plots, IScenarioRepository scenarios, IProjectAccessService access) : IMapStoryService { public async Task GetAsync(int projectId, int mapId, int userId, int? scenarioId = null) { if (!await access.CanAccessProjectAsync(projectId)) return null; var choices = await scenarios.ListAsync(projectId); if (scenarioId.HasValue && !choices.Any(s => s.ScenarioID == scenarioId && !s.IsArchived)) return null; var source = await repository.GetAsync(projectId, mapId, userId); if (source is null) return null; var membership = await plots.GetAsync(projectId, null, scenarioId); // Scenario order is supplied by the same projection which owns Plot Lines membership. if (scenarioId.HasValue) { var order = membership.AttributionScenes.ToDictionary(s => s.SceneID); var titles = source.Scenes.DistinctBy(s => s.BookID).ToDictionary(s => s.BookID, s => s.BookTitle); source.Scenes = source.Scenes.Where(s => order.ContainsKey(s.SceneID)).ToList(); foreach (var scene in source.Scenes) { var entry = order[scene.SceneID]; scene.NarrativeOrder = entry.NarrativeOrder; scene.ChapterID = entry.ChapterID; scene.ChapterNumber = entry.ChapterNumber; scene.ChapterTitle = entry.ChapterTitle; scene.BookID = entry.BookID; scene.BookTitle = titles.GetValueOrDefault(entry.BookID) ?? "Book"; } } var projection = MapStoryComposer.Compose(source, membership, mapId); projection.UserID = userId; projection.ScenarioID = scenarioId; projection.Scenarios = choices.Where(s => !s.IsArchived).ToList(); return projection; } } public static class MapStoryComposer { // Catalogue/Location hierarchy and explicit parent-feature links are the only spatial evidence. public static Func Resolver(MapStoryData data, int mapId) { var locations = data.Locations.ToDictionary(x => x.LocationID); var maps = data.Maps.ToDictionary(x => x.MapID); var current = data.Features.Where(f => f.MapID == mapId).OrderBy(f => f.IsProvisional).ThenBy(f => f.FeatureID).ToList(); var byLocation = data.Features.Where(f => f.LocationID.HasValue && f.IsPlaced).GroupBy(f => f.LocationID!.Value) .ToDictionary(g => g.Key, g => g.OrderBy(f => f.IsProvisional).ThenBy(f => f.MapID).ThenBy(f => f.FeatureID).ToList()); var cache = new Dictionary(); MapStoryLocation Resolve(int? id) { if (!id.HasValue) return new(); if (cache.TryGetValue(id.Value, out var cached)) return cached; var result = new MapStoryLocation { LocationID = id, LocationName = locations.GetValueOrDefault(id.Value)?.LocationName, Status = "Unmapped" }; var chain = new List(); var seen = new HashSet(); int? cursor = id; while (cursor.HasValue && seen.Add(cursor.Value)) { chain.Add(cursor.Value); cursor = locations.GetValueOrDefault(cursor.Value)?.ParentLocationID; } foreach (var locationId in chain) { var match = current.FirstOrDefault(f => f.IsPlaced && f.LocationID == locationId); if (match is not null) { Assign(result, match, locationId == id ? "Exact" : "Ancestor location"); break; } } { foreach (var locationId in chain) { foreach (var candidate in byLocation.GetValueOrDefault(locationId) ?? []) { var pathSeen = new HashSet(); var map = maps.GetValueOrDefault(candidate.MapID); while (map?.ParentMapID is int parent && pathSeen.Add(map.MapID)) { if (parent == mapId) { var anchor = current.FirstOrDefault(f => f.FeatureID == map.ParentFeatureID && f.IsPlaced); if (anchor is not null && !result.FeatureID.HasValue) Assign(result, anchor, "Detail map"); else if (anchor is null && !result.FeatureID.HasValue) result.Status = "On detail map"; result.DetailMapID = candidate.MapID; break; } map = maps.GetValueOrDefault(parent); } if (result.DetailMapID.HasValue) break; } if (result.DetailMapID.HasValue) break; } } if (!result.FeatureID.HasValue && !result.DetailMapID.HasValue) { var map = maps.GetValueOrDefault(mapId); var mapSeen = new HashSet(); while (map?.ParentMapID is int parent && mapSeen.Add(map.MapID)) { if (data.Features.Any(f => f.MapID == parent && f.IsPlaced && chain.Contains(f.LocationID ?? -1))) { result.DetailMapID = parent; result.Status = "On ancestor map"; break; } map = maps.GetValueOrDefault(parent); } } result.FloorPlanID ??= data.FloorPlans.FirstOrDefault(f => chain.Contains(f.LocationID ?? -1))?.FloorPlanID; cache[id.Value] = result; return result; } return Resolve; } private static void Assign(MapStoryLocation result, MapFeature f, string status) { result.FeatureID = f.FeatureID; result.FloorPlanID = f.FloorPlanID; result.Status = status; result.IsProvisional = f.IsProvisional; } public static bool PhysicalAppearance(SceneCharacter appearance) => appearance.RoleInSceneTypeName != "Mentioned Only" && appearance.PresenceTypeName is not ("Mentioned Only" or "Off-screen"); public static int? RecordedAppearanceLocation(SceneCharacter a,int? primaryLocationId) => a.PresenceTypeName == "Unknown" ? null : a.ExitLocationID ?? a.LocationID ?? (a.PresenceTypeName is "Present" or "Arrives" or "Leaves" or "Nearby" or "Hidden" or "Overhearing" ? primaryLocationId : null); private static int? AppearanceLocation(SceneCharacter a,MapStoryScene s)=>RecordedAppearanceLocation(a,s.PrimaryLocationID); public static MapStoryProjection Compose(MapStoryData data, PlotLineWorkspaceData plots, int mapId) { var resolve = Resolver(data, mapId); var scenes = data.Scenes.OrderBy(s => s.NarrativeOrder).ThenBy(s => s.SceneID).ToList(); var byId = scenes.ToDictionary(s => s.SceneID); var memberships = plots.Contributions.GroupBy(c => c.SceneID).ToDictionary(g => g.Key, g => g.Select(c => c.PlotLineID).Distinct().ToList()); var appearances = data.Appearances.Where(a => byId.ContainsKey(a.SceneID)).ToList(); var people = appearances.GroupBy(a => a.SceneID).ToDictionary(g => g.Key, g => g.Select(a => a.CharacterID).Distinct().ToList()); foreach (var scene in scenes) { scene.Position = resolve(scene.PrimaryLocationID); scene.CharacterIDs = people.GetValueOrDefault(scene.SceneID) ?? []; scene.PlotLineIDs = memberships.GetValueOrDefault(scene.SceneID) ?? []; } var result = new MapStoryProjection { MapID = mapId, Scenes = scenes, Characters = data.Characters.OrderByDescending(c => c.CharacterImportance).ThenBy(c => c.CharacterName).Select(c => new MapStoryPerson(c.CharacterID, c.CharacterName, c.CharacterImportance ?? 0)).ToList(), PlotLines = plots.PlotLines.ToList() }; var relationships = data.Relationships.Where(r => r.MapID == mapId).ToLookup(r => (r.SourceID, r.TargetID)); var notes = data.JourneyNotes.Where(n => n.MapID == mapId).ToDictionary(n => (n.CharacterID, n.FromSceneID, n.ToSceneID)); foreach (var group in appearances.Where(PhysicalAppearance).GroupBy(a => a.CharacterID)) { var ordered = group.OrderBy(a => byId[a.SceneID].NarrativeOrder).ThenBy(a => a.SceneCharacterID).DistinctBy(a => a.SceneID).ToList(); MapStoryStop? previous = null; var sequence = 0; foreach (var a in ordered) { var scene = byId[a.SceneID]; var locationId = AppearanceLocation(a, scene); var stop = new MapStoryStop { CharacterID = a.CharacterID, SceneID = a.SceneID, Sequence = ++sequence, Position = resolve(locationId), ObservedAt = a.ExitLocationID.HasValue ? scene.EndDateTime : scene.StartDateTime, TimePrecision = a.ExitLocationID.HasValue && (!scene.EndDateTime.HasValue || scene.EndDateTime < scene.StartDateTime) ? null : scene.TimePrecision, Evidence = locationId.HasValue ? (a.ExitLocationID.HasValue ? "Explicit exit Location" : a.LocationID.HasValue ? "Explicit character Location" : "Scene Location with physical presence") : "Position unknown" }; result.Stops.Add(stop); if (previous is not null) { var leg = new MapStoryLeg { CharacterID = a.CharacterID, FromSceneID = previous.SceneID, ToSceneID = a.SceneID, From = previous.Position, To = stop.Position, Note = notes.GetValueOrDefault((a.CharacterID, previous.SceneID, a.SceneID)) }; // Aggregated ancestors are useful display anchors, not exact endpoints for timing evidence. var exact = leg.From.Status == "Exact" && leg.To.Status == "Exact" && !leg.From.IsProvisional && !leg.To.IsProvisional; var relation = exact ? relationships[(leg.From.FeatureID!.Value, leg.To.FeatureID!.Value)].FirstOrDefault() ?? relationships[(leg.To.FeatureID!.Value, leg.From.FeatureID!.Value)].FirstOrDefault() : null; if (relation is not null) { leg.Direction = relation.SourceID == leg.From.FeatureID ? relation.Direction : Reverse(relation.Direction); leg.RelativeDistance = relation.RelativeDistance; leg.MeasuredDistance = relation.MeasuredDistance; leg.Unit = relation.Unit; leg.TypicalTravelTime = relation.TypicalTravelTime; leg.TypicalMinutes = ParseMinutes(relation.TypicalTravelTime); leg.EvidenceLevel = relation.MeasuredDistance.HasValue ? 2 : 1; } if (leg.Note?.TypicalMinutes is int minutes) leg.TypicalMinutes = minutes; var origin = byId[leg.FromSceneID]; if (exact && leg.From.LocationID != leg.To.LocationID && previous.TimePrecision == "Timestamp" && stop.TimePrecision == "Timestamp" && (origin.EndDateTime is null || origin.EndDateTime >= origin.StartDateTime)) { leg.ElapsedMinutes = (stop.ObservedAt!.Value - previous.ObservedAt!.Value).TotalMinutes; if (leg.TypicalMinutes is > 0 && leg.ElapsedMinutes >= 0) { leg.EvidenceLevel = 3; leg.TimingObservation = leg.ElapsedMinutes < leg.TypicalMinutes; } } result.Legs.Add(leg); } previous = stop; } } return result; } private static string? Reverse(string? d) => d is null ? null : MapValidation.Directions[(Array.IndexOf(MapValidation.Directions, d) + 4) % 8]; // Deliberately constrained duration syntax; vague/descriptive prose remains context, never timing evidence. public static int? ParseMinutes(string? text) { if (string.IsNullOrWhiteSpace(text)) return null; var m = Regex.Match(text.Trim(), @"^(?:(?\d+(?:\.\d+)?)\s*(?:h|hours?|hrs?)\s*)?(?:(?\d+(?:\.\d+)?)\s*(?:m|minutes?|mins?)\s*)?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (!m.Success || (!m.Groups["h"].Success && !m.Groups["m"].Success)) return null; var total = (m.Groups["h"].Success ? double.Parse(m.Groups["h"].Value, CultureInfo.InvariantCulture) * 60 : 0) + (m.Groups["m"].Success ? double.Parse(m.Groups["m"].Value, CultureInfo.InvariantCulture) : 0); return total is > 0 and <= 525600 ? (int)Math.Ceiling(total) : null; } }