cobre-io 0.12.0

Case directory loading and validation for the Cobre power systems ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
//! Parsing for `initial_conditions.json` — initial system state.
//!
//! [`parse_initial_conditions`] reads `initial_conditions.json` from the case
//! directory root and returns a fully-validated [`InitialConditions`].
//!
//! ## JSON structure
//!
//! The file contains two required top-level arrays and three optional arrays:
//!
//! - `storage` — initial reservoir volumes for operating hydros (hm³).
//! - `filling_storage` — initial reservoir volumes for filling hydros (hm³).
//! - `past_inflows` — past inflow values for PAR(p) lag initialization (m³/s),
//!   ordered from most recent (lag 1) to oldest (lag p). Optional; defaults to
//!   an empty array when absent.
//! - `recent_observations` — observed inflow data for partial periods before
//!   the study start (m³/s per date range per hydro). Optional; defaults to an
//!   empty array when absent.
//! - `past_anticipated_commitments` — committed MW values for each anticipated
//!   thermal plant, ordered by delivery stage ascending. Optional; defaults to
//!   an empty array when no anticipated thermals are present.
//! - `past_defluences` — past release windows per arc (m³/s per date range),
//!   keyed by the upstream hydro whose release feeds the arc. Each entry is a
//!   self-describing `[start_date, end_date)` window on the pre-study calendar,
//!   mirroring `recent_observations`. Optional; defaults to an empty array when
//!   absent.
//!
//! ```json
//! {
//!   "$schema": "https://raw.githubusercontent.com/cobre-rs/cobre/refs/heads/main/schemas/initial_conditions.schema.json",
//!   "storage": [
//!     { "hydro_id": 0, "value_hm3": 15000.0 },
//!     { "hydro_id": 1, "value_hm3": 8500.0 }
//!   ],
//!   "filling_storage": [{ "hydro_id": 10, "value_hm3": 200.0 }],
//!   "past_inflows": [
//!     { "hydro_id": 0, "values_m3s": [600.0, 500.0] },
//!     { "hydro_id": 1, "values_m3s": [200.0, 100.0] }
//!   ],
//!   "recent_observations": [
//!     { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 },
//!     { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 }
//!   ],
//!   "past_anticipated_commitments": [
//!     { "thermal_id": 1, "values_mw": [0.0, 0.0] }
//!   ]
//! }
//! ```
//!
//! ## Validation
//!
//! After deserializing, the following invariants are checked before conversion:
//!
//! 1. Every `value_hm3` is non-negative (`>= 0.0`).
//! 2. No `hydro_id` appears more than once within `storage` or within
//!    `filling_storage` (no intra-array duplicates).
//! 3. No `hydro_id` appears in both `storage` and `filling_storage`
//!    (mutual exclusion).
//! 4. No `hydro_id` appears more than once in `past_inflows`.
//! 5. Every value in `past_inflows[i].values_m3s` is finite and non-negative.
//! 6. Every `start_date` and `end_date` in `recent_observations` parses as
//!    ISO 8601 (`YYYY-MM-DD`), and `end_date > start_date`.
//! 7. Every `value_m3s` in `recent_observations` is finite and non-negative.
//! 8. For observations with the same `hydro_id`, date ranges do not overlap
//!    (adjacent ranges where `start == prev_end` are accepted).
//! 9. No `thermal_id` appears more than once in `past_anticipated_commitments`.
//! 10. Every `past_anticipated_commitments[i].values_mw` is non-empty.
//! 11. Every value in `past_anticipated_commitments[i].values_mw` is finite and
//!     non-negative (`>= 0.0`) (parse-time check).
//! 12. `past_anticipated_commitments[i].values_mw.len()` equals the
//!     calendar-derived count of pre-study-committed delivery stages for that
//!     thermal's lead mode — not `lead_stages` on a non-uniform calendar — and
//!     every value lies within the plant's `[min_generation_mw, max_generation_mw]`
//!     bounds and, if the plant has a commissioning window, matures inside it.
//!     All three are enforced by the semantic validator (Layer 5a); the committed
//!     values are sunk cost and do not enter the study objective. See
//!     [`AnticipatedCommitmentHistory`] in `cobre-core` for the full contract.
//! 13. Every `start_date` and `end_date` in `past_defluences` parses as ISO 8601
//!     (`YYYY-MM-DD`), and `end_date > start_date`.
//! 14. Every `value_m3s` in `past_defluences` is finite and non-negative.
//! 15. For defluence windows with the same `hydro_id`, date ranges do not overlap
//!     (adjacent ranges where `start == prev_end` are accepted).
//!
//! Cross-reference validation (checking that hydro IDs exist in the hydro
//! registry) is deferred to Layer 3 (deferred). Storage bounds validation
//! (value within `[min_storage_hm3, max_storage_hm3]`) also requires the
//! hydro registry and is likewise deferred.

use chrono::NaiveDate;
use cobre_core::{
    AnticipatedCommitmentHistory, EntityId, HydroPastDefluence, HydroPastInflows, HydroStorage,
    InitialConditions, RecentObservation,
};
use serde::Deserialize;
use std::collections::HashSet;
use std::path::Path;

use crate::LoadError;

// ── Intermediate serde types ──────────────────────────────────────────────────

/// Intermediate serde type for `initial_conditions.json`, deserialized then
/// validated before conversion to [`InitialConditions`].
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RawInitialConditions {
    /// JSON schema URI — informational, not validated.
    #[serde(rename = "$schema")]
    _schema: Option<String>,

    /// Initial reservoir volumes for operating hydros [hm³].
    storage: Vec<RawHydroStorage>,

    /// Initial reservoir volumes for filling hydros [hm³].
    /// A filling hydro may not also appear in `storage`.
    filling_storage: Vec<RawHydroStorage>,

    /// Past inflow values for PAR(p) lag initialization [m³/s], one entry per
    /// hydro. For each hydro, `values_m3s[0]` is the most recent past inflow
    /// (lag 1) and `values_m3s[p-1]` is the oldest (lag p). Required when
    /// `inflow_lags` is enabled and the PAR order is > 0. Optional; defaults
    /// to empty.
    #[serde(default)]
    past_inflows: Vec<RawHydroPastInflows>,

    /// Observed inflow data for partial periods before the study start
    /// [m³/s per date range per hydro]. Used to seed the lag accumulator when
    /// a study begins mid-season. Date ranges for the same hydro must not
    /// overlap; adjacent ranges (start == previous end) are accepted.
    /// Optional; defaults to empty.
    #[serde(default)]
    recent_observations: Vec<RawRecentObservation>,

    /// Past committed MW values for each anticipated thermal plant, ordered by
    /// delivery stage ascending. Present only when the study includes at least
    /// one anticipated thermal. Optional; defaults to empty.
    #[serde(default)]
    past_anticipated_commitments: Vec<RawAnticipatedCommitmentHistory>,

    /// Past defluence (release) windows per arc [m³/s per date range], keyed by
    /// the upstream hydro whose release feeds the arc. Each entry is a
    /// self-describing `[start_date, end_date)` window on the pre-study calendar.
    /// Windows for the same hydro must not overlap; adjacent ranges
    /// (start == previous end) are accepted. Optional; defaults to empty.
    #[serde(default)]
    past_defluences: Vec<RawHydroPastDefluence>,
}

/// Initial reservoir volume for one hydro plant, in hm³.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHydroStorage {
    /// Hydro plant identifier. Must be unique within its array.
    hydro_id: i32,
    /// Reservoir volume [hm³]. Must be >= 0.0.
    value_hm3: f64,
}

/// Past inflow values for PAR(p) lag initialization for one hydro plant.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHydroPastInflows {
    /// Hydro plant identifier. Must be unique within `past_inflows`.
    hydro_id: i32,
    /// Past inflow values [m³/s], ordered from most recent (lag 1, index 0) to
    /// oldest (lag p, index p-1). Must have length >= the hydro's PAR order.
    values_m3s: Vec<f64>,
    /// Optional season IDs corresponding to each lag entry in `values_m3s`,
    /// one per entry. When present, length must equal `values_m3s.length`.
    /// Each value must reference a season ID defined in `season_definitions`.
    /// Absent from legacy JSON files (backward compatible).
    #[serde(default)]
    season_ids: Option<Vec<u32>>,
}

/// Past defluence (release) for the arc fed by a single upstream hydro over a
/// specific date range.
///
/// Mirrors [`RawRecentObservation`]: a self-describing `[start_date, end_date)`
/// window (ISO 8601, `end_date` exclusive and after `start_date`) carrying the
/// average release rate over the window. Multiple windows per hydro are allowed;
/// date ranges for the same hydro must not overlap, though adjacent ranges
/// (`start_date == previous end_date`) are accepted.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHydroPastDefluence {
    /// Upstream hydro plant identifier whose release feeds the arc.
    hydro_id: i32,
    /// Start of the release window (inclusive), as an ISO 8601 date
    /// (YYYY-MM-DD).
    start_date: String,
    /// End of the release window (exclusive), as an ISO 8601 date (YYYY-MM-DD).
    /// Must be after `start_date`.
    end_date: String,
    /// Average release rate over the window [m³/s]. Must be finite and
    /// non-negative.
    value_m3s: f64,
}

/// Observed inflow for a single hydro plant over a specific date range.
///
/// Used to seed the lag accumulator when a study begins mid-season (before the
/// first lag-period boundary). Each entry covers one hydro over one
/// observation period. Multiple entries per hydro are allowed for rolling
/// revisions.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawRecentObservation {
    /// Hydro plant identifier. Must reference a hydro entity in the system.
    hydro_id: i32,
    /// Start of the observation period (inclusive), as an ISO 8601 date
    /// (YYYY-MM-DD).
    start_date: String,
    /// End of the observation period (exclusive), as an ISO 8601 date
    /// (YYYY-MM-DD). Must be after `start_date`.
    end_date: String,
    /// Average inflow observed during the period [m³/s]. Must be finite and
    /// non-negative.
    value_m3s: f64,
}

/// Past committed MW values for one anticipated thermal plant.
///
/// `values_mw[j]` is the MW dispatched at the `j`-th pre-study-committed
/// delivery stage (delivery-anchored; required length is calendar-derived, not
/// `lead_stages` on a non-uniform calendar — validated semantically). The
/// values are sunk cost: they do not enter the study objective. Each value
/// must lie within the plant's `[min_generation_mw, max_generation_mw]` bounds
/// and, if the plant has a commissioning window, mature inside it (both
/// validated semantically).
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RawAnticipatedCommitmentHistory {
    /// Thermal plant identifier. Must reference an anticipated thermal.
    thermal_id: i32,
    /// Past committed MW values, ordered by delivery stage ascending. Required
    /// length is calendar-derived (validated semantically), not `lead_stages`.
    values_mw: Vec<f64>,
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Load and validate `initial_conditions.json` from `path`.
///
/// # Errors
///
/// | Condition                                              | Error variant              |
/// | ------------------------------------------------------ | -------------------------- |
/// | File not found / read failure                          | [`LoadError::IoError`]     |
/// | Invalid JSON syntax or missing required field          | [`LoadError::ParseError`]  |
/// | Negative `value_hm3`                                  | [`LoadError::SchemaError`] |
/// | Duplicate `hydro_id` within `storage`                 | [`LoadError::SchemaError`] |
/// | Duplicate `hydro_id` within `filling_storage`         | [`LoadError::SchemaError`] |
/// | `hydro_id` in both `storage` and `filling_storage`    | [`LoadError::SchemaError`] |
/// | Duplicate `hydro_id` within `past_inflows`            | [`LoadError::SchemaError`] |
/// | Non-finite or negative value in `past_inflows`        | [`LoadError::SchemaError`] |
/// | Invalid date / non-finite value / overlap in `past_defluences` | [`LoadError::SchemaError`] |
///
/// # Examples
///
/// ```no_run
/// use cobre_io::initial_conditions::parse_initial_conditions;
/// use std::path::Path;
///
/// let ic = parse_initial_conditions(Path::new("case/initial_conditions.json")).unwrap();
/// assert_eq!(ic.storage.len(), 2);
/// ```
pub fn parse_initial_conditions(path: &Path) -> Result<InitialConditions, LoadError> {
    let raw_text = std::fs::read_to_string(path).map_err(|e| LoadError::io(path, e))?;

    let raw: RawInitialConditions =
        serde_json::from_str(&raw_text).map_err(|e| LoadError::parse(path, e.to_string()))?;

    validate_raw(&raw, path)?;

    Ok(convert(raw))
}

// ── Validation ────────────────────────────────────────────────────────────────

/// Validate all invariants on the raw deserialized data.
///
/// Called before conversion so that error messages can reference JSON field
/// paths rather than Rust field names.
fn validate_raw(raw: &RawInitialConditions, path: &Path) -> Result<(), LoadError> {
    validate_non_negative(&raw.storage, "storage", path)?;
    validate_non_negative(&raw.filling_storage, "filling_storage", path)?;
    validate_no_duplicates(&raw.storage, "storage", path)?;
    validate_no_duplicates(&raw.filling_storage, "filling_storage", path)?;
    validate_mutual_exclusion(raw, path)?;
    validate_past_inflows_no_duplicates(&raw.past_inflows, path)?;
    validate_past_inflows_values(&raw.past_inflows, path)?;
    validate_past_inflows_season_ids(&raw.past_inflows, path)?;
    validate_recent_observations_dates(&raw.recent_observations, path)?;
    validate_recent_observations_values(&raw.recent_observations, path)?;
    validate_recent_observations_no_overlap(&raw.recent_observations, path)?;
    validate_anticipated_commitment_histories(&raw.past_anticipated_commitments, path)?;
    validate_past_defluences_dates(&raw.past_defluences, path)?;
    validate_past_defluences_values(&raw.past_defluences, path)?;
    validate_past_defluences_no_overlap(&raw.past_defluences, path)?;
    Ok(())
}

fn validate_non_negative(
    entries: &[RawHydroStorage],
    array_name: &str,
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        if entry.value_hm3 < 0.0 {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("{array_name}[{i}].value_hm3"),
                message: format!("value_hm3 must be >= 0.0, got {}", entry.value_hm3),
            });
        }
    }
    Ok(())
}

fn validate_no_duplicates(
    entries: &[RawHydroStorage],
    array_name: &str,
    path: &Path,
) -> Result<(), LoadError> {
    let mut seen: HashSet<i32> = HashSet::new();
    for (i, entry) in entries.iter().enumerate() {
        if !seen.insert(entry.hydro_id) {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("{array_name}[{i}].hydro_id"),
                message: format!("duplicate hydro_id {} in {array_name}", entry.hydro_id),
            });
        }
    }
    Ok(())
}

fn validate_mutual_exclusion(raw: &RawInitialConditions, path: &Path) -> Result<(), LoadError> {
    let storage_ids: HashSet<i32> = raw.storage.iter().map(|e| e.hydro_id).collect();

    for (i, entry) in raw.filling_storage.iter().enumerate() {
        if storage_ids.contains(&entry.hydro_id) {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("filling_storage[{i}].hydro_id"),
                message: format!(
                    "hydro_id {} appears in both storage and filling_storage; \
                     a hydro must appear in exactly one of the two arrays",
                    entry.hydro_id
                ),
            });
        }
    }
    Ok(())
}

fn validate_past_inflows_no_duplicates(
    entries: &[RawHydroPastInflows],
    path: &Path,
) -> Result<(), LoadError> {
    let mut seen: HashSet<i32> = HashSet::new();
    for (i, entry) in entries.iter().enumerate() {
        if !seen.insert(entry.hydro_id) {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_inflows[{i}].hydro_id"),
                message: format!("duplicate hydro_id {} in past_inflows", entry.hydro_id),
            });
        }
    }
    Ok(())
}

fn validate_past_inflows_values(
    entries: &[RawHydroPastInflows],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        for (j, &v) in entry.values_m3s.iter().enumerate() {
            if !v.is_finite() {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: format!("past_inflows[{i}].values_m3s[{j}]"),
                    message: format!(
                        "past_inflows[{i}].values_m3s[{j}] is not finite (got {v}); \
                         all inflow values must be finite numbers"
                    ),
                });
            }
        }
    }
    Ok(())
}

fn validate_past_inflows_season_ids(
    entries: &[RawHydroPastInflows],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        if let Some(season_ids) = &entry.season_ids
            && season_ids.len() != entry.values_m3s.len()
        {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_inflows[{i}].season_ids"),
                message: format!(
                    "past_inflows[{i}].season_ids has {} element(s) but \
                         past_inflows[{i}].values_m3s has {} element(s); \
                         season_ids length must equal values_m3s length",
                    season_ids.len(),
                    entry.values_m3s.len()
                ),
            });
        }
    }
    Ok(())
}

fn validate_recent_observations_dates(
    entries: &[RawRecentObservation],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        let start = NaiveDate::parse_from_str(&entry.start_date, "%Y-%m-%d").map_err(|_| {
            LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("recent_observations[{i}].start_date"),
                message: format!(
                    "recent_observations[{i}].start_date '{}' is not a valid ISO 8601 date \
                     (expected YYYY-MM-DD)",
                    entry.start_date
                ),
            }
        })?;
        let end = NaiveDate::parse_from_str(&entry.end_date, "%Y-%m-%d").map_err(|_| {
            LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("recent_observations[{i}].end_date"),
                message: format!(
                    "recent_observations[{i}].end_date '{}' is not a valid ISO 8601 date \
                     (expected YYYY-MM-DD)",
                    entry.end_date
                ),
            }
        })?;
        if end <= start {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("recent_observations[{i}].end_date"),
                message: format!(
                    "recent_observations[{i}]: end_date must be after start_date \
                     (start_date={}, end_date={})",
                    entry.start_date, entry.end_date
                ),
            });
        }
    }
    Ok(())
}

fn validate_recent_observations_values(
    entries: &[RawRecentObservation],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        if !entry.value_m3s.is_finite() || entry.value_m3s < 0.0 {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("recent_observations[{i}].value_m3s"),
                message: format!(
                    "recent_observations[{i}].value_m3s must be a finite non-negative number, \
                     got {}",
                    entry.value_m3s
                ),
            });
        }
    }
    Ok(())
}

/// Check that for observations with the same `hydro_id`, date ranges do not
/// overlap. Adjacent ranges where `start_date == previous end_date` are
/// accepted (exclusive-end convention).
///
/// Precondition: [`validate_recent_observations_dates`] has returned `Ok(())`
/// for these entries (dates are valid and `end > start`).
fn validate_recent_observations_no_overlap(
    entries: &[RawRecentObservation],
    path: &Path,
) -> Result<(), LoadError> {
    use std::collections::HashMap;

    let mut by_hydro: HashMap<i32, Vec<usize>> = HashMap::new();
    for (i, entry) in entries.iter().enumerate() {
        by_hydro.entry(entry.hydro_id).or_default().push(i);
    }

    for (hydro_id, mut indices) in by_hydro {
        indices.sort_by_key(|&i| {
            NaiveDate::parse_from_str(&entries[i].start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated"))
        });

        for window in indices.windows(2) {
            let (i_prev, i_curr) = (window[0], window[1]);
            let prev_end = NaiveDate::parse_from_str(&entries[i_prev].end_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("end_date already validated"));
            let curr_start = NaiveDate::parse_from_str(&entries[i_curr].start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated"));

            if curr_start < prev_end {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: format!("recent_observations[{i_curr}].start_date"),
                    message: format!(
                        "recent_observations: overlapping date ranges for hydro_id {hydro_id}: \
                         entry [{i_prev}] ends on {prev_end} but entry [{i_curr}] starts on \
                         {curr_start}"
                    ),
                });
            }
        }
    }
    Ok(())
}

/// Validate IO-layer invariants on `past_anticipated_commitments`.
fn validate_anticipated_commitment_histories(
    histories: &[RawAnticipatedCommitmentHistory],
    path: &Path,
) -> Result<(), LoadError> {
    let mut seen: HashSet<i32> = HashSet::new();
    for (i, entry) in histories.iter().enumerate() {
        if !seen.insert(entry.thermal_id) {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_anticipated_commitments[{i}].thermal_id"),
                message: format!(
                    "duplicate thermal_id {} in past_anticipated_commitments",
                    entry.thermal_id
                ),
            });
        }
        if entry.values_mw.is_empty() {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_anticipated_commitments[{i}].values_mw"),
                message: format!(
                    "past_anticipated_commitments[{i}].values_mw must not be empty; \
                     anticipated plants always require at least one committed value"
                ),
            });
        }
        for (j, &v) in entry.values_mw.iter().enumerate() {
            if !v.is_finite() {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: format!("past_anticipated_commitments[{i}].values_mw[{j}]"),
                    message: format!(
                        "past_anticipated_commitments[{i}].values_mw[{j}] is not finite \
                         (got {v}); all committed MW values must be finite numbers"
                    ),
                });
            }
            if v < 0.0 {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: format!("past_anticipated_commitments[{i}].values_mw[{j}]"),
                    message: format!(
                        "past_anticipated_commitments[{i}].values_mw[{j}] must be >= 0 \
                         (got {v}); anticipated commitments are physical generation amounts"
                    ),
                });
            }
        }
    }
    Ok(())
}

fn validate_past_defluences_dates(
    entries: &[RawHydroPastDefluence],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        let start = NaiveDate::parse_from_str(&entry.start_date, "%Y-%m-%d").map_err(|_| {
            LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_defluences[{i}].start_date"),
                message: format!(
                    "past_defluences[{i}].start_date '{}' is not a valid ISO 8601 date \
                     (expected YYYY-MM-DD)",
                    entry.start_date
                ),
            }
        })?;
        let end = NaiveDate::parse_from_str(&entry.end_date, "%Y-%m-%d").map_err(|_| {
            LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_defluences[{i}].end_date"),
                message: format!(
                    "past_defluences[{i}].end_date '{}' is not a valid ISO 8601 date \
                     (expected YYYY-MM-DD)",
                    entry.end_date
                ),
            }
        })?;
        if end <= start {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_defluences[{i}].end_date"),
                message: format!(
                    "past_defluences[{i}]: end_date must be after start_date \
                     (start_date={}, end_date={})",
                    entry.start_date, entry.end_date
                ),
            });
        }
    }
    Ok(())
}

fn validate_past_defluences_values(
    entries: &[RawHydroPastDefluence],
    path: &Path,
) -> Result<(), LoadError> {
    for (i, entry) in entries.iter().enumerate() {
        if !entry.value_m3s.is_finite() || entry.value_m3s < 0.0 {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("past_defluences[{i}].value_m3s"),
                message: format!(
                    "past_defluences[{i}].value_m3s must be a finite non-negative number, \
                     got {}",
                    entry.value_m3s
                ),
            });
        }
    }
    Ok(())
}

/// Check that for defluence windows with the same `hydro_id`, date ranges do
/// not overlap. Adjacent ranges where `start_date == previous end_date` are
/// accepted (exclusive-end convention).
///
/// Precondition: [`validate_past_defluences_dates`] has returned `Ok(())` for
/// these entries (dates are valid and `end > start`).
fn validate_past_defluences_no_overlap(
    entries: &[RawHydroPastDefluence],
    path: &Path,
) -> Result<(), LoadError> {
    use std::collections::HashMap;

    let mut by_hydro: HashMap<i32, Vec<usize>> = HashMap::new();
    for (i, entry) in entries.iter().enumerate() {
        by_hydro.entry(entry.hydro_id).or_default().push(i);
    }

    for (hydro_id, mut indices) in by_hydro {
        indices.sort_by_key(|&i| {
            NaiveDate::parse_from_str(&entries[i].start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated"))
        });

        for window in indices.windows(2) {
            let (i_prev, i_curr) = (window[0], window[1]);
            let prev_end = NaiveDate::parse_from_str(&entries[i_prev].end_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("end_date already validated"));
            let curr_start = NaiveDate::parse_from_str(&entries[i_curr].start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated"));

            if curr_start < prev_end {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: format!("past_defluences[{i_curr}].start_date"),
                    message: format!(
                        "past_defluences: overlapping date ranges for hydro_id {hydro_id}: \
                         entry [{i_prev}] ends on {prev_end} but entry [{i_curr}] starts on \
                         {curr_start}"
                    ),
                });
            }
        }
    }
    Ok(())
}

// ── Conversion ────────────────────────────────────────────────────────────────

/// Convert validated raw data into [`InitialConditions`].
///
/// Precondition: [`validate_raw`] has returned `Ok(())` for this data.
/// All arrays are sorted by `hydro_id` to satisfy the declaration-order
/// invariance requirement.
fn convert(raw: RawInitialConditions) -> InitialConditions {
    let mut storage: Vec<HydroStorage> = raw
        .storage
        .into_iter()
        .map(|e| HydroStorage {
            hydro_id: EntityId(e.hydro_id),
            value_hm3: e.value_hm3,
        })
        .collect();
    storage.sort_by_key(|e| e.hydro_id.0);

    let mut filling_storage: Vec<HydroStorage> = raw
        .filling_storage
        .into_iter()
        .map(|e| HydroStorage {
            hydro_id: EntityId(e.hydro_id),
            value_hm3: e.value_hm3,
        })
        .collect();
    filling_storage.sort_by_key(|e| e.hydro_id.0);

    let mut past_inflows: Vec<HydroPastInflows> = raw
        .past_inflows
        .into_iter()
        .map(|e| HydroPastInflows {
            hydro_id: EntityId(e.hydro_id),
            values_m3s: e.values_m3s,
            season_ids: e.season_ids,
        })
        .collect();
    past_inflows.sort_by_key(|e| e.hydro_id.0);

    let mut recent_observations: Vec<RecentObservation> = raw
        .recent_observations
        .into_iter()
        .map(|e| RecentObservation {
            hydro_id: EntityId(e.hydro_id),
            start_date: NaiveDate::parse_from_str(&e.start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated")),
            end_date: NaiveDate::parse_from_str(&e.end_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("end_date already validated")),
            value_m3s: e.value_m3s,
        })
        .collect();
    recent_observations.sort_by_key(|e| (e.hydro_id.0, e.start_date));

    let mut past_anticipated_commitments: Vec<AnticipatedCommitmentHistory> = raw
        .past_anticipated_commitments
        .into_iter()
        .map(|e| AnticipatedCommitmentHistory {
            thermal_id: EntityId(e.thermal_id),
            values_mw: e.values_mw,
        })
        .collect();
    past_anticipated_commitments.sort_by_key(|e| e.thermal_id.0);

    let mut past_defluences: Vec<HydroPastDefluence> = raw
        .past_defluences
        .into_iter()
        .map(|e| HydroPastDefluence {
            hydro_id: EntityId(e.hydro_id),
            start_date: NaiveDate::parse_from_str(&e.start_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("start_date already validated")),
            end_date: NaiveDate::parse_from_str(&e.end_date, "%Y-%m-%d")
                .unwrap_or_else(|_| unreachable!("end_date already validated")),
            value_m3s: e.value_m3s,
        })
        .collect();
    past_defluences.sort_by_key(|e| (e.hydro_id.0, e.start_date));

    InitialConditions {
        storage,
        filling_storage,
        past_inflows,
        past_anticipated_commitments,
        recent_observations,
        past_defluences,
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic, clippy::too_many_lines)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Write a string to a temp file and return the file handle (keeps it alive).
    fn write_json(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    /// Canonical valid `initial_conditions.json` with 2 storage and 1 filling entry.
    const VALID_JSON: &str = r#"{
      "$schema": "https://raw.githubusercontent.com/cobre-rs/cobre/refs/heads/main/schemas/initial_conditions.schema.json",
      "storage": [
        { "hydro_id": 0, "value_hm3": 15000.0 },
        { "hydro_id": 1, "value_hm3": 8500.0 }
      ],
      "filling_storage": [
        { "hydro_id": 10, "value_hm3": 200.0 }
      ]
    }"#;

    // ── AC: parse valid initial conditions ────────────────────────────────────

    /// Given a valid `initial_conditions.json` with 2 storage entries and
    /// 1 filling entry, `parse_initial_conditions` returns `Ok(ic)` with
    /// correct field counts and entity IDs.
    #[test]
    fn test_parse_valid_initial_conditions() {
        let f = write_json(VALID_JSON);
        let ic = parse_initial_conditions(f.path()).unwrap();

        assert_eq!(ic.storage.len(), 2);
        assert_eq!(ic.filling_storage.len(), 1);
        assert!(
            ic.past_inflows.is_empty(),
            "past_inflows absent defaults to empty"
        );

        assert_eq!(ic.storage[0].hydro_id, EntityId(0));
        assert!(
            (ic.storage[0].value_hm3 - 15_000.0).abs() < f64::EPSILON,
            "expected 15000.0, got {}",
            ic.storage[0].value_hm3
        );
        assert_eq!(ic.storage[1].hydro_id, EntityId(1));
        assert!(
            (ic.storage[1].value_hm3 - 8_500.0).abs() < f64::EPSILON,
            "expected 8500.0, got {}",
            ic.storage[1].value_hm3
        );

        assert_eq!(ic.filling_storage[0].hydro_id, EntityId(10));
        assert!(
            (ic.filling_storage[0].value_hm3 - 200.0).abs() < f64::EPSILON,
            "expected 200.0, got {}",
            ic.filling_storage[0].value_hm3
        );
    }

    /// Given a valid `initial_conditions.json` with `past_inflows`, the values
    /// are parsed correctly and sorted by `hydro_id`.
    #[test]
    fn test_parse_valid_past_inflows() {
        let json = r#"{
          "storage": [
            { "hydro_id": 0, "value_hm3": 1000.0 },
            { "hydro_id": 1, "value_hm3": 2000.0 }
          ],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 1, "values_m3s": [200.0, 100.0] },
            { "hydro_id": 0, "values_m3s": [600.0, 500.0] }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();

        assert_eq!(ic.past_inflows.len(), 2);
        assert_eq!(ic.past_inflows[0].hydro_id, EntityId(0));
        assert_eq!(ic.past_inflows[0].values_m3s, vec![600.0, 500.0]);
        assert_eq!(ic.past_inflows[1].hydro_id, EntityId(1));
        assert_eq!(ic.past_inflows[1].values_m3s, vec![200.0, 100.0]);
    }

    // ── AC: empty arrays → Ok ─────────────────────────────────────────────────

    /// Given an `initial_conditions.json` with empty arrays, `parse_initial_conditions`
    /// returns `Ok(ic)` with empty storage and `filling_storage` vectors.
    #[test]
    fn test_parse_empty_arrays() {
        let json = r#"{ "storage": [], "filling_storage": [] }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert!(ic.storage.is_empty());
        assert!(ic.filling_storage.is_empty());
        assert!(ic.past_inflows.is_empty());
    }

    // ── AC: negative value_hm3 → SchemaError ─────────────────────────────────

    /// Given an `initial_conditions.json` with a negative `value_hm3` in
    /// `storage`, `parse_initial_conditions` returns `Err(LoadError::SchemaError)`
    /// with field containing `"value_hm3"`.
    #[test]
    fn test_negative_storage_value() {
        let json = r#"{
          "storage": [
            { "hydro_id": 0, "value_hm3": -1.0 }
          ],
          "filling_storage": []
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("value_hm3"),
                    "field should contain 'value_hm3', got: {field}"
                );
                assert!(
                    message.contains("value_hm3"),
                    "message should mention value_hm3, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given an `initial_conditions.json` with a negative `value_hm3` in
    /// `filling_storage`, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with field containing `"value_hm3"`.
    #[test]
    fn test_negative_filling_storage_value() {
        let json = r#"{
          "storage": [],
          "filling_storage": [
            { "hydro_id": 10, "value_hm3": -100.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("value_hm3"),
                    "field should contain 'value_hm3', got: {field}"
                );
                assert!(
                    message.contains("value_hm3"),
                    "message should mention value_hm3, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: duplicate hydro_id within storage → SchemaError ───────────────────

    /// Given an `initial_conditions.json` where the same `hydro_id` appears
    /// twice in `storage`, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` mentioning "duplicate".
    #[test]
    fn test_duplicate_hydro_id_in_storage() {
        let json = r#"{
          "storage": [
            { "hydro_id": 5, "value_hm3": 1000.0 },
            { "hydro_id": 5, "value_hm3": 2000.0 }
          ],
          "filling_storage": []
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("storage"),
                    "field should mention 'storage', got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should mention 'duplicate', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given an `initial_conditions.json` where the same `hydro_id` appears
    /// twice in `filling_storage`, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` mentioning "duplicate".
    #[test]
    fn test_duplicate_hydro_id_in_filling_storage() {
        let json = r#"{
          "storage": [],
          "filling_storage": [
            { "hydro_id": 10, "value_hm3": 100.0 },
            { "hydro_id": 10, "value_hm3": 200.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("filling_storage"),
                    "field should mention 'filling_storage', got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should mention 'duplicate', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: hydro_id in both lists → SchemaError ──────────────────────────────

    /// Given an `initial_conditions.json` where the same `hydro_id` appears in
    /// both `storage` and `filling_storage`, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` mentioning mutual exclusion.
    #[test]
    fn test_hydro_id_in_both_lists() {
        let json = r#"{
          "storage": [
            { "hydro_id": 5, "value_hm3": 1000.0 }
          ],
          "filling_storage": [
            { "hydro_id": 5, "value_hm3": 100.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("filling_storage"),
                    "field should mention 'filling_storage', got: {field}"
                );
                assert!(
                    message.contains("storage") && message.contains("filling_storage"),
                    "message should mention both arrays for mutual exclusion, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: past_inflows duplicate hydro_id → SchemaError ─────────────────────

    /// Given `past_inflows` with a duplicate `hydro_id`, `parse_initial_conditions`
    /// returns `Err(LoadError::SchemaError)` mentioning "duplicate" and "`past_inflows`".
    #[test]
    fn test_duplicate_hydro_id_in_past_inflows() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 3, "values_m3s": [100.0] },
            { "hydro_id": 3, "values_m3s": [200.0] }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("past_inflows"),
                    "field should mention 'past_inflows', got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should mention 'duplicate', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: file not found → IoError ─────────────────────────────────────────

    /// Given a nonexistent path, `parse_initial_conditions` returns
    /// `Err(LoadError::IoError)` with the matching path.
    #[test]
    fn test_file_not_found() {
        let path = Path::new("/nonexistent/initial_conditions.json");
        let err = parse_initial_conditions(path).unwrap_err();
        match &err {
            LoadError::IoError { path: p, .. } => {
                assert_eq!(p, path);
            }
            other => panic!("expected IoError, got: {other:?}"),
        }
    }

    // ── Additional edge cases ─────────────────────────────────────────────────

    /// Zero storage value (exactly 0.0) is valid — the boundary is non-negative.
    #[test]
    fn test_zero_storage_value_is_valid() {
        let json = r#"{
          "storage": [
            { "hydro_id": 0, "value_hm3": 0.0 }
          ],
          "filling_storage": []
        }"#;
        let f = write_json(json);
        let result = parse_initial_conditions(f.path());
        assert!(
            result.is_ok(),
            "0.0 is non-negative and must be accepted, got: {result:?}"
        );
    }

    /// Filling storage value below dead volume is valid . Only non-negativity is
    /// checked here; bounds against dead volume are deferred to Layer 3.
    #[test]
    fn test_filling_storage_below_dead_volume_is_valid() {
        let json = r#"{
          "storage": [],
          "filling_storage": [
            { "hydro_id": 10, "value_hm3": 1.0 }
          ]
        }"#;
        let f = write_json(json);
        let result = parse_initial_conditions(f.path());
        assert!(
            result.is_ok(),
            "filling storage values below dead volume are valid at this layer, got: {result:?}"
        );
    }

    /// Declaration-order invariance: arrays are sorted by `hydro_id` after loading.
    #[test]
    fn test_declaration_order_invariance() {
        let json_ordered = r#"{
          "storage": [
            { "hydro_id": 0, "value_hm3": 1000.0 },
            { "hydro_id": 1, "value_hm3": 2000.0 }
          ],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 0, "values_m3s": [600.0, 500.0] },
            { "hydro_id": 1, "values_m3s": [200.0, 100.0] }
          ]
        }"#;
        let json_reversed = r#"{
          "storage": [
            { "hydro_id": 1, "value_hm3": 2000.0 },
            { "hydro_id": 0, "value_hm3": 1000.0 }
          ],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 1, "values_m3s": [200.0, 100.0] },
            { "hydro_id": 0, "values_m3s": [600.0, 500.0] }
          ]
        }"#;

        let f1 = write_json(json_ordered);
        let f2 = write_json(json_reversed);
        let ic1 = parse_initial_conditions(f1.path()).unwrap();
        let ic2 = parse_initial_conditions(f2.path()).unwrap();

        assert_eq!(
            ic1, ic2,
            "results must be identical regardless of input ordering"
        );
        assert_eq!(ic1.storage[0].hydro_id, EntityId(0));
        assert_eq!(ic1.storage[1].hydro_id, EntityId(1));
        assert_eq!(ic1.past_inflows[0].hydro_id, EntityId(0));
        assert_eq!(ic1.past_inflows[1].hydro_id, EntityId(1));
    }

    /// Invalid JSON syntax → `ParseError`.
    #[test]
    fn test_invalid_json_syntax() {
        let f = write_json(r#"{"storage": [not valid json}}"#);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        assert!(
            matches!(err, LoadError::ParseError { .. }),
            "expected ParseError for invalid JSON, got: {err:?}"
        );
    }

    /// Missing required field `storage` → `ParseError`.
    #[test]
    fn test_missing_required_field() {
        let json = r#"{ "filling_storage": [] }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        assert!(
            matches!(err, LoadError::ParseError { .. }),
            "expected ParseError for missing storage field, got: {err:?}"
        );
    }

    /// Zero value in `past_inflows.values_m3s` is valid (dry season).
    #[test]
    fn test_zero_past_inflow_value_is_valid() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 1, "values_m3s": [0.0, 50.0] }
          ]
        }"#;
        let f = write_json(json);
        let result = parse_initial_conditions(f.path());
        assert!(
            result.is_ok(),
            "0.0 in past_inflows is valid (dry season), got: {result:?}"
        );
    }

    /// Empty `values_m3s` array is accepted — no lag initialization needed.
    #[test]
    fn test_empty_values_m3s_is_valid() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 1, "values_m3s": [] }
          ]
        }"#;
        let f = write_json(json);
        let result = parse_initial_conditions(f.path());
        assert!(
            result.is_ok(),
            "empty values_m3s should be accepted, got: {result:?}"
        );
    }

    // ── AC: recent_observations absent → empty Vec (backward compat) ──────────

    /// Given a `initial_conditions.json` without a `recent_observations` key,
    /// `parse_initial_conditions` returns `Ok(ic)` with an empty
    /// `recent_observations` vec.
    #[test]
    fn test_recent_observations_absent_defaults_to_empty() {
        let f = write_json(VALID_JSON);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert!(
            ic.recent_observations.is_empty(),
            "absent recent_observations must default to empty vec"
        );
    }

    /// Given `"recent_observations": []`, `parse_initial_conditions` returns
    /// `Ok(ic)` with an empty `recent_observations` vec.
    #[test]
    fn test_recent_observations_empty_array() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": []
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert!(ic.recent_observations.is_empty());
    }

    // ── AC: valid recent_observations → parsed and sorted ─────────────────────

    /// Given two valid `recent_observations` entries for the same hydro with
    /// adjacent (non-overlapping) date ranges, `parse_initial_conditions` returns
    /// `Ok(ic)` with both entries, dates parsed as `NaiveDate`.
    #[test]
    fn test_recent_observations_valid_two_entries() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 },
            { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert_eq!(ic.recent_observations.len(), 2);
        assert_eq!(ic.recent_observations[0].hydro_id, EntityId(0));
        assert_eq!(
            ic.recent_observations[0].start_date,
            chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap()
        );
        assert_eq!(
            ic.recent_observations[0].end_date,
            chrono::NaiveDate::from_ymd_opt(2026, 4, 4).unwrap()
        );
        assert!((ic.recent_observations[0].value_m3s - 500.0).abs() < f64::EPSILON);
        assert!((ic.recent_observations[1].value_m3s - 480.0).abs() < f64::EPSILON);
    }

    // ── AC: invalid start_date format → SchemaError ───────────────────────────

    /// Given a `recent_observations` entry with an invalid `start_date` format
    /// (slash-separated), `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with field containing `start_date`.
    #[test]
    fn test_recent_observations_invalid_start_date_format() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026/04/01", "end_date": "2026-04-04", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert!(
                    field.contains("start_date"),
                    "field should mention 'start_date', got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `recent_observations` entry with an invalid `end_date` format,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// field containing `end_date`.
    #[test]
    fn test_recent_observations_invalid_end_date_format() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "not-a-date", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert!(
                    field.contains("end_date"),
                    "field should mention 'end_date', got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: end_date == start_date → SchemaError ──────────────────────────────

    /// Given a `recent_observations` entry where `end_date == start_date`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// `message` containing "`end_date` must be after `start_date`".
    #[test]
    fn test_recent_observations_end_date_equals_start_date() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-01", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("end_date must be after start_date"),
                    "message should contain 'end_date must be after start_date', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `recent_observations` entry where `end_date < start_date`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// `message` containing "`end_date` must be after `start_date`".
    #[test]
    fn test_recent_observations_end_date_before_start_date() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-05", "end_date": "2026-04-01", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("end_date must be after start_date"),
                    "message should contain 'end_date must be after start_date', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: negative value_m3s → SchemaError ─────────────────────────────────

    /// Given a `recent_observations` entry with `value_m3s: -1.0`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// field containing `"value_m3s"`.
    #[test]
    fn test_recent_observations_negative_value() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": -1.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert!(
                    field.contains("value_m3s"),
                    "field should contain 'value_m3s', got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: overlapping date ranges → SchemaError ─────────────────────────────

    /// Given two `recent_observations` entries for the same hydro with
    /// overlapping date ranges, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with `message` containing "overlapping".
    #[test]
    fn test_recent_observations_overlapping_ranges() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-05", "value_m3s": 500.0 },
            { "hydro_id": 0, "start_date": "2026-04-03", "end_date": "2026-04-10", "value_m3s": 480.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("overlapping"),
                    "message should contain 'overlapping', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: adjacent non-overlapping ranges → Ok ──────────────────────────────

    /// Given two `recent_observations` entries for the same hydro where
    /// `start == prev_end` (adjacent, exclusive-end convention), they are
    /// accepted.
    #[test]
    fn test_recent_observations_adjacent_ranges_are_valid() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 },
            { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 }
          ]
        }"#;
        let f = write_json(json);
        let result = parse_initial_conditions(f.path());
        assert!(
            result.is_ok(),
            "adjacent ranges (start == prev_end) must be accepted, got: {result:?}"
        );
    }

    // ── AC: declaration-order invariance ──────────────────────────────────────

    /// Given `recent_observations` entries for `hydro_id`s [1, 0] in that order,
    /// the result is sorted by `(hydro_id, start_date)` with `hydro_id` 0 first.
    #[test]
    fn test_recent_observations_sorted_by_hydro_id_then_start_date() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 1, "start_date": "2026-04-01", "end_date": "2026-04-07", "value_m3s": 300.0 },
            { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 },
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert_eq!(ic.recent_observations.len(), 3);
        assert_eq!(ic.recent_observations[0].hydro_id, EntityId(0));
        assert_eq!(
            ic.recent_observations[0].start_date,
            chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap()
        );
        assert_eq!(ic.recent_observations[1].hydro_id, EntityId(0));
        assert_eq!(
            ic.recent_observations[1].start_date,
            chrono::NaiveDate::from_ymd_opt(2026, 4, 4).unwrap()
        );
        assert_eq!(ic.recent_observations[2].hydro_id, EntityId(1));
    }

    /// Given `recent_observations` entries declared in reverse vs forward order,
    /// the resulting `InitialConditions` values are equal (declaration-order
    /// invariance).
    #[test]
    fn test_recent_observations_declaration_order_invariance() {
        let json_forward = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 },
            { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 }
          ]
        }"#;
        let json_reversed = r#"{
          "storage": [],
          "filling_storage": [],
          "recent_observations": [
            { "hydro_id": 0, "start_date": "2026-04-04", "end_date": "2026-04-11", "value_m3s": 480.0 },
            { "hydro_id": 0, "start_date": "2026-04-01", "end_date": "2026-04-04", "value_m3s": 500.0 }
          ]
        }"#;
        let f1 = write_json(json_forward);
        let f2 = write_json(json_reversed);
        let ic1 = parse_initial_conditions(f1.path()).unwrap();
        let ic2 = parse_initial_conditions(f2.path()).unwrap();
        assert_eq!(
            ic1, ic2,
            "results must be identical regardless of input ordering"
        );
        assert_eq!(
            ic1.recent_observations[0].start_date,
            chrono::NaiveDate::from_ymd_opt(2026, 4, 1).unwrap()
        );
    }

    // ── AC: past_inflows season_ids ───────────────────────────────────────────

    /// Given a `past_inflows` entry with matching `season_ids` and `values_m3s`
    /// lengths, `parse_initial_conditions` returns `Ok(ic)` with the `season_ids`
    /// preserved.
    #[test]
    fn test_parse_past_inflows_with_valid_season_ids() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 0, "values_m3s": [600.0, 500.0], "season_ids": [3, 2] }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert_eq!(ic.past_inflows.len(), 1);
        assert_eq!(ic.past_inflows[0].hydro_id, EntityId(0));
        assert_eq!(ic.past_inflows[0].values_m3s, vec![600.0, 500.0]);
        assert_eq!(ic.past_inflows[0].season_ids, Some(vec![3, 2]));
    }

    /// Given a `past_inflows` entry where `season_ids` has length 3 but
    /// `values_m3s` has length 2, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with field containing `season_ids`.
    #[test]
    fn test_parse_past_inflows_season_ids_length_mismatch() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 0, "values_m3s": [600.0, 500.0], "season_ids": [3, 2, 1] }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("season_ids"),
                    "field should contain 'season_ids', got: {field}"
                );
                assert!(
                    field.contains("past_inflows[0]"),
                    "field should reference 'past_inflows[0]', got: {field}"
                );
                assert!(
                    message.contains("season_ids length must equal values_m3s length")
                        || message.contains('3')
                        || message.contains('2'),
                    "message should describe the mismatch, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `past_inflows` entry without a `season_ids` key (legacy JSON),
    /// `parse_initial_conditions` returns `Ok(ic)` with `season_ids == None`.
    #[test]
    fn test_parse_past_inflows_without_season_ids_backward_compat() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_inflows": [
            { "hydro_id": 0, "values_m3s": [600.0, 500.0] }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert_eq!(ic.past_inflows.len(), 1);
        assert_eq!(
            ic.past_inflows[0].season_ids, None,
            "absent season_ids must deserialize as None"
        );
    }

    // ── AC: past_anticipated_commitments ─────────────────────────────────────

    /// Given an `initial_conditions.json` with one `past_anticipated_commitments`
    /// entry, `parse_initial_conditions` returns the correct parsed value.
    #[test]
    fn test_parse_past_anticipated_commitments_present() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 1, "values_mw": [120.0, 180.0] }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();

        assert_eq!(ic.past_anticipated_commitments.len(), 1);
        assert_eq!(ic.past_anticipated_commitments[0].thermal_id, EntityId(1));
        assert_eq!(
            ic.past_anticipated_commitments[0].values_mw,
            vec![120.0, 180.0]
        );
    }

    /// Given an `initial_conditions.json` with no `past_anticipated_commitments`
    /// key, `parse_initial_conditions` returns an empty vec.
    #[test]
    fn test_parse_past_anticipated_commitments_absent_defaults_empty() {
        let f = write_json(VALID_JSON);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert!(
            ic.past_anticipated_commitments.is_empty(),
            "absent past_anticipated_commitments must default to empty vec"
        );
    }

    /// Given two JSON inputs identical except for entry order in
    /// `past_anticipated_commitments`, the resulting vecs are identical
    /// (sorted by `thermal_id` ascending — declaration-order invariance).
    #[test]
    fn test_past_anticipated_commitments_declaration_order_invariance() {
        let json_forward = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 1, "values_mw": [120.0, 180.0] },
            { "thermal_id": 2, "values_mw": [50.0] }
          ]
        }"#;
        let json_reversed = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 2, "values_mw": [50.0] },
            { "thermal_id": 1, "values_mw": [120.0, 180.0] }
          ]
        }"#;
        let f1 = write_json(json_forward);
        let f2 = write_json(json_reversed);
        let ic1 = parse_initial_conditions(f1.path()).unwrap();
        let ic2 = parse_initial_conditions(f2.path()).unwrap();

        assert_eq!(
            ic1.past_anticipated_commitments, ic2.past_anticipated_commitments,
            "results must be identical regardless of input ordering"
        );
        assert_eq!(ic1.past_anticipated_commitments[0].thermal_id, EntityId(1));
        assert_eq!(ic1.past_anticipated_commitments[1].thermal_id, EntityId(2));
    }

    /// Given two entries with the same `thermal_id: 5` in
    /// `past_anticipated_commitments`, `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with field containing
    /// `"past_anticipated_commitments["` and message containing `"duplicate"`.
    #[test]
    fn test_duplicate_thermal_id_in_past_anticipated_commitments_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 5, "values_mw": [100.0] },
            { "thermal_id": 5, "values_mw": [200.0] }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("past_anticipated_commitments["),
                    "field should contain 'past_anticipated_commitments[', got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should contain 'duplicate', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `past_anticipated_commitments` entry with `values_mw: []`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// `message` containing `"values_mw must not be empty"`.
    #[test]
    fn test_empty_values_mw_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 3, "values_mw": [] }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("values_mw must not be empty"),
                    "message should contain 'values_mw must not be empty', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `past_anticipated_commitments` entry with a negative MW value
    /// (e.g. `values_mw: [120.0, -50.0]`), `parse_initial_conditions` returns
    /// `Err(LoadError::SchemaError)` with `message` containing `"must be >= 0"`
    /// and `field` containing `"values_mw[1]"`.
    #[test]
    fn test_negative_values_mw_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_anticipated_commitments": [
            { "thermal_id": 7, "values_mw": [120.0, -50.0] }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    message.contains("must be >= 0"),
                    "message should contain 'must be >= 0', got: {message}"
                );
                assert!(
                    field.contains("values_mw[1]"),
                    "field should contain 'values_mw[1]', got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: past_defluences absent → empty; present → parsed and sorted ───────

    /// Given a `initial_conditions.json` without a `past_defluences` key,
    /// `parse_initial_conditions` returns `Ok(ic)` with an empty
    /// `past_defluences` vec.
    #[test]
    fn test_past_defluences_absent_defaults_to_empty() {
        let f = write_json(VALID_JSON);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert!(
            ic.past_defluences.is_empty(),
            "absent past_defluences must default to empty vec"
        );
    }

    /// Given two valid `past_defluences` windows for the same hydro with adjacent
    /// (non-overlapping) date ranges plus one for another hydro, the entries are
    /// parsed with dates as `NaiveDate` and sorted by `(hydro_id, start_date)`
    /// (declaration-order invariance).
    #[test]
    fn test_parse_valid_past_defluences_windows_sorted() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_defluences": [
            { "hydro_id": 1, "start_date": "2023-12-30", "end_date": "2024-01-01", "value_m3s": 200.0 },
            { "hydro_id": 0, "start_date": "2023-12-25", "end_date": "2023-12-28", "value_m3s": 600.0 },
            { "hydro_id": 0, "start_date": "2023-12-28", "end_date": "2024-01-01", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let ic = parse_initial_conditions(f.path()).unwrap();
        assert_eq!(ic.past_defluences.len(), 3);
        assert_eq!(ic.past_defluences[0].hydro_id, EntityId(0));
        assert_eq!(
            ic.past_defluences[0].start_date,
            chrono::NaiveDate::from_ymd_opt(2023, 12, 25).unwrap()
        );
        assert_eq!(ic.past_defluences[1].hydro_id, EntityId(0));
        assert_eq!(
            ic.past_defluences[1].start_date,
            chrono::NaiveDate::from_ymd_opt(2023, 12, 28).unwrap()
        );
        assert_eq!(ic.past_defluences[2].hydro_id, EntityId(1));
        assert!((ic.past_defluences[2].value_m3s - 200.0).abs() < f64::EPSILON);
    }

    /// Given two `past_defluences` windows for the same hydro with overlapping
    /// date ranges, `parse_initial_conditions` returns `Err(LoadError::SchemaError)`
    /// with `message` containing "overlapping".
    #[test]
    fn test_past_defluences_overlapping_windows_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_defluences": [
            { "hydro_id": 0, "start_date": "2023-12-25", "end_date": "2023-12-30", "value_m3s": 500.0 },
            { "hydro_id": 0, "start_date": "2023-12-28", "end_date": "2024-01-01", "value_m3s": 480.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("overlapping"),
                    "message should contain 'overlapping', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `past_defluences` window where `end_date <= start_date`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// `message` containing "`end_date` must be after `start_date`".
    #[test]
    fn test_past_defluences_end_before_start_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_defluences": [
            { "hydro_id": 0, "start_date": "2024-01-01", "end_date": "2023-12-30", "value_m3s": 500.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("end_date must be after start_date"),
                    "message should contain 'end_date must be after start_date', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Given a `past_defluences` window with `value_m3s: -1.0`,
    /// `parse_initial_conditions` returns `Err(LoadError::SchemaError)` with
    /// field containing `"value_m3s"`.
    #[test]
    fn test_past_defluences_negative_value_rejected() {
        let json = r#"{
          "storage": [],
          "filling_storage": [],
          "past_defluences": [
            { "hydro_id": 0, "start_date": "2023-12-30", "end_date": "2024-01-01", "value_m3s": -1.0 }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_initial_conditions(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert!(
                    field.contains("value_m3s"),
                    "field should contain 'value_m3s', got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }
}