using System.Text.RegularExpressions; using Flypaper.Storage.Entities; namespace Flypaper.Storage.Explanations; public sealed record Explanation(ExplanationRuleEntity? Target, ExplanationRuleEntity? Client, ExplanationRuleEntity? Outcome) { public bool HasTarget => Target is not null; } public sealed class RuleSet { public static readonly RuleSet Empty = new([]); private readonly IReadOnlyDictionary> _byKind; public RuleSet(IEnumerable rules) { var compiled = new Dictionary>(); foreach (var rule in rules.OrderByDescending(r => r.Priority).ThenBy(r => r.Id)) { Regex regex; try { regex = ExplanationValidator.Compile(rule.Pattern); } catch (Exception exception) when (exception is ArgumentException or NotSupportedException) { continue; } if (!compiled.TryGetValue(rule.Kind, out var list)) { compiled[rule.Kind] = list = []; } list.Add((rule, regex)); } _byKind = compiled.ToDictionary(p => p.Key, p => (IReadOnlyList<(ExplanationRuleEntity, Regex)>)p.Value); } public ExplanationRuleEntity? Winner(ExplanationKind kind, string value) => Matching(kind, value).FirstOrDefault(); public IEnumerable Matching(ExplanationKind kind, string value) { if (!_byKind.TryGetValue(kind, out var rules)) { yield break; } foreach (var (rule, regex) in rules) { if (IsMatch(regex, value)) { yield return rule; } } } public Explanation Explain(TrapEventEntity trapEvent) => new( trapEvent.Target is null ? null : Winner(ExplanationKind.Target, ExplanationText.Value(ExplanationKind.Target, trapEvent)), Winner(ExplanationKind.ClientInfo, ExplanationText.Value(ExplanationKind.ClientInfo, trapEvent)), Winner(ExplanationKind.Outcome, ExplanationText.Value(ExplanationKind.Outcome, trapEvent))); private static bool IsMatch(Regex regex, string value) { try { return regex.IsMatch(value); } catch (RegexMatchTimeoutException) { return false; } } }