using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Mvc.Rendering; using PlotLine.Data; using PlotLine.Models; using PlotLine.ViewModels; namespace PlotLine.Services.Context; public sealed class ContextRelationshipForm { public int BookID{get;set;}public int SceneID{get;set;}public int RelationshipID{get;set;}public string Mode{get;set;}="scene";public string Fingerprint{get;set;}="";public string ReferenceLens{get;set;}="story"; public int SourceID{get;set;}public int TargetID{get;set;}public int TypeID{get;set;}public int StateID{get;set;} [Range(1,10)]public int? Intensity{get;set;}public bool Mutual{get;set;}public bool Known{get;set;}[StringLength(4000)]public string? Notes{get;set;} public string Label{get;set;}="";public IReadOnlyList Characters{get;set;}=[];public IReadOnlyList Types{get;set;}=[];public IReadOnlyList States{get;set;}=[]; } // Focused adapter over existing canonical initial-relationship and event operations. public sealed class ContextRelationshipEditing(ICharacterRepository repository,ICharacterService characters,IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,ContextWorkspaceNotifications notifications) { private static readonly SemaphoreSlim[] Locks=Enumerable.Range(0,64).Select(_=>new SemaphoreSlim(1,1)).ToArray(); private sealed record Frame(ContextRelationshipForm Form,RelationshipMapData Data,CharacterRelationship? Relationship,RelationshipEvent? Event,CharacterLookupData Lookups,int ProjectID); public async Task Read(int bookId,int sceneId,int relationshipId,string mode,string referenceLens="story")=>(await Load(bookId,sceneId,relationshipId,mode,referenceLens)).Form; private async Task Load(int bookId,int sceneId,int relationshipId,string mode,string referenceLens) { if(referenceLens is not ("family" or "story"))throw new ArgumentException("Choose a supported reference lens."); var author=user.UserId??throw new UnauthorizedAccessException();var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException(); if(!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException(); var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();if(!ContextEditPolicy.CanEdit(await projects.GetForUserAsync(book.ProjectID,author)))throw new UnauthorizedAccessException(); if(mode is not ("initial" or "scene"))throw new ArgumentException("Choose initial state or a scene development."); var data=await repository.GetRelationshipMapAsync(book.ProjectID);var lookups=await repository.GetLookupsAsync(book.ProjectID); var relation=relationshipId>0?data.Relationships.SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId&&!r.IsArchived):null; if(relationshipId>0&&(relation==null||relation.ProjectID!=book.ProjectID))throw new UnauthorizedAccessException(); if(referenceLens=="family"&&relation!=null&&!ContextRelationshipLenses.Family(relation.RelationshipCategoryName,relation.RelationshipTypeName))throw new ArgumentException("Choose an established family connection."); if(mode=="initial"&&relation!=null&&!relation.IsInitialRelationship)throw new ArgumentException("This relationship starts in a scene. Correct its development rather than adding an earlier initial state."); var events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId&&e.SceneID==sceneId).ToList(); if(mode=="scene"&&(events.Count>1||events.Any(e=>e.EvidenceState!="Verified")))throw new ArgumentException("Review multiple or unverified scene events in the full Relationships Editor before correcting this relationship."); var change=mode=="scene"?events.SingleOrDefault():null; var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i); var projected=RelationshipMapService.BuildAtScene(data,order,sceneId).SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId); if(relation!=null&&projected==null&&!(referenceLens=="family"&&mode=="initial"))throw new ArgumentException("This relationship is not established at the selected story point."); var state=mode=="initial"?relation?.InitialRelationshipStateID:change?.RelationshipStateID??lookups.RelationshipStates.FirstOrDefault(s=>s.StateName==projected?.CurrentStateName)?.RelationshipStateID; var form=new ContextRelationshipForm{BookID=bookId,SceneID=sceneId,RelationshipID=relationshipId,Mode=mode,ReferenceLens=referenceLens,SourceID=relation?.CharacterAID??0,TargetID=relation?.CharacterBID??0,TypeID=relation?.RelationshipTypeID??0,StateID=state??0, Intensity=mode=="initial"?relation?.InitialIntensity:change?.Intensity??projected?.CurrentIntensity,Mutual=relation?.IsReciprocal??false,Known=mode=="initial"?relation?.ReaderInitiallyKnows??false:change?.IsKnownToOtherCharacter??false, Notes=mode=="initial"?relation?.Notes:change?.Description,Label=mode=="initial"?(referenceLens=="family"?"Author-established initial family connection":"Initial relationship (before scene developments)"):"Relationship development at "+(data.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.SceneTitle??"the selected scene"), Characters=data.Characters.Where(c=>!c.IsArchived).OrderBy(c=>c.CharacterName).Select(c=>new SelectListItem(c.CharacterName,c.CharacterID.ToString())).ToList(), Types=lookups.RelationshipTypes.Where(t=>(t.IsActive||t.RelationshipTypeID==relation?.RelationshipTypeID)&&(referenceLens!="family"||ContextRelationshipLenses.Family(t.RelationshipCategoryName,t.TypeName))).Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToList(), States=lookups.RelationshipStates.Where(s=>s.IsActive||s.RelationshipStateID==state).Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToList()}; form.Fingerprint=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new{relation,Events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId).ToList(),Matches=data.Relationships.Select(r=>new{r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeID,r.IsReciprocal,r.IsArchived})})))); return new(form,data,relation,change,lookups,book.ProjectID); } public async Task Save(ContextRelationshipForm input) { var mutex=Locks[(input.BookID&int.MaxValue)%Locks.Length];await mutex.WaitAsync();try{ var frame=await Load(input.BookID,input.SceneID,input.RelationshipID,input.Mode,input.ReferenceLens);var f=frame.Form;var r=frame.Relationship; if(f.Fingerprint!=input.Fingerprint)throw new InvalidOperationException("Relationships changed in another window. Your draft is retained; cancel and reopen current values."); if(input.SourceID==input.TargetID||!f.Characters.Any(c=>c.Value==input.SourceID.ToString())||!f.Characters.Any(c=>c.Value==input.TargetID.ToString())||!f.Types.Any(t=>t.Value==input.TypeID.ToString())||!f.States.Any(s=>s.Value==input.StateID.ToString()))throw new ArgumentException("Choose two different project characters and a recorded relationship type and state."); if(input.Intensity is <1 or >10||input.Notes?.Length>4000)throw new ArgumentException("Intensity must be 1–10 and notes at most 4,000 characters."); if(r!=null&&(r.CharacterAID!=input.SourceID||r.CharacterBID!=input.TargetID||r.RelationshipTypeID!=input.TypeID||r.IsReciprocal!=input.Mutual))throw new ArgumentException("Use the full Relationships Editor to change the pair, type or direction of an existing relationship."); if(r==null&&frame.Data.Relationships.Any(x=>!x.IsArchived&&x.RelationshipTypeID==input.TypeID&&((x.CharacterAID==input.SourceID&&x.CharacterBID==input.TargetID)||(x.IsReciprocal&&x.CharacterAID==input.TargetID&&x.CharacterBID==input.SourceID))))throw new ArgumentException("This relationship already exists. Correct its recorded state or use the full editor."); if(input.Mode=="initial")await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes}); else{ var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID}; if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit); } await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID,kind:"relationships"); }finally{mutex.Release();} } }