using PlotLine.Data; using PlotLine.Models; using PlotLine.ViewModels; namespace PlotLine.Services.Context; public sealed record ContextFamilyEntry(int Key,int FocusID,string Label,IReadOnlyList SceneMembers,bool IsPov); public sealed record ContextFamilyIndex(IReadOnlyList Groups,int? DefaultKey,IReadOnlyList Warnings); public sealed record ContextFamilyBranch(int ID,int Hidden,bool Expanded); public sealed record ContextFamilyTree(int FamilyKey,ContextLensGraph Graph,IReadOnlyList Branches,IReadOnlyList Warnings); public sealed record FamilySemantics(string Kind,int From=0,int To=0,int Generations=0); // Membership is explicit kinship, not co-occurrence, surnames or character knowledge. public sealed class ContextFamilyTopology { public static string Normalise(string value)=>string.Join(' ',value.ToLowerInvariant().Replace('-',' ').Replace('_',' ').Split(' ',StringSplitOptions.RemoveEmptyEntries)); public static FamilySemantics Semantics(CharacterRelationship r) { if(!ContextRelationshipLenses.Family(r.RelationshipCategoryName,r.RelationshipTypeName))return new("ambiguous"); var type=Normalise(r.RelationshipTypeName); var parents=new[]{"parent","mother","father","biological parent","adoptive parent","step parent","grandparent","grandmother","grandfather","great grandparent"}; var children=new[]{"child","son","daughter","biological child","adopted child","adoptive child","step child","stepchild","grandchild","grandson","granddaughter","great grandchild"}; if(parents.Contains(type)||children.Contains(type))return r.IsReciprocal||r.CharacterAID==r.CharacterBID?new("ambiguous"):new("parent",parents.Contains(type)?r.CharacterAID:r.CharacterBID,parents.Contains(type)?r.CharacterBID:r.CharacterAID,type.StartsWith("great ")?3:type.StartsWith("grand")?2:1); if(type is "spouse" or "partner" or "ex spouse" or "former spouse" or "romantic partner")return new("partner"); if(type is "sibling" or "half sibling" or "sister" or "brother")return new("sibling"); if(type is "aunt" or "uncle" or "niece" or "nephew" or "cousin")return new("kinship"); // Guardianship alone does not establish genealogical membership. return new("ambiguous"); } public IReadOnlyList Links {get;} public IReadOnlyList Rejected {get;} readonly Dictionary> neighbours=[]; readonly Dictionary components=[]; public ContextFamilyTopology(IReadOnlyList records) { var roles=records.ToDictionary(r=>r.CharacterRelationshipID,Semantics); var directed=records.Where(r=>roles[r.CharacterRelationshipID].Kind=="parent").GroupBy(r=>roles[r.CharacterRelationshipID].From).ToDictionary(g=>g.Key,g=>g.Select(r=>roles[r.CharacterRelationshipID].To).Distinct().ToList()); // Strong components identify ancestry cycles without labelling their descendants as cycles. var postorder=new List();var visited=new HashSet();var all=records.SelectMany(r=>new[]{r.CharacterAID,r.CharacterBID}).Distinct().Order().ToArray(); foreach(var id in all){var pending=new Stack<(int ID,bool Exit)>();pending.Push((id,false));while(pending.TryPop(out var frame)){if(frame.Exit){postorder.Add(frame.ID);continue;}if(!visited.Add(frame.ID))continue;pending.Push((frame.ID,true));foreach(var child in directed.GetValueOrDefault(frame.ID,[]).OrderDescending())if(!visited.Contains(child))pending.Push((child,false));}} var reverse=directed.SelectMany(pair=>pair.Value.Select(child=>(Parent:pair.Key,Child:child))).GroupBy(e=>e.Child).ToDictionary(g=>g.Key,g=>g.Select(e=>e.Parent).ToList()); int component=0;var scc=new Dictionary();var sizes=new Dictionary(); foreach(var id in postorder.AsEnumerable().Reverse()){if(scc.ContainsKey(id))continue;var pending=new Stack();pending.Push(id);int count=0;while(pending.TryPop(out var n)){if(!scc.TryAdd(n,component))continue;count++;foreach(var parent in reverse.GetValueOrDefault(n,[]))if(!scc.ContainsKey(parent))pending.Push(parent);}sizes[component++]=count;} bool Valid(CharacterRelationship r){var role=roles[r.CharacterRelationshipID];return r.CharacterAID!=r.CharacterBID&&role.Kind!="ambiguous"&&(role.Kind!="parent"||scc[role.From]!=scc[role.To]||sizes[scc[role.From]]==1);} Links=records.Where(Valid).OrderBy(r=>r.CharacterRelationshipID).ToList();Rejected=records.Where(r=>!Valid(r)).ToList(); foreach(var r in Links){if(!neighbours.ContainsKey(r.CharacterAID))neighbours[r.CharacterAID]=[];if(!neighbours.ContainsKey(r.CharacterBID))neighbours[r.CharacterBID]=[];neighbours[r.CharacterAID].Add(r.CharacterBID);neighbours[r.CharacterBID].Add(r.CharacterAID);} foreach(var id in neighbours.Keys.Order()){if(components.ContainsKey(id))continue;var members=new HashSet{id};var todo=new Queue();todo.Enqueue(id);while(todo.TryDequeue(out var n))foreach(var adjacent in neighbours[n])if(members.Add(adjacent))todo.Enqueue(adjacent);var key=members.Min();foreach(var n in members)components[n]=key;} } public int Key(int id)=>components.GetValueOrDefault(id,id); public IReadOnlyList Warnings(IEnumerable people){var set=people.ToHashSet();return Rejected.Any(r=>set.Contains(r.CharacterAID)||set.Contains(r.CharacterBID))?["An ambiguous, unsupported or cyclic family record was excluded from membership and ancestry. Review it in the Relationships Editor."]:[];} public IReadOnlyList Adjacent(int id)=>neighbours.GetValueOrDefault(id,[]).Distinct().Order().ToList(); public (int[] People,int[] Links,IReadOnlyList Branches,bool Truncated) Visible(int focus,IReadOnlyList expanded) { if(expanded.Count>64||expanded.Any(id=>Key(id)!=Key(focus)))throw new ArgumentException("Choose branches within the selected family (maximum 64)."); var near=Adjacent(focus).ToHashSet();var visible=new HashSet{focus};visible.UnionWith(near); var parents=Links.Where(r=>Semantics(r) is {Kind:"parent",Generations:1} s&&s.To==focus).Select(r=>Semantics(r).From).ToHashSet(); // Shared recorded parentage supports siblings; no missing parent or union is inferred. foreach(var r in Links){var role=Semantics(r);if(role.Kind=="parent"&&role.Generations==1&&parents.Contains(role.From))visible.Add(role.To);} var basePeople=visible.ToHashSet();foreach(var r in Links)if(Semantics(r).Kind=="partner"&&(basePeople.Contains(r.CharacterAID)||basePeople.Contains(r.CharacterBID))){visible.Add(r.CharacterAID);visible.Add(r.CharacterBID);} bool changed;do{changed=false;foreach(var id in expanded.Where(visible.Contains))foreach(var other in Adjacent(id))if(visible.Add(other))changed=true;}while(changed); var all=visible.OrderBy(id=>id==focus?0:near.Contains(id)?1:2).ThenBy(id=>id).ToList();var people=all.Take(128).ToArray();var bounded=people.ToHashSet();var edges=Links.Where(r=>bounded.Contains(r.CharacterAID)&&bounded.Contains(r.CharacterBID)).ToList(); var branches=people.Select(id=>new ContextFamilyBranch(id,Adjacent(id).Count(n=>!bounded.Contains(n)),expanded.Contains(id))).Where(b=>b.Hidden>0||b.Expanded).ToList(); return(people,edges.Take(256).Select(r=>r.CharacterRelationshipID).ToArray(),branches,all.Count>128||edges.Count>256); } } public sealed class ContextFamilyExploration(ContextRelationshipLenses lenses,IContextFamilyReader reader,ICharacterRepository characters,ICurrentUserService user) { static int[] Seeds(SceneEditViewModel scene,int? extra=null)=>scene.SceneCharacters.Where(ContextRelationshipLenses.Physical).Select(c=>c.CharacterID).Distinct().Order().Take(32).Concat(scene.POVCharacterID.HasValue?[scene.POVCharacterID.Value]:Array.Empty()).Concat(extra.HasValue?[extra.Value]:Array.Empty()).Distinct().ToArray(); public static ContextFamilyIndex Index(ContextFamilyStructure data,SceneEditViewModel scene) { var topology=new ContextFamilyTopology(data.Links);var seeds=Seeds(scene).ToHashSet();var names=data.Seeds.Where(c=>seeds.Contains(c.CharacterID)).ToDictionary(c=>c.CharacterID); var groups=names.Values.GroupBy(c=>topology.Key(c.CharacterID)).Select(g=>{var ordered=g.OrderByDescending(c=>c.CharacterID==scene.POVCharacterID).ThenBy(c=>c.CharacterName,StringComparer.OrdinalIgnoreCase).ThenBy(c=>c.CharacterID).ToList();return new ContextFamilyEntry(g.Key,ordered[0].CharacterID,string.Join(" & ",ordered.Take(2).Select(c=>c.CharacterName))+(ordered.Count>2?" …":""),ordered.Select(c=>c.CharacterID).ToArray(),ordered.Any(c=>c.CharacterID==scene.POVCharacterID));}).OrderByDescending(g=>g.IsPov).ThenBy(g=>g.Label,StringComparer.OrdinalIgnoreCase).ThenBy(g=>g.Key).ToList(); var warnings=topology.Warnings(seeds).ToList();if(scene.SceneCharacters.Where(ContextRelationshipLenses.Physical).Select(c=>c.CharacterID).Distinct().Count()>32)warnings.Add("The index shows the first 32 physical participants plus the POV. Find another character to explore further families."); return new(groups,groups.FirstOrDefault()?.Key,warnings); } public async Task Index(int book,int scene,CancellationToken cancellationToken){var scope=await lenses.Scope(book,scene);return Index(await reader.Structure(scope.Book.ProjectID,user.UserId!.Value,Seeds(scope.Scene),cancellationToken),scope.Scene);} public async Task Tree(int book,int scene,int focus,IReadOnlyList expanded,CancellationToken cancellationToken) { var scope=await lenses.Scope(book,scene);var author=user.UserId!.Value;if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=scope.Book.ProjectID)throw new UnauthorizedAccessException(); return await ReadProjectTree(scope.Book.ProjectID,author,focus,scope.Scene,scope.CanEdit,expanded,cancellationToken); } public async Task ReadProjectTree(int project,int author,int focus,SceneEditViewModel scene,bool canEdit,IReadOnlyList expanded,CancellationToken cancellationToken) { if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=project)throw new UnauthorizedAccessException(); var structure=await reader.Structure(project,author,Seeds(scene,focus),cancellationToken);var topology=new ContextFamilyTopology(structure.Links);var visible=topology.Visible(focus,expanded);var data=await reader.Tree(project,author,visible.People,visible.Links,cancellationToken); // Re-check the returned records: a concurrent edit must not leave disconnected // physical participants in the chosen tree after an edge changed semantics. var current=new ContextFamilyTopology(data.Relationships);var reachable=new HashSet{focus};var pending=new Queue();pending.Enqueue(focus);while(pending.TryDequeue(out var id))foreach(var adjacent in current.Adjacent(id))if(reachable.Add(adjacent))pending.Enqueue(adjacent); var safe=new RelationshipMapData{Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters.Where(c=>reachable.Contains(c.CharacterID)).ToList(),Relationships=current.Links.Where(r=>reachable.Contains(r.CharacterAID)&&reachable.Contains(r.CharacterBID)).ToList(),RelationshipEvents=data.RelationshipEvents}; var graph=ContextRelationshipLenses.Compose(new(safe,focus,visible.Truncated),"family",scene,canEdit); // Unlike Story, Family contains only the chosen genealogical component, including isolated focus. return new(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)); } }