using System.Text.Json; using Microsoft.Extensions.Caching.Memory; using PlotLine.Data; using PlotLine.Models.Investigations; namespace PlotLine.Services.Investigations; public sealed class GuidanceState { public string? Finding {get;set;}public string? Capability {get;set;} public Dictionary Progress {get;set;}=[]; } public sealed record GuidanceTool(string Id,string Name,string Why,string Action,string Progress,bool Available); public sealed record GuidanceFinding(string Id,string Title,string Explanation,string Action,string Uncertainty,IReadOnlyList Tools); public sealed record GuidanceSummary(Guid ID,int ProjectID,int BookID,string BookTitle,int Version,bool Active,bool Finished,string Concern,string Message,string? Finding,string? Capability,IReadOnlyList Findings); public sealed class InvestigationGuidanceService(IInvestigationGuidanceRepository guidance,IInvestigationRepository investigations,IMemoryCache cache,IConfiguration configuration) { public static readonly string[] ProgressStates=["Not started","Exploring","Done","Skipped"]; public static string Key(string finding,string capability)=>finding+"/"+capability; public static (Investigation Investigation,Evaluation? Evaluation,GuidanceState State) Decode(GuidanceRecord r)=> (JsonSerializer.Deserialize(r.InvestigationJson,CatalogueValidator.Json)!,r.EvaluationJson==null?null:JsonSerializer.Deserialize(r.EvaluationJson,CatalogueValidator.Json),r.GuidanceJson==null?new():JsonSerializer.Deserialize(r.GuidanceJson,CatalogueValidator.Json)??new()); public async Task Catalogue(string version)=>await cache.GetOrCreateAsync("guidance-catalogue:"+version,async entry=>{entry.AbsoluteExpirationRelativeToNow=TimeSpan.FromMinutes(30);return await investigations.Catalogue(version)??throw new KeyNotFoundException();})??throw new KeyNotFoundException(); public static IReadOnlyList Recommended(Investigation i,Evaluation? e)=>i.CurrentQuestion==null&&e?.Outcome!="Investigating"?e?.Recommendations??[]:[]; public bool Available(Capability d,Investigation i)=>configuration.GetValue($"WriterInvestigations:Capabilities:{d.Id}:Enabled",true)&&DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!=null; public GuidanceSummary Summary(GuidanceRecord r,Catalogue c) { var(i,e,s)=Decode(r);var ids=Recommended(i,e); var findings=ids.Select(id=>{ var h=c.Hypotheses.Single(h=>h.Id==id);var authored=c.Editorial?.Results.SingleOrDefault(x=>x.Hypothesis==id); var explanation=authored?.Explanation??h.Reason;var action=authored?.Action??"Use the suggested tool to explore this possibility."; return new GuidanceFinding(id,authored?.Title??h.Summary,explanation,action,h.Uncertainty,c.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)).Select(d=>new GuidanceTool(d.Id,d.Name,d.Description,d.ActionText,s.Progress.GetValueOrDefault(Key(id,d.Id),"Not started"),Available(d,i))).ToArray()); }).ToArray(); var message=e==null?"This older investigation has no saved result. Open the full investigation to continue.":i.CurrentQuestion!=null?"Continue the saved investigation before choosing a tool.":ids.Count==0?"Your saved answers do not yet support a specific tool recommendation. Open the full results to review the uncertainty and next steps.":"These suggestions reflect your questionnaire answers, not verified manuscript analysis."; return new(r.ID,r.ProjectID,r.BookID,r.BookTitle,r.GuidanceVersion,r.IsActive,r.Finished,c.Concerns.SingleOrDefault(x=>x.Id==i.Concern)?.Text??"Saved story concern",message,s.Finding,s.Capability,findings); } public void Select(GuidanceRecord r,Catalogue c,GuidanceState state,string finding,string? capability) { var(i,e,_)=Decode(r);if(!Recommended(i,e).Contains(finding))throw new ArgumentException("This finding is no longer recommended. Open the full results."); if(capability!=null&&!c.Hypotheses.Single(h=>h.Id==finding).Capabilities.Contains(capability))throw new ArgumentException("This tool does not belong to this finding."); state.Finding=finding;state.Capability=capability; } public Task Save(int user,GuidanceRecord r,GuidanceState state,string operation)=>guidance.Save(user,r.BookID,r.ID,r.GuidanceVersion,operation,JsonSerializer.Serialize(state,CatalogueValidator.Json)); public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability,Action? timed=null) { var timer=System.Diagnostics.Stopwatch.StartNew(); var(i,_,s)=Decode(r);Select(r,c,s,finding,capability);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability)??throw new ArgumentException("Tool unavailable."); if(!Available(d,i))throw new ArgumentException("This tool is currently unavailable. Your investigation is retained."); // Opening never completes a step, nor resets an explicit Done/Skipped decision. var key=Key(finding,capability);if(s.Progress.GetValueOrDefault(key,"Not started")=="Not started")s.Progress[key]="Exploring"; timed?.Invoke("eligibility-registry",timer.Elapsed.TotalMilliseconds);timer.Restart(); await Save(user,r,s,"activate");timed?.Invoke("guidance-save",timer.Elapsed.TotalMilliseconds);return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value; } }