1use std::collections::BTreeSet;
9
10use flexpool_core::{BusinessDay, EurPerMwh};
11use time::format_description::well_known::Rfc3339;
12use time::{Duration, OffsetDateTime};
13
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[error("line {line}: {message}")]
17pub struct ImportProblem {
18 pub line: usize,
20 pub message: String,
22}
23
24pub fn day_ahead_csv(
29 text: &str,
30 day: &BusinessDay,
31 minutes: u16,
32 limits: (EurPerMwh, EurPerMwh),
33) -> Result<Vec<(OffsetDateTime, EurPerMwh)>, Vec<ImportProblem>> {
34 let mut problems = Vec::new();
35 let mut rows = Vec::new();
36 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
37 let mut lines = text.lines().enumerate();
38 match lines.next() {
39 Some((_, h)) if h.trim() == "start_utc,price_eur_mwh" => {}
40 _ => problems.push(ImportProblem {
41 line: 1,
42 message: "header must be `start_utc,price_eur_mwh`".into(),
43 }),
44 }
45 let step = Duration::minutes(i64::from(minutes));
46 let mut expected = BTreeSet::new();
47 let mut t = day.start();
48 while t < day.end() {
49 expected.insert(t);
50 t += step;
51 }
52 let mut seen = BTreeSet::new();
53 for (i, raw) in lines {
54 let line = i + 1;
55 let raw = raw.trim();
56 if raw.is_empty() {
57 continue;
58 }
59 let Some((start, price)) = raw.split_once(',') else {
60 problems.push(ImportProblem {
61 line,
62 message: format!("expected `start_utc,price_eur_mwh`, got {raw:?}"),
63 });
64 continue;
65 };
66 let start = match OffsetDateTime::parse(start.trim(), &Rfc3339) {
67 Ok(s) => s.to_offset(time::UtcOffset::UTC),
68 Err(_) => {
69 problems.push(ImportProblem {
70 line,
71 message: format!("{start:?} is not an RFC 3339 instant"),
72 });
73 continue;
74 }
75 };
76 let price = match flexpool_core::parse_plain(price.trim()) {
77 Some(p) => EurPerMwh::new(p),
78 None => {
79 problems.push(ImportProblem {
80 line,
81 message: format!("{:?} is not a decimal price", price.trim()),
82 });
83 continue;
84 }
85 };
86 if !expected.contains(&start) {
87 problems.push(ImportProblem {
88 line,
89 message: format!(
90 "{start} is not a {minutes}-minute interval of {}",
91 day.date()
92 ),
93 });
94 } else if !seen.insert(start) {
95 problems.push(ImportProblem {
96 line,
97 message: format!("duplicate interval {start}"),
98 });
99 }
100 if price < limits.0 || price > limits.1 {
101 problems.push(ImportProblem {
102 line,
103 message: format!(
104 "price {price} is outside the limits {} … {} in force",
105 limits.0, limits.1
106 ),
107 });
108 }
109 rows.push((start, price));
110 }
111 for missing in expected.difference(&seen) {
112 problems.push(ImportProblem {
113 line: 0,
114 message: format!("missing interval {missing}"),
115 });
116 }
117 if problems.is_empty() {
118 rows.sort_by_key(|(s, _)| *s);
119 Ok(rows)
120 } else {
121 Err(problems)
122 }
123}