using System.Data; using System.Text.Json; using Dapper; using PlotLine.Models; using PlotLine.Services; namespace PlotLine.Data; public sealed record ContextFamilyStructure(IReadOnlyList Seeds,IReadOnlyList Links); public interface IContextFamilyReader { Task Structure(int project,int user,IReadOnlyList seeds,CancellationToken cancellationToken); Task Tree(int project,int user,IReadOnlyList people,IReadOnlyList links,CancellationToken cancellationToken); } public sealed class ContextFamilyReader(ISqlConnectionFactory connections,IConfiguration configuration):IContextFamilyReader { public async Task Structure(int project,int user,IReadOnlyList seeds,CancellationToken cancellationToken) { using var db=connections.CreateConnection();using var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Structure",new{ProjectID=project,UserID=user,Seeds=JsonSerializer.Serialize(seeds)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken)); var names=(await rows.ReadAsync()).ToList();var links=(await rows.ReadAsync()).ToList(); if(links.Count>8192)throw new ArgumentException("Family membership exceeds the Context limit. Use the full Relationships Editor."); return new(names,links); } public async Task Tree(int project,int user,IReadOnlyList people,IReadOnlyList links,CancellationToken cancellationToken) { using var db=connections.CreateConnection();RelationshipMapData data; using(var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Tree",new{ProjectID=project,UserID=user,CharacterIDs=JsonSerializer.Serialize(people),RelationshipIDs=JsonSerializer.Serialize(links)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))) data=new(){Books=(await rows.ReadAsync()).ToList(),Chapters=(await rows.ReadAsync()).ToList(),Scenes=(await rows.ReadAsync()).ToList(),Characters=(await rows.ReadAsync()).ToList(),Relationships=(await rows.ReadAsync()).ToList()}; if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Narrative ordering exceeds the Context limit. Use the full Relationships Editor."); var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList(); var changes=(await db.QueryAsync(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=order.Count-1},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList(); await ParagraphEvidenceProjection.Apply(db,configuration,changes);return new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters,Relationships=data.Relationships,RelationshipEvents=changes}; } }