1use serde::{Deserialize, Serialize};
26
27use crate::record::EpistemicStatus;
28
29use super::accumulate::{
30 Interaction, InteractionKind, accumulate, interactions, systemic_implications,
31};
32use super::factor::{EvidenceTier, Factor};
33use super::systems::body_system;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum Lens {
39 Person,
40 Clinician,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum WellbeingLevel {
47 Settled,
49 WorthWatching,
51 UnderStrain,
53}
54
55impl WellbeingLevel {
56 pub fn from_net(net_milli: u32) -> Self {
58 match net_milli {
59 0..=99 => WellbeingLevel::Settled,
60 100..=299 => WellbeingLevel::WorthWatching,
61 _ => WellbeingLevel::UnderStrain,
62 }
63 }
64}
65
66#[inline]
79pub fn burden_to_sigma(net_milli: u32) -> f32 {
80 const GREEN: f32 = 0.50; const RED: f32 = 0.93; let t = (net_milli.min(1000) as f32) / 1000.0;
83 GREEN + t * (RED - GREEN)
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct SystemView {
89 pub system_id: String,
90 pub system_label: String,
92 pub plain_label: String,
94 pub level: WellbeingLevel,
95 pub net_milli: u32,
96 pub headline: String,
98 pub detail: Vec<String>,
100 pub converging_factors: Vec<String>,
102 pub dominant_evidence: EvidenceTier,
103 pub interactions: Vec<Interaction>,
104 pub epistemic_status: EpistemicStatus,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct AnatomyView {
111 pub lens: Lens,
112 pub systems: Vec<SystemView>,
114 pub summary: String,
116 pub boundary: String,
118 pub uncertainty_note: String,
120}
121
122const PERSON_BOUNDARY: &str = "This is a general picture to help you get a sense of things — it is not medical advice or a diagnosis. If anything here concerns you, it's worth discussing with a clinician.";
123const CLINICIAN_BOUNDARY: &str = "Decision-support considerations only — not a diagnosis, a test order, or a prescription. Surfaced from the person's own records for the clinician's independent evaluation (OSCE-Prac aid).";
124const UNCERTAINTY_NOTE: &str = "Illustrative model, not a measurement. Bodies vary; computed implications are hypotheses to explore, not facts.";
125
126pub fn build_view(factors: &[Factor], lens: Lens, convergence_threshold: usize) -> AnatomyView {
129 let burdens = accumulate(factors);
130 let implications = systemic_implications(factors, convergence_threshold);
131 let all_interactions = interactions(factors);
132
133 let systems = match lens {
134 Lens::Person => person_systems(&burdens, &implications),
135 Lens::Clinician => clinician_systems(&implications, &all_interactions),
136 };
137
138 let summary = match lens {
139 Lens::Person => person_summary(&systems),
140 Lens::Clinician => clinician_summary(&systems, &all_interactions),
141 };
142
143 AnatomyView {
144 lens,
145 systems,
146 summary,
147 boundary: lens_boundary(lens).to_string(),
148 uncertainty_note: UNCERTAINTY_NOTE.to_string(),
149 }
150}
151
152fn lens_boundary(lens: Lens) -> &'static str {
153 match lens {
154 Lens::Person => PERSON_BOUNDARY,
155 Lens::Clinician => CLINICIAN_BOUNDARY,
156 }
157}
158
159fn person_systems(
161 burdens: &[super::accumulate::SystemBurden],
162 implications: &[super::accumulate::SystemicImplication],
163) -> Vec<SystemView> {
164 let mut views: Vec<SystemView> = burdens
165 .iter()
166 .filter(|b| b.net_milli > 0)
167 .map(|b| {
168 let (label, plain) = labels_for(&b.system_id);
169 let level = WellbeingLevel::from_net(b.net_milli);
170 let imp = implications.iter().find(|i| i.system_id == b.system_id);
171 let converging = imp
172 .map(|i| i.converging_factors.clone())
173 .unwrap_or_default();
174 SystemView {
175 headline: person_headline(&plain, level, converging.len()),
176 detail: person_detail(&label, b),
177 system_id: b.system_id.clone(),
178 system_label: label,
179 plain_label: plain,
180 level,
181 net_milli: b.net_milli,
182 converging_factors: converging,
183 dominant_evidence: imp
184 .map(|i| i.dominant_evidence)
185 .unwrap_or(EvidenceTier::CommunityAnecdotal),
186 interactions: imp.map(|i| i.interactions.clone()).unwrap_or_default(),
187 epistemic_status: EpistemicStatus::Hypothesis,
188 }
189 })
190 .collect();
191 views.sort_by(|a, b| {
192 b.net_milli
193 .cmp(&a.net_milli)
194 .then(a.system_id.cmp(&b.system_id))
195 });
196 views
197}
198
199fn clinician_systems(
201 implications: &[super::accumulate::SystemicImplication],
202 _all_interactions: &[Interaction],
203) -> Vec<SystemView> {
204 let mut views: Vec<SystemView> = implications
205 .iter()
206 .map(|i| {
207 let (label, plain) = labels_for(&i.system_id);
208 SystemView {
209 headline: clinician_headline(&label, i),
210 detail: clinician_detail(i),
211 system_id: i.system_id.clone(),
212 system_label: label,
213 plain_label: plain,
214 level: WellbeingLevel::from_net(i.net_milli),
215 net_milli: i.net_milli,
216 converging_factors: i.converging_factors.clone(),
217 dominant_evidence: i.dominant_evidence,
218 interactions: i.interactions.clone(),
219 epistemic_status: i.epistemic_status,
220 }
221 })
222 .collect();
223 views.sort_by(|a, b| {
224 b.net_milli
225 .cmp(&a.net_milli)
226 .then(a.system_id.cmp(&b.system_id))
227 });
228 views
229}
230
231fn labels_for(system_id: &str) -> (String, String) {
232 match body_system(system_id) {
233 Some(s) => (s.label.to_string(), s.plain_label.to_string()),
234 None => (system_id.to_string(), system_id.to_string()),
235 }
236}
237
238fn person_headline(plain: &str, level: WellbeingLevel, converging: usize) -> String {
239 match level {
240 WellbeingLevel::Settled => format!("Your {plain} looks settled."),
241 WellbeingLevel::WorthWatching => {
242 format!("Your {plain} has a little going on — worth being aware of.")
243 }
244 WellbeingLevel::UnderStrain if converging >= 2 => {
245 format!("A few things you've logged seem to be adding up for your {plain}.")
246 }
247 WellbeingLevel::UnderStrain => {
248 format!("Something you've logged is weighing on your {plain}.")
249 }
250 }
251}
252
253fn person_detail(label: &str, b: &super::accumulate::SystemBurden) -> Vec<String> {
254 let mut d = Vec::new();
255 d.push(format!("System: {label}."));
256 if !b.adverse_contributors.is_empty() {
257 d.push(format!(
258 "Contributing: {}.",
259 b.adverse_contributors.join(", ")
260 ));
261 }
262 if !b.supportive_contributors.is_empty() {
263 d.push(format!(
264 "Helping: {}.",
265 b.supportive_contributors.join(", ")
266 ));
267 }
268 d
269}
270
271fn clinician_headline(label: &str, i: &super::accumulate::SystemicImplication) -> String {
272 let n = i.converging_factors.len();
273 let ix = i.interactions.len();
274 let mut h = format!(
275 "{label}: {n} converging factor{} (net load {}, dominant evidence {}).",
276 if n == 1 { "" } else { "s" },
277 i.net_milli,
278 evidence_word(i.dominant_evidence),
279 );
280 if ix > 0 {
281 h.push_str(&format!(
282 " {ix} interaction{} to review.",
283 if ix == 1 { "" } else { "s" }
284 ));
285 }
286 h.push_str(" Consider whether this pattern warrants review.");
287 h
288}
289
290fn clinician_detail(i: &super::accumulate::SystemicImplication) -> Vec<String> {
291 let mut d = Vec::new();
292 d.push(format!(
293 "Converging factors: {}.",
294 i.converging_factors.join(", ")
295 ));
296 for it in &i.interactions {
297 d.push(format!(
298 "{}: {} + {} on this system — {}.",
299 interaction_word(it.kind),
300 it.factor_a,
301 it.factor_b,
302 interaction_note(it.kind),
303 ));
304 }
305 d.push(format!(
306 "Dominant evidence tier: {}.",
307 evidence_word(i.dominant_evidence)
308 ));
309 d.push("Structural considerations only — clinical specifics (tests, medications, referrals) are the clinician's own judgement.".to_string());
310 d
311}
312
313fn person_summary(systems: &[SystemView]) -> String {
314 let strained = systems
315 .iter()
316 .filter(|s| s.level == WellbeingLevel::UnderStrain)
317 .count();
318 match (systems.len(), strained) {
319 (0, _) => "Nothing much is adding up right now from what you've logged.".to_string(),
320 (_, 0) => {
321 "A few small things to be aware of, but nothing is standing out strongly.".to_string()
322 }
323 (_, n) => format!(
324 "A few things seem to be adding up across {n} area{}. It may be worth a chat with a clinician.",
325 if n == 1 { "" } else { "s" }
326 ),
327 }
328}
329
330fn clinician_summary(systems: &[SystemView], all_interactions: &[Interaction]) -> String {
331 let herb_drug = all_interactions
332 .iter()
333 .filter(|i| i.kind == InteractionKind::HerbDrug)
334 .count();
335 let mut s = format!(
336 "{} system{} flagged by convergence.",
337 systems.len(),
338 if systems.len() == 1 { "" } else { "s" }
339 );
340 if herb_drug > 0 {
341 s.push_str(&format!(
342 " {herb_drug} herb–drug interaction{} present.",
343 if herb_drug == 1 { "" } else { "s" }
344 ));
345 }
346 s
347}
348
349fn evidence_word(t: EvidenceTier) -> &'static str {
350 match t {
351 EvidenceTier::CommunityAnecdotal => "community/anecdotal",
352 EvidenceTier::TraditionalUse => "traditional-use",
353 EvidenceTier::NutritionalData => "nutritional-data",
354 EvidenceTier::Mechanistic => "mechanistic",
355 EvidenceTier::ClinicalEvidence => "clinical",
356 }
357}
358
359fn interaction_word(k: InteractionKind) -> &'static str {
360 match k {
361 InteractionKind::HerbDrug => "Herb–drug",
362 InteractionKind::Compounding => "Compounding",
363 InteractionKind::Opposing => "Opposing",
364 }
365}
366
367fn interaction_note(k: InteractionKind) -> &'static str {
368 match k {
369 InteractionKind::HerbDrug => "a medication and a botanical acting on the same system",
370 InteractionKind::Compounding => "two adverse factors on the same system",
371 InteractionKind::Opposing => "an adverse and a supportive factor on the same system",
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378 use crate::anatomy::{Effect, FactorKind};
379
380 #[test]
381 fn burden_sigma_walks_green_to_red_within_the_emf_band() {
382 let settled = burden_to_sigma(0);
383 let strained = burden_to_sigma(1000);
384 assert!((settled - 0.50).abs() < 1e-6, "settled σ={settled}");
386 assert!((strained - 0.93).abs() < 1e-6, "strained σ={strained}");
387 assert!(strained > settled);
389 assert!(burden_to_sigma(150) > settled && burden_to_sigma(150) < strained);
391 assert!(
392 burden_to_sigma(5000) <= 0.93 + 1e-6,
393 "σ clamps at the red end"
394 );
395 assert_eq!(WellbeingLevel::from_net(0), WellbeingLevel::Settled);
397 assert_eq!(WellbeingLevel::from_net(1000), WellbeingLevel::UnderStrain);
398 }
399
400 fn med(id: &str, system: &str, w: u32) -> Factor {
401 Factor::new(id, FactorKind::Medication, id).targeting(
402 system,
403 Effect::Adverse,
404 EvidenceTier::ClinicalEvidence,
405 w,
406 )
407 }
408 fn herb(id: &str, system: &str, effect: Effect, w: u32) -> Factor {
409 Factor::new(id, FactorKind::Herb, id).targeting(
410 system,
411 effect,
412 EvidenceTier::TraditionalUse,
413 w,
414 )
415 }
416
417 #[test]
418 fn person_lens_is_plain_non_diagnostic_and_worst_first() {
419 let factors = vec![
420 med("cond:nafld", "digestive", 500),
421 med("med:hepatotoxic", "digestive", 300),
422 med("med:mild", "urinary", 120),
423 ];
424 let view = build_view(&factors, Lens::Person, 2);
425 assert_eq!(view.lens, Lens::Person);
426 assert_eq!(view.systems[0].system_id, "digestive");
428 assert!(view.systems[0].net_milli > view.systems[1].net_milli);
429 assert_eq!(view.systems[0].plain_label, "digestion");
431 assert!(view.systems[0].headline.contains("digestion"));
432 assert!(!view.systems[0].headline.to_lowercase().contains("diagnos"));
433 assert!(
435 view.systems
436 .iter()
437 .all(|s| s.epistemic_status == EpistemicStatus::Hypothesis)
438 );
439 assert!(view.boundary.contains("not medical advice"));
440 }
441
442 #[test]
443 fn clinician_lens_surfaces_structural_considerations_and_the_herb_drug_interaction() {
444 let factors = vec![
445 med("med:warfarin", "circulatory", 400),
446 herb("herb:ginkgo", "circulatory", Effect::Adverse, 300),
447 ];
448 let view = build_view(&factors, Lens::Clinician, 2);
449 assert_eq!(view.systems.len(), 1);
450 let c = &view.systems[0];
451 assert_eq!(c.system_id, "circulatory");
452 assert_eq!(c.interactions.len(), 1);
453 assert_eq!(c.interactions[0].kind, InteractionKind::HerbDrug);
454 assert!(c.headline.contains("converging factor"));
456 assert!(
457 c.headline
458 .contains("Consider whether this pattern warrants review")
459 );
460 assert_eq!(c.epistemic_status, EpistemicStatus::Hypothesis);
461 assert!(view.boundary.contains("not a diagnosis"));
463 assert!(view.summary.contains("herb–drug"));
464 assert!(
466 c.detail
467 .iter()
468 .any(|d| d.contains("clinician's own judgement"))
469 );
470 }
471
472 #[test]
473 fn person_summary_is_gentle_when_nothing_converges() {
474 let view = build_view(&[], Lens::Person, 2);
475 assert!(view.systems.is_empty());
476 assert!(view.summary.contains("Nothing much is adding up"));
477 }
478
479 #[test]
480 fn view_serde_round_trips() {
481 let view = build_view(&[med("m", "digestive", 400)], Lens::Person, 1);
482 let json = serde_json::to_string(&view).unwrap();
483 let back: AnatomyView = serde_json::from_str(&json).unwrap();
484 assert_eq!(view, back);
485 }
486}