1use crate::store::HealthStore;
14use crate::webizen::{LANE_BILATERAL, LANE_PASSTHROUGH};
15
16#[derive(Debug)]
18pub struct N3RuleMatch {
19 pub pattern: &'static str,
20 pub confidence: &'static str,
21 pub routing_lane: u8,
22 pub n3_source: &'static str,
24 pub recommended_action: Option<&'static str>,
26}
27
28impl N3RuleMatch {
29 fn to_json(&self) -> String {
30 let action = self
31 .recommended_action
32 .map(|a| format!(",\"recommendedAction\":\"{}\"", a))
33 .unwrap_or_default();
34 format!(
35 "{{\"pattern\":\"{}\",\"confidence\":\"{}\",\"routingLane\":{},\"n3Source\":\"{}\"{}}}",
36 self.pattern, self.confidence, self.routing_lane, self.n3_source, action
37 )
38 }
39}
40
41fn query_avg(store: &HealthStore, sparql: &str) -> Option<f64> {
43 match store.query(sparql) {
44 Ok(json) => {
45 if let Some(start) = json.find("\"value\":\"") {
48 let after = &json[start + 9..];
49 if let Some(end) = after.find('"') {
50 return after[..end].parse::<f64>().ok();
51 }
52 }
53 None
54 }
55 Err(_) => None,
56 }
57}
58
59const HEALTH: &str = "https://health.example.org/ns#";
60const FHIR: &str = "http://hl7.org/fhir/";
61const SNOMED: &str = "http://snomed.info/id/";
62
63const SNOMED_HEART_RATE: &str = "364075005";
65const SNOMED_STEPS: &str = "256235009";
66
67pub fn evaluate_n3_rules(store: &HealthStore) -> Vec<N3RuleMatch> {
70 let mut matches = Vec::new();
71
72 let avg_sleep_eff = query_avg(
76 store,
77 &format!(
78 "SELECT (AVG(?e) AS ?avg) WHERE {{ ?obs <{}sleepEfficiency> ?e }}",
79 HEALTH
80 ),
81 );
82
83 let avg_sleep_hrs = query_avg(
85 store,
86 &format!(
87 "SELECT (AVG(?h) AS ?avg) WHERE {{ ?obs <{}sleepHours> ?h }}",
88 HEALTH
89 ),
90 );
91
92 let avg_hr = query_avg(
94 store,
95 &format!(
96 "SELECT (AVG(?hr) AS ?avg) WHERE {{ \
97 ?obs <{}snomedConcept> <{}{}> ; \
98 <{}Observation.valueQuantity> ?hr \
99 }}",
100 HEALTH, SNOMED, SNOMED_HEART_RATE, FHIR
101 ),
102 );
103
104 let avg_steps = query_avg(
106 store,
107 &format!(
108 "SELECT (AVG(?s) AS ?avg) WHERE {{ \
109 ?obs <{}snomedConcept> <{}{}> ; \
110 <{}Observation.valueQuantity> ?s \
111 }}",
112 HEALTH, SNOMED, SNOMED_STEPS, FHIR
113 ),
114 );
115
116 let avg_stress = query_avg(
118 store,
119 &format!(
120 "SELECT (AVG(?s) AS ?avg) WHERE {{ ?obs <{}stressScore> ?s }}",
121 HEALTH
122 ),
123 );
124 let avg_maslow = query_avg(
125 store,
126 &format!(
127 "SELECT (AVG(?m) AS ?avg) WHERE {{ ?obs <{}maslowSafetyScore> ?m }}",
128 HEALTH
129 ),
130 );
131
132 if let (Some(eff), Some(hrs)) = (avg_sleep_eff, avg_sleep_hrs) {
137 if eff < 70.0 && hrs < 6.0 {
138 matches.push(N3RuleMatch {
139 pattern: "ChronicSleepDebt",
140 confidence: "high",
141 routing_lane: LANE_BILATERAL,
142 n3_source: "sleep_debt.n3",
143 recommended_action: None,
144 });
145 }
146 }
147
148 if let Some(hr) = avg_hr {
152 if hr > 100.0 {
153 matches.push(N3RuleMatch {
154 pattern: "TachycardiaFlag",
155 confidence: "high",
156 routing_lane: LANE_BILATERAL,
157 n3_source: "cardiovascular_risk.n3",
158 recommended_action: None,
159 });
160 }
161
162 if let Some(steps) = avg_steps {
167 if steps < 3000.0 && hr > 80.0 {
168 matches.push(N3RuleMatch {
169 pattern: "DeconditioningRisk",
170 confidence: "moderate",
171 routing_lane: LANE_BILATERAL,
172 n3_source: "cardiovascular_risk.n3",
173 recommended_action: None,
174 });
175 }
176 }
177 }
178
179 if let (Some(hrs), Some(hr)) = (avg_sleep_hrs, avg_hr) {
184 if hrs < 5.0 && hr > 90.0 {
185 matches.push(N3RuleMatch {
186 pattern: "AdrenalFatigueSuspected",
187 confidence: "moderate",
188 routing_lane: LANE_BILATERAL,
189 n3_source: "adrenal_fatigue.n3",
190 recommended_action: None,
191 });
192 }
193 }
194
195 if let (Some(stress), Some(maslow), Some(hrs)) = (avg_stress, avg_maslow, avg_sleep_hrs) {
202 if stress > 75.0 && maslow < 40.0 && hrs < 5.0 {
203 matches.push(N3RuleMatch {
204 pattern: "TraumaCascadeActive",
205 confidence: "high",
206 routing_lane: LANE_BILATERAL,
207 n3_source: "trauma_cascade.n3",
208 recommended_action: Some("urgent-welfare-review"),
209 });
210 }
211 }
212
213 if let (Some(steps), Some(hr)) = (avg_steps, avg_hr) {
218 if steps < 2000.0 && hr > 85.0 {
219 matches.push(N3RuleMatch {
220 pattern: "SystemicFrailty",
221 confidence: "moderate",
222 routing_lane: LANE_BILATERAL,
223 n3_source: "trauma_cascade.n3",
224 recommended_action: None,
225 });
226 }
227 }
228
229 if let Some(steps) = avg_steps {
234 if steps < 5000.0 {
235 matches.push(N3RuleMatch {
236 pattern: "LowActivityFlag",
237 confidence: "low",
238 routing_lane: LANE_PASSTHROUGH,
239 n3_source: "cardiovascular_risk.n3",
240 recommended_action: None,
241 });
242 }
243 }
244
245 matches
246}
247
248pub fn evaluate_n3_rules_turtle(turtle: &str) -> String {
250 let prefixes = crate::rdf::generate_rdf_prefixes();
251 let full = format!("{}\n{}", prefixes, turtle);
252 let mut store = match HealthStore::new() {
253 Ok(s) => s,
254 Err(e) => return format!("{{\"error\":\"{}\"}}", e),
255 };
256 if let Err(e) = store.load_turtle(&full) {
257 return format!("{{\"error\":\"{}\"}}", e);
258 }
259 let results = evaluate_n3_rules(&store);
260 let json_items: Vec<String> = results.iter().map(|r| r.to_json()).collect();
261 format!("[{}]", json_items.join(","))
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use crate::rdf::generate_rdf_prefixes;
268
269 fn store_with(data: &str) -> HealthStore {
270 let prefixes = generate_rdf_prefixes();
271 let full = format!("{}\n{}", prefixes, data);
272 let mut s = HealthStore::new().unwrap();
273 s.load_turtle(&full).unwrap();
274 s
275 }
276
277 #[test]
278 fn test_tachycardia_fires() {
279 let data = format!(
281 "<urn:health:hr:1> a <http://hl7.org/fhir/Observation> ; \
282 <https://health.example.org/ns#snomedConcept> \
283 <http://snomed.info/id/364075005> ; \
284 <http://hl7.org/fhir/Observation.valueQuantity> 110 ."
285 );
286 let store = store_with(&data);
287 let matches = evaluate_n3_rules(&store);
288 assert!(
289 matches.iter().any(|m| m.pattern == "TachycardiaFlag"),
290 "TachycardiaFlag should fire for HR 110"
291 );
292 }
293
294 #[test]
295 fn test_sleep_debt_fires() {
296 let data = format!(
298 "<urn:health:sleep:1> a <http://hl7.org/fhir/Observation> ; \
299 <https://health.example.org/ns#sleepEfficiency> 60 ; \
300 <https://health.example.org/ns#sleepHours> 5.0 ."
301 );
302 let store = store_with(&data);
303 let matches = evaluate_n3_rules(&store);
304 assert!(
305 matches.iter().any(|m| m.pattern == "ChronicSleepDebt"),
306 "ChronicSleepDebt should fire for eff=60, hrs=5.0"
307 );
308 }
309
310 #[test]
311 fn test_normal_data_no_flags() {
312 let data = format!(
314 "<urn:health:hr:ok> a <http://hl7.org/fhir/Observation> ; \
315 <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/364075005> ; \
316 <http://hl7.org/fhir/Observation.valueQuantity> 65 . \
317 <urn:health:sleep:ok> a <http://hl7.org/fhir/Observation> ; \
318 <https://health.example.org/ns#sleepEfficiency> 85 ; \
319 <https://health.example.org/ns#sleepHours> 8.0 . \
320 <urn:health:steps:ok> a <http://hl7.org/fhir/Observation> ; \
321 <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/256235009> ; \
322 <http://hl7.org/fhir/Observation.valueQuantity> 8000 ."
323 );
324 let store = store_with(&data);
325 let matches = evaluate_n3_rules(&store);
326 let critical: Vec<_> = matches.iter().filter(|m| m.routing_lane == 2).collect();
327 assert!(
328 critical.is_empty(),
329 "No BilateralMicroCommons rules should fire for normal data. Got: {:?}",
330 critical.iter().map(|m| m.pattern).collect::<Vec<_>>()
331 );
332 }
333
334 #[test]
335 fn test_adrenal_fatigue_fires() {
336 let data = format!(
338 "<urn:health:sleep:1> a <http://hl7.org/fhir/Observation> ; \
339 <https://health.example.org/ns#sleepHours> 4.5 . \
340 <urn:health:hr:1> a <http://hl7.org/fhir/Observation> ; \
341 <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/364075005> ; \
342 <http://hl7.org/fhir/Observation.valueQuantity> 95 ."
343 );
344 let store = store_with(&data);
345 let matches = evaluate_n3_rules(&store);
346 assert!(
347 matches
348 .iter()
349 .any(|m| m.pattern == "AdrenalFatigueSuspected"),
350 "AdrenalFatigueSuspected should fire for sleep=4.5h, HR=95"
351 );
352 }
353}