using System.Globalization; using HealthApp.Contracts; namespace HealthApp.Analytics; internal sealed class ClinicalPolicy(ReferenceCatalog catalog) { internal const string GeneralLimits = "General reference thresholds are not individual treatment targets. " + "This is a descriptive assessment, not a diagnosis or medication recommendation. " + "Symptoms, treatment, training, risk factors and measurement technique are not established by these observations."; internal (ClinicalReference? Reference, string Comparison, string Interpretation, string Hint) Apply(string metric, string unit, IReadOnlyList observations, ComparabilityAssessment comparability, (DateTime Time, decimal Value)[] points, string direction, int reversals, decimal mean, Func value) { var reference = SelectReference(metric, observations, comparability); var comparison = "Unavailable: known, non-conflicting resting conditions" + (metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability."; var interpretation = "CannotInterpret"; var hint = "Numerical changes alone do not establish favourable or concerning development."; if (reference is not null) { var above = observations.Count(o => IsHigh(value(o), reference)); var below = observations.Count(o => IsLow(value(o), reference)); comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " + $"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" + (reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") + " This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation; if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability") { var first = points[0].Value; var last = points[^1].Value; if (reversals > 0 && (above > 0 || below > 0)) { interpretation = "Mixed"; hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " + "an overall slope does not establish consistent improvement or deterioration."; } else if (direction == "Decreasing" && IsHigh(first, reference) && !IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference))) { interpretation = "PotentiallyFavourable"; hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " + "This is a cautious inference from the source's reference comparison, not a clinical decision rule. " + (IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." : "Reaching the reference interval does not establish an individual treatment target or good health."); } else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) && !IsHigh(last, reference) && above == 0) { interpretation = "PotentiallyFavourable"; hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " + "but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " + (IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." : "Being within these boundaries does not establish good health."); } else if (above > 0 || below > 0) { interpretation = "PotentiallyConcerning"; hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " + "Limited variation does not establish healthy levels, and a decrease into low resting pulse " + "is not automatically favourable. The cause and individual significance cannot be determined here."; } } else hint = "The recorded context supports this limited reference comparison, but " + (points.Length < 2 ? "temporal direction is unavailable. " : "missing or differing conditions limit interpretation of the combined trajectory. ") + "An outside-reference value is not dismissed because preparation information is incomplete."; } return (reference, comparison, interpretation, hint); } private ClinicalReference? SelectReference(string metric, IReadOnlyList observations, ComparabilityAssessment comparability) { if (comparability.Conflicts.Count > 0 || observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null; if (metric == "Pulse") return catalog.Pulse(); var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray(); if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null; // Known inadequate rest prevents even a provisional resting-pressure comparison. if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null; if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) && !new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase))) return null; return catalog.Pressure(metric, settings[0]!); } private static bool IsHigh(decimal value, ClinicalReference reference) => reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary; private static bool IsLow(decimal value, ClinicalReference reference) => reference.LowerBoundary is { } lower && value < lower; private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero); private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture); }