wellfare_core/
sleep_analytics.rs1use serde::{Deserialize, Serialize};
6
7pub const DEFAULT_TARGET_SLEEP_MIN: f64 = 480.0;
9
10#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
11pub struct SleepNightSample {
12 pub night_unix: u32,
13 pub duration_min: f64,
14 pub efficiency: Option<f64>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
18pub struct SleepDebtReport {
19 pub target_sleep_min: f64,
20 pub nights_analyzed: u32,
21 pub cumulative_debt_min: f64,
22 pub avg_duration_min: f64,
23 pub avg_efficiency: Option<f64>,
24 pub chronic_sleep_debt_flag: bool,
26 pub formula_note: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
30pub struct SleepHeatmapCell {
31 pub day_label: String,
32 pub night_unix: u32,
33 pub duration_min: f64,
34 pub fill_ratio: f64,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub struct SleepHeatmapReport {
40 pub target_sleep_min: f64,
41 pub cells: Vec<SleepHeatmapCell>,
42}
43
44pub fn compute_sleep_debt(samples: &[SleepNightSample], target_min: f64) -> SleepDebtReport {
46 let n = samples.len();
47 if n == 0 {
48 return SleepDebtReport {
49 target_sleep_min: target_min,
50 nights_analyzed: 0,
51 cumulative_debt_min: 0.0,
52 avg_duration_min: 0.0,
53 avg_efficiency: None,
54 chronic_sleep_debt_flag: false,
55 formula_note:
56 "No sleep nights in journal. Debt = Σ max(0, target − duration) per night.".into(),
57 };
58 }
59
60 let mut debt = 0.0;
61 let mut dur_sum = 0.0;
62 let mut eff_sum = 0.0;
63 let mut eff_count = 0u32;
64 for s in samples {
65 debt += (target_min - s.duration_min).max(0.0);
66 dur_sum += s.duration_min;
67 if let Some(e) = s.efficiency {
68 eff_sum += e;
69 eff_count += 1;
70 }
71 }
72
73 let avg_dur = dur_sum / n as f64;
74 let avg_eff = if eff_count > 0 {
75 Some(eff_sum / eff_count as f64)
76 } else {
77 None
78 };
79 let chronic = avg_eff.map(|e| e < 70.0).unwrap_or(false) && avg_dur < 360.0;
80
81 SleepDebtReport {
82 target_sleep_min: target_min,
83 nights_analyzed: n as u32,
84 cumulative_debt_min: debt,
85 avg_duration_min: avg_dur,
86 avg_efficiency: avg_eff,
87 chronic_sleep_debt_flag: chronic,
88 formula_note: format!(
89 "Debt = Σ max(0, {:.0}min − duration) over {n} night(s). \
90 Chronic flag (non-diagnostic): avg efficiency < 70% AND avg duration < 6h.",
91 target_min
92 ),
93 }
94}
95
96pub fn compute_weekly_heatmap(samples: &[SleepNightSample], target_min: f64) -> SleepHeatmapReport {
98 let take = samples.len().min(7);
99 let slice = if take > 0 {
100 &samples[samples.len() - take..]
101 } else {
102 &[]
103 };
104
105 let cells: Vec<SleepHeatmapCell> = slice
106 .iter()
107 .map(|s| {
108 let fill = (s.duration_min / target_min).clamp(0.0, 1.0);
109 SleepHeatmapCell {
110 day_label: format!("{}", s.night_unix),
111 night_unix: s.night_unix,
112 duration_min: s.duration_min,
113 fill_ratio: fill,
114 }
115 })
116 .collect();
117
118 SleepHeatmapReport {
119 target_sleep_min: target_min,
120 cells,
121 }
122}
123
124pub fn parse_sleep_summary_json(summary: &str) -> Option<(f64, Option<f64>)> {
126 let v: serde_json::Value = serde_json::from_str(summary).ok()?;
127 let dur = v.get("duration_min")?.as_f64()?;
128 let eff = v.get("efficiency").and_then(|x| x.as_f64());
129 Some((dur, eff))
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 #[test]
137 fn debt_accumulates_short_nights() {
138 let samples = vec![
139 SleepNightSample {
140 night_unix: 1,
141 duration_min: 360.0,
142 efficiency: Some(75.0),
143 },
144 SleepNightSample {
145 night_unix: 2,
146 duration_min: 420.0,
147 efficiency: Some(80.0),
148 },
149 ];
150 let report = compute_sleep_debt(&samples, 480.0);
151 assert!((report.cumulative_debt_min - 180.0).abs() < 0.01);
152 assert_eq!(report.nights_analyzed, 2);
153 }
154
155 #[test]
156 fn chronic_flag_requires_low_efficiency_and_duration() {
157 let samples = vec![SleepNightSample {
158 night_unix: 1,
159 duration_min: 300.0,
160 efficiency: Some(65.0),
161 }];
162 let report = compute_sleep_debt(&samples, 480.0);
163 assert!(report.chronic_sleep_debt_flag);
164 }
165
166 #[test]
167 fn heatmap_caps_at_seven() {
168 let samples: Vec<_> = (0..10)
169 .map(|i| SleepNightSample {
170 night_unix: i,
171 duration_min: 400.0 + i as f64,
172 efficiency: None,
173 })
174 .collect();
175 let hm = compute_weekly_heatmap(&samples, 480.0);
176 assert_eq!(hm.cells.len(), 7);
177 assert_eq!(hm.cells[0].night_unix, 3);
178 }
179}