using PlotLine.Models.WritingSolver; namespace PlotLine.Services; public static class WritingSolverEngine { public static SolverOutcome Evaluate(SolverGraph graph, IEnumerable history) { var scores = new Dictionary(StringComparer.Ordinal); var accepted = new List(); var next = graph.Nodes.Single(n => n.Id == graph.EntryNode && n.Active); foreach (var answer in history.Take(graph.MaxAnswers)) { if (next is null || answer.Node != next.Id) break; // Discard the stale suffix after revision. var ids = answer.Choices.Distinct(StringComparer.Ordinal).ToArray(); var choices = next.Choices.Where(c => c.Active && ids.Contains(c.Id)).ToArray(); if (ids.Length == 0 || choices.Length != ids.Length || (!next.Multiple && ids.Length != 1) || (choices.Any(c => c.Fallback) && ids.Length != 1)) break; accepted.Add(new(answer.Node, ids)); foreach (var choice in choices) foreach (var weight in choice.Weights) scores[weight.Key] = scores.GetValueOrDefault(weight.Key) + weight.Value; next = SelectNext(graph, next, ids, accepted, scores); } var solutions = graph.Solutions.Where(s => s.Active) .Select(s => new { Solution = s, Score = s.Signals.Sum(w => scores.GetValueOrDefault(w.Key) * w.Value) }) .Where(s => s.Score >= s.Solution.Threshold) .OrderByDescending(s => s.Score).ThenBy(s => s.Solution.Order).ThenBy(s => s.Solution.Id, StringComparer.Ordinal) .Select(s => s.Solution).Take(3).ToArray(); if (accepted.Count >= graph.MaxAnswers || (accepted.Count >= graph.MinAnswers && solutions.Length > 0)) next = null; return new(next, next is null ? solutions : [], scores, accepted); } private static SolverNode? SelectNext(SolverGraph graph, SolverNode current, string[] choices, List answers, Dictionary scores) { var routes = current.Routes.Where(r => (r.Choice is null || choices.Contains(r.Choice)) && (r.Signal is null || scores.GetValueOrDefault(r.Signal) >= r.Minimum)); return routes.Select(r => new { Route = r, Node = graph.Nodes.Single(n => n.Id == r.Target) }) .Where(x => x.Node.Active && !answers.Any(a => a.Node == x.Node.Id)) .OrderByDescending(x => x.Route.Priority + x.Node.Affinity.Sum(w => scores.GetValueOrDefault(w.Key) * w.Value)) .ThenBy(x => x.Node.Order).ThenBy(x => x.Node.Id, StringComparer.Ordinal).Select(x => x.Node).FirstOrDefault(); } }