Skip to main content

popo_cli/
models.rs

1use chrono::{DateTime, NaiveDate, Utc};
2use serde::{Deserialize, Serialize};
3
4/// Schema version this build understands. See `docs/feed-schema.md`.
5pub const SCHEMA_VERSION: u32 = 1;
6
7/// A single daily report, as published by the feed.
8///
9/// Counter fields are `Option` because the archive spans ~26 years and older
10/// windows occasionally omit a day entirely. A day that is present with no
11/// activity is `Some(0)`; `None` means "not reported", not "zero".
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
13pub struct VolcanoReport {
14    #[serde(default = "default_schema_version")]
15    pub schema_version: u32,
16
17    pub date: NaiveDate,
18
19    // Seismic activity
20    #[serde(default)]
21    pub exhalations: Option<u32>,
22    #[serde(default)]
23    pub volcanotectonic_events: Option<u32>,
24    #[serde(default)]
25    pub tremor_minutes_total: Option<u32>,
26    #[serde(default)]
27    pub tremor_high_frequency_minutes: Option<u32>,
28    #[serde(default)]
29    pub tremor_harmonic_minutes: Option<u32>,
30    #[serde(default)]
31    pub explosions: Option<u32>,
32
33    // Emissions. Only populated when the measurement is contemporaneous with
34    // `date`; CENAPRED renders one global "last reading" on every page,
35    // including pages for reports years older than the reading itself.
36    #[serde(default)]
37    pub so2_emissions_tons_per_day: Option<f64>,
38    #[serde(default)]
39    pub so2_measurement_date: Option<NaiveDate>,
40
41    // Alert status. Absent on `partial` records: one page embeds a 15-day
42    // window of counters, but the alert describes only that page's own day.
43    #[serde(default)]
44    pub alert_level: Option<AlertLevel>,
45    #[serde(default)]
46    pub alert_phase: Option<String>,
47
48    // Environmental
49    #[serde(default)]
50    pub wind_direction: Option<WindDirection>,
51
52    // Narrative
53    #[serde(default)]
54    pub summary_spanish: Option<String>,
55    #[serde(default)]
56    pub ashfall_reports: Vec<String>,
57
58    // Media
59    #[serde(default)]
60    pub image_urls: Vec<String>,
61    #[serde(default)]
62    pub video_urls: Vec<String>,
63
64    // Provenance
65    #[serde(default)]
66    pub source_url: Option<String>,
67    #[serde(default)]
68    pub ingested_at: Option<DateTime<Utc>>,
69
70    /// True when this record carries counters only, harvested from another
71    /// day's chart window. Report-level detail is absent by design rather than
72    /// missing, and is never copied across from the neighbouring report.
73    #[serde(default)]
74    pub partial: bool,
75}
76
77impl VolcanoReport {
78    /// Whether this record carries report-level detail (alert, narrative,
79    /// wind, media) as opposed to counters alone.
80    pub fn is_full(&self) -> bool {
81        !self.partial
82    }
83}
84
85fn default_schema_version() -> u32 {
86    SCHEMA_VERSION
87}
88
89/// Listing of everything the feed currently carries.
90#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
91pub struct FeedIndex {
92    #[serde(default = "default_schema_version")]
93    pub schema_version: u32,
94    pub updated_at: DateTime<Utc>,
95    pub earliest: NaiveDate,
96    pub latest: NaiveDate,
97    pub count: usize,
98    #[serde(default)]
99    pub dates: Vec<NaiveDate>,
100}
101
102#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
103#[serde(rename_all = "UPPERCASE")]
104pub enum AlertLevel {
105    Green,
106    Yellow,
107    Orange,
108    Red,
109}
110
111impl AlertLevel {
112    pub fn from_spanish(text: &str) -> Option<Self> {
113        let text_lower = text.to_lowercase();
114        if text_lower.contains("verde") {
115            Some(AlertLevel::Green)
116        } else if text_lower.contains("amarillo") {
117            Some(AlertLevel::Yellow)
118        } else if text_lower.contains("naranja") {
119            Some(AlertLevel::Orange)
120        } else if text_lower.contains("rojo") {
121            Some(AlertLevel::Red)
122        } else {
123            None
124        }
125    }
126
127    /// Coloured indicator for terminal output.
128    pub fn emoji(self) -> &'static str {
129        match self {
130            AlertLevel::Green => "🟢",
131            AlertLevel::Yellow => "🟡",
132            AlertLevel::Orange => "🟠",
133            AlertLevel::Red => "🔴",
134        }
135    }
136}
137
138#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
139#[serde(rename_all = "UPPERCASE")]
140pub enum WindDirection {
141    N,
142    NNE,
143    NE,
144    ENE,
145    E,
146    ESE,
147    SE,
148    SSE,
149    S,
150    SSW,
151    SW,
152    WSW,
153    W,
154    WNW,
155    NW,
156    NNW,
157}
158
159impl WindDirection {
160    /// Map CENAPRED's Spanish compass wording onto a 16-point code.
161    ///
162    /// Matching is ordered longest-first: `oestenoroeste` contains `noroeste`,
163    /// so a shortest-first scan silently resolves WNW as NW.
164    pub fn from_spanish(text: &str) -> Option<Self> {
165        let normalized = text.to_lowercase().replace([' ', '-', '_'], "");
166
167        const PATTERNS: &[(&str, WindDirection)] = &[
168            // Three-part (most specific)
169            ("nornoroeste", WindDirection::NNW),
170            ("nortenoroeste", WindDirection::NNW),
171            ("nornoreste", WindDirection::NNE),
172            ("nortenoreste", WindDirection::NNE),
173            ("oestenoroeste", WindDirection::WNW),
174            ("oestesuroeste", WindDirection::WSW),
175            ("estesureste", WindDirection::ESE),
176            ("estenoreste", WindDirection::ENE),
177            ("sursuroeste", WindDirection::SSW),
178            ("sursureste", WindDirection::SSE),
179            // Two-part
180            ("noroeste", WindDirection::NW),
181            ("suroeste", WindDirection::SW),
182            ("sureste", WindDirection::SE),
183            ("noreste", WindDirection::NE),
184            // Cardinal (least specific)
185            ("norte", WindDirection::N),
186            ("oeste", WindDirection::W),
187            ("este", WindDirection::E),
188            ("sur", WindDirection::S),
189        ];
190
191        PATTERNS
192            .iter()
193            .find(|(pattern, _)| normalized.contains(pattern))
194            .map(|(_, dir)| *dir)
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn test_alert_level_from_spanish() {
204        assert_eq!(
205            AlertLevel::from_spanish("Amarillo Fase 2"),
206            Some(AlertLevel::Yellow)
207        );
208        assert_eq!(AlertLevel::from_spanish("VERDE"), Some(AlertLevel::Green));
209        assert_eq!(AlertLevel::from_spanish("rojo"), Some(AlertLevel::Red));
210        assert_eq!(
211            AlertLevel::from_spanish("NARANJA"),
212            Some(AlertLevel::Orange)
213        );
214        assert_eq!(AlertLevel::from_spanish("unknown"), None);
215    }
216
217    #[test]
218    fn test_wind_direction_from_spanish() {
219        assert_eq!(
220            WindDirection::from_spanish("norte-noroeste"),
221            Some(WindDirection::NNW)
222        );
223        assert_eq!(
224            WindDirection::from_spanish("NORESTE"),
225            Some(WindDirection::NE)
226        );
227        assert_eq!(WindDirection::from_spanish("sur"), Some(WindDirection::S));
228        assert_eq!(
229            WindDirection::from_spanish("oeste-suroeste"),
230            Some(WindDirection::WSW)
231        );
232        // Live wording seen on the report page.
233        assert_eq!(
234            WindDirection::from_spanish("Dirección del viento SURESTE"),
235            Some(WindDirection::SE)
236        );
237        assert_eq!(WindDirection::from_spanish("OESTE"), Some(WindDirection::W));
238    }
239
240    /// Compound directions must not be swallowed by their shorter substrings.
241    #[test]
242    fn test_wind_direction_prefers_most_specific() {
243        assert_eq!(
244            WindDirection::from_spanish("oeste noroeste"),
245            Some(WindDirection::WNW)
246        );
247        assert_eq!(
248            WindDirection::from_spanish("sur suroeste"),
249            Some(WindDirection::SSW)
250        );
251        assert_eq!(
252            WindDirection::from_spanish("norte noreste"),
253            Some(WindDirection::NNE)
254        );
255        assert_eq!(
256            WindDirection::from_spanish("este sureste"),
257            Some(WindDirection::ESE)
258        );
259    }
260
261    #[test]
262    fn test_wind_direction_serializes_uppercase() {
263        let json = serde_json::to_string(&WindDirection::NNW).unwrap();
264        assert_eq!(json, "\"NNW\"");
265        let parsed: WindDirection = serde_json::from_str("\"W\"").unwrap();
266        assert_eq!(parsed, WindDirection::W);
267    }
268
269    #[test]
270    fn test_report_deserializes_from_feed_json() {
271        let json = r#"{
272            "schema_version": 1,
273            "date": "2026-08-04",
274            "exhalations": 160,
275            "volcanotectonic_events": 0,
276            "tremor_minutes_total": 0,
277            "tremor_high_frequency_minutes": null,
278            "tremor_harmonic_minutes": null,
279            "explosions": 0,
280            "so2_emissions_tons_per_day": null,
281            "so2_measurement_date": null,
282            "alert_level": "YELLOW",
283            "alert_phase": "AMARILLO FASE 2",
284            "wind_direction": "W",
285            "summary_spanish": "Se detectaron 160 exhalaciones.",
286            "ashfall_reports": ["Atlautla, Estado de México"],
287            "image_urls": [],
288            "video_urls": [],
289            "source_url": "https://www.cenapred.unam.mx/",
290            "ingested_at": "2026-08-05T17:04:00Z",
291            "a_field_from_the_future": 42
292        }"#;
293
294        let report: VolcanoReport = serde_json::from_str(json).unwrap();
295        assert_eq!(report.exhalations, Some(160));
296        assert_eq!(report.explosions, Some(0));
297        assert_eq!(report.alert_level, Some(AlertLevel::Yellow));
298        assert_eq!(report.wind_direction, Some(WindDirection::W));
299        assert_eq!(report.so2_emissions_tons_per_day, None);
300        assert_eq!(report.ashfall_reports, vec!["Atlautla, Estado de México"]);
301        assert!(report.is_full());
302    }
303
304    /// Backfill harvests a 15-day counter window from a single page. The other
305    /// 14 days get counters only; report-level detail is explicitly `null`
306    /// rather than copied across from a neighbouring day.
307    #[test]
308    fn test_partial_record_deserializes() {
309        let json = r#"{
310            "schema_version": 1,
311            "date": "2022-04-13",
312            "exhalations": 22,
313            "volcanotectonic_events": 0,
314            "tremor_minutes_total": 0,
315            "tremor_high_frequency_minutes": null,
316            "tremor_harmonic_minutes": null,
317            "explosions": 0,
318            "so2_emissions_tons_per_day": null,
319            "so2_measurement_date": null,
320            "alert_level": null,
321            "alert_phase": null,
322            "wind_direction": null,
323            "summary_spanish": null,
324            "ashfall_reports": [],
325            "image_urls": [],
326            "video_urls": [],
327            "source_url": "https://www.cenapred.unam.mx/",
328            "ingested_at": "2026-08-06T00:00:00Z",
329            "partial": true
330        }"#;
331
332        let report: VolcanoReport = serde_json::from_str(json).unwrap();
333        assert!(report.partial);
334        assert!(!report.is_full());
335        assert_eq!(report.exhalations, Some(22));
336        assert_eq!(report.alert_level, None);
337        assert_eq!(report.alert_phase, None);
338        assert_eq!(report.summary_spanish, None);
339    }
340
341    /// A missing counter is distinct from a zero counter.
342    #[test]
343    fn test_absent_counter_is_none_not_zero() {
344        let json = r#"{
345            "date": "2001-01-05",
346            "alert_level": "YELLOW",
347            "alert_phase": "AMARILLO FASE 2",
348            "ingested_at": "2026-08-05T17:04:00Z"
349        }"#;
350        let report: VolcanoReport = serde_json::from_str(json).unwrap();
351        assert_eq!(report.exhalations, None);
352        assert_eq!(report.tremor_minutes_total, None);
353        assert!(report.image_urls.is_empty());
354        assert_eq!(report.schema_version, SCHEMA_VERSION);
355        // Absent `partial` means a full report, not a partial one.
356        assert!(report.is_full());
357    }
358}