public static class LoincCodeMapper
{
    // LOINC → internal observation code. Covers all codes in DataSeeder + PlausibilityValidator.
    private static readonly Dictionary<string, LoincMapping> _map = new(StringComparer.OrdinalIgnoreCase)
    {
        ["8867-4"]  = new("HEART_RATE", "/min"),
        ["8310-5"]  = new("TEMP_C", "Cel", AllowFahrenheit: true),
        ["2823-3"]  = new("POTASSIUM_MEQ_L", "mmol/L"),
        ["2708-6"]  = new("SPO2", "%"),
        ["9279-1"]  = new("RESP_RATE", "/min"),
        ["6690-2"]  = new("WBC_K_UL", "10*3/uL"),
        ["8480-6"]  = new("SYSTOLIC_BP", "mm[Hg]"),
        ["8462-4"]  = new("DIASTOLIC_BP", "mm[Hg]"),
        ["2524-7"]  = new("LACTATE_MMOL_L", "mmol/L"),
        ["2339-0"]  = new("GLUCOSE_MG_DL", "mg/dL"),
        ["777-3"]   = new("PLATELET_K_UL", "10*3/uL"),
        ["1975-2"]  = new("BILIRUBIN_MG_DL", "mg/dL"),
        ["2160-0"]  = new("CREATININE_MG_DL", "mg/dL"),
        ["2703-7"]  = new("PAO2_MMHG", "mm[Hg]"),
        ["3150-0"]  = new("FIO2_PCT", "%"),
        ["9187-6"]  = new("URINE_OUTPUT_ML_H", "mL/h"),
        // GCS — often sent as panel with components; also map individual LOINC codes used by some EHRs
        ["80288-7"] = new("GCS_EYE", "{score}"),
        ["80289-5"] = new("GCS_VERBAL", "{score}"),
        ["80290-3"] = new("GCS_MOTOR", "{score}"),
    };

    // SNOMED CT fallbacks for non-LOINC sites
    private static readonly Dictionary<string, LoincMapping> _snomedMap = new(StringComparer.OrdinalIgnoreCase)
    {
        ["364075005"] = new("HEART_RATE", "/min"),
        ["431314004"] = new("SPO2", "%"),
        ["86290005"]  = new("RESP_RATE", "/min"),
    };

    public static bool TryMap(string system, string code, out LoincMapping mapping)
    {
        if (system.Contains("loinc", StringComparison.OrdinalIgnoreCase) &&
            _map.TryGetValue(code, out mapping!))
            return true;

        if (system.Contains("snomed", StringComparison.OrdinalIgnoreCase) &&
            _snomedMap.TryGetValue(code, out mapping!))
            return true;

        mapping = null!;
        return false;
    }

    public static IReadOnlyCollection<string> SupportedLoincCodes => _map.Keys;
}