cobre-io 0.15.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
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
//! Parsing for `system/hydro_production_models.json` — per-hydro production model configuration.
//!
//! [`parse_production_models`] reads `system/hydro_production_models.json` and returns a sorted
//! `Vec<ProductionModelConfig>` describing the HPF model selection for each configured hydro.
//!
//! ## JSON structure
//!
//! ```json
//! {
//!   "$schema": "https://raw.githubusercontent.com/cobre-rs/cobre/refs/heads/main/schemas/production_models.schema.json",
//!   "production_models": [
//!     {
//!       "hydro_id": 0,
//!       "selection_mode": "stage_ranges",
//!       "stage_ranges": [
//!         {
//!           "start_stage_id": 0, "end_stage_id": 24,
//!           "model": "fpha",
//!           "fpha_config": { "source": "computed" }
//!         }
//!       ]
//!     }
//!   ]
//! }
//! ```
//!
//! ## Selection modes
//!
//! - **`stage_ranges`**: Each stage maps to a model via explicit `[start, end)` ranges.
//! - **`seasonal`**: Each stage maps to a model via its season index. Seasons not listed
//!   fall back to `default_model`.
//!
//! ## Output ordering
//!
//! Results are sorted by `hydro_id` ascending. Duplicate `hydro_id` values are rejected
//! as a `SchemaError`.
//!
//! ## Validation
//!
//! Per-entry constraints enforced by this parser:
//!
//! - No two entries share the same `hydro_id`.
//! - For `stage_ranges` mode: `start_stage_id <= end_stage_id` when `end_stage_id` is not null.
//! - In `fitting_window`: absolute bounds (`volume_min_hm3` / `volume_max_hm3`) and percentile
//!   bounds (`volume_min_percentile` / `volume_max_percentile`) are mutually exclusive.
//! - `productivity_mw_per_m3s` is **rejected** for `"fpha"` entries (both stage-range and
//!   seasonal); FPHA derives productivity from its hyperplane geometry.
//! - `productivity_mw_per_m3s` is **optional** for `"constant_productivity"` and
//!   `"linearized_head"` entries. When omitted or `null`, the value is expected to be supplied by
//!   `system/hydro_energy_productivity.parquet`; cross-file resolution is enforced by
//!   `validation::productivity_resolution`.
//! - When `productivity_mw_per_m3s` is present for a non-FPHA entry it must be finite and
//!   non-negative (`>= 0.0`). A value of `0.0` is accepted as a planned-outage marker.
//!
//! Deferred validations (not performed here):
//!
//! - `hydro_id` existence in the hydro registry — Layer 3.
//! - Cross-validation that `source: "precomputed"` hydros have FPHA hyperplanes — Layer 3/5.
//! - That exactly one source (JSON or parquet) provides `productivity_mw_per_m3s` for each
//!   `(hydro, stage)` pair — `validation::productivity_resolution`.

use cobre_core::EntityId;
use serde::Deserialize;
use std::collections::HashSet;
use std::path::Path;

use crate::LoadError;

/// Production model configuration for one hydro plant.
///
/// Loaded from `system/hydro_production_models.json`. Specifies how the hydro
/// production function (HPF) model is selected across stages or seasons.
///
/// # Examples
///
/// ```
/// use cobre_io::extensions::{ProductionModelConfig, SelectionMode};
/// use cobre_core::EntityId;
///
/// let config = ProductionModelConfig {
///     hydro_id: EntityId::from(0),
///     selection_mode: SelectionMode::StageRanges {
///         ranges: vec![],
///     },
/// };
/// assert_eq!(config.hydro_id, EntityId::from(0));
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ProductionModelConfig {
    /// Hydro plant this configuration applies to.
    pub hydro_id: EntityId,
    /// How the model variant is selected for each stage.
    pub selection_mode: SelectionMode,
}

/// Parsed contents of `system/hydro_production_models.json`.
///
/// Bundles the per-hydro production model configs with the optional file-level
/// FPHA plane-reduction block. `plane_reduction` is `None` when the file carries
/// no `fpha_plane_reduction` key (the off-by-default case).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ProductionModelFile {
    /// Per-hydro production model configurations, sorted by `hydro_id` ascending.
    pub configs: Vec<ProductionModelConfig>,
    /// File-level similar-hyperplane reduction config, applied uniformly to
    /// every plant. `None` ⇒ no reduction.
    pub plane_reduction: Option<PlaneReductionConfig>,
}

/// Model selection strategy for a hydro plant.
///
/// The two variants are mutually exclusive within a single hydro entry.
#[derive(Debug, Clone, PartialEq)]
pub enum SelectionMode {
    /// Models are selected by stage ID ranges.
    StageRanges {
        /// Ordered list of stage range descriptors.
        ranges: Vec<StageRange>,
    },
    /// Models are selected by season index, with a fallback default.
    Seasonal {
        /// Fallback model for seasons not listed in `seasons`.
        default_model: String,
        /// Season-specific overrides.
        seasons: Vec<SeasonConfig>,
    },
}

/// A stage range descriptor for the `stage_ranges` selection mode.
#[derive(Debug, Clone, PartialEq)]
pub struct StageRange {
    /// First stage (inclusive) to which this entry applies.
    pub start_stage_id: i32,
    /// Last stage (inclusive) to which this entry applies. `None` means "until end of horizon".
    pub end_stage_id: Option<i32>,
    /// Model name: `"constant_productivity"`, `"linearized_head"`, or `"fpha"`.
    pub model: String,
    /// FPHA configuration, required when `model == "fpha"`.
    pub fpha_config: Option<FphaColumnLayout>,
    /// Optional reference operating volume, a sibling of `fpha_config`. `None`
    /// when not declared; a default is applied later in resolution, not here.
    pub reference_volume: Option<ReferenceVolume>,
    /// Per-stage productivity coefficient [MW/(m³/s)]; see the module doc for the
    /// optional / `0.0`-outage / `None`-for-fpha rules.
    pub productivity_mw_per_m3s: Option<f64>,
}

/// A season-specific model descriptor for the `seasonal` selection mode.
#[derive(Debug, Clone, PartialEq)]
pub struct SeasonConfig {
    /// Season index (0-based, matching `stages.json` season map).
    pub season_id: i32,
    /// Model name: `"constant_productivity"`, `"linearized_head"`, or `"fpha"`.
    pub model: String,
    /// FPHA configuration, required when `model == "fpha"`.
    pub fpha_config: Option<FphaColumnLayout>,
    /// Optional reference operating volume, a sibling of `fpha_config`. `None`
    /// when not declared; a default is applied later in resolution, not here.
    pub reference_volume: Option<ReferenceVolume>,
    /// Per-season productivity coefficient [MW/(m³/s)]; see the module doc for the
    /// optional / `0.0`-outage / `None`-for-fpha rules.
    pub productivity_mw_per_m3s: Option<f64>,
}

/// Configuration for the FPHA production function model.
#[derive(Debug, Clone, PartialEq)]
pub struct FphaColumnLayout {
    /// `"computed"` (fit from topology) or `"precomputed"` (from `fpha_hyperplanes.parquet`).
    pub source: String,
    /// Number of volume discretization points used when computing hyperplanes.
    pub volume_discretization_points: Option<i32>,
    /// Number of turbine flow discretization points used when computing hyperplanes.
    pub turbine_discretization_points: Option<i32>,
    /// Number of spillage discretization points used when computing hyperplanes.
    pub spillage_discretization_points: Option<i32>,
    /// Maximum number of planes per hydro after heuristic selection.
    pub max_planes_per_hydro: Option<i32>,
    /// Optional fitting window restricting the volume range for hyperplane computation.
    pub fitting_window: Option<FittingWindow>,
}

/// Similar-hyperplane reduction configuration for FPHA planes.
///
/// Selects how near-parallel / near-coincident FPHA planes are merged into
/// their mean hyperplane to shrink the LP. The two variants are mutually
/// exclusive (the input picks one `method`); both are applied uniformly to
/// every plant. Absent in the input means no reduction.
#[derive(Debug, Clone, PartialEq)]
pub enum PlaneReductionConfig {
    /// Merge planes whose normal vectors lie within `tolerance_deg` of each
    /// other. `tolerance_deg` is an angle in degrees, in `[0.0, 90.0]`.
    Angle {
        /// Maximum angle (degrees) between plane normals to treat them as
        /// parallel.
        tolerance_deg: f64,
    },
    /// Merge planes whose mean-squared distance over `n_samples` sampled points
    /// stays within `tolerance_pct`.
    Distance {
        /// Maximum relative MSE distance (fraction) to treat two planes as
        /// coincident.
        tolerance_pct: f64,
        /// Number of sample points used to estimate the distance.
        n_samples: u32,
    },
}

/// Volume fitting window for computed FPHA hyperplanes.
///
/// Absolute bounds (`volume_min_hm3` / `volume_max_hm3`) and percentile bounds
/// (`volume_min_percentile` / `volume_max_percentile`) are mutually exclusive.
#[derive(Debug, Clone, PartialEq)]
pub struct FittingWindow {
    /// Explicit minimum volume for fitting (hm³). Mutually exclusive with `volume_min_percentile`.
    pub volume_min_hm3: Option<f64>,
    /// Explicit maximum volume for fitting (hm³). Mutually exclusive with `volume_max_percentile`.
    pub volume_max_hm3: Option<f64>,
    /// Minimum as percentile of the operating range. Mutually exclusive with `volume_min_hm3`.
    pub volume_min_percentile: Option<f64>,
    /// Maximum as percentile of the operating range. Mutually exclusive with `volume_max_hm3`.
    pub volume_max_percentile: Option<f64>,
}

/// Reference operating volume for a stage range or season.
///
/// The input declares the reference volume either as an absolute storage value
/// (hm³) or as a percentile of the plant's operating range; the two are mutually
/// exclusive. Resolution of the percentile form to an absolute value happens in a
/// later stage, not here.
#[derive(Debug, Clone, PartialEq)]
pub enum ReferenceVolume {
    /// Absolute reference volume `[hm³]`. Finite and `> 0.0`.
    AbsoluteHm3(f64),
    /// Reference volume as a percentile of the operating range, in `[0.0, 1.0]`.
    Percentile(f64),
}

/// Per-hydro production model configuration loaded from
/// `system/hydro_production_models.json`.
///
/// Specifies how the hydro production function (HPF) model variant is selected
/// for each stage or season. Two selection modes are supported:
///
/// - `stage_ranges`: maps each stage to a model via explicit `[start, end]`
///   intervals.
/// - `seasonal`: maps each stage to a model via its season index, with a
///   fallback default.
///
/// Each hydro may appear at most once. Results are sorted by `hydro_id`
/// ascending.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RawProductionModelFile {
    /// JSON schema URI — informational, not validated.
    #[serde(rename = "$schema")]
    _schema: Option<String>,

    /// Array of per-hydro production model configurations. Each `hydro_id`
    /// must be unique.
    production_models: Vec<RawProductionModel>,

    /// Optional file-level FPHA plane-reduction block, applied uniformly to
    /// every plant. Absent ⇒ no reduction. Carries a `method` tag selecting
    /// the `angle` or `distance` reduction method and its tolerance.
    #[serde(default)]
    fpha_plane_reduction: Option<RawPlaneReductionConfig>,
}

/// Production model configuration for one hydro plant.
///
/// The `selection_mode` field discriminates between two layouts:
/// `stage_ranges` carries a stage-range array, while `seasonal` carries a
/// `default_model` plus a `seasons` override list.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
struct RawProductionModel {
    /// Hydro plant identifier. Must be unique within the file.
    hydro_id: i32,

    /// Tagged-union payload for the model selection.
    #[serde(flatten)]
    selection: RawSelectionMode,
}

/// Model selection layout for a hydro plant, discriminated by the
/// `selection_mode` JSON field.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(tag = "selection_mode", rename_all = "snake_case")]
enum RawSelectionMode {
    /// Stage-range selection: each stage maps to a model via explicit
    /// `[start, end]` ranges.
    StageRanges {
        /// Ordered list of stage range descriptors.
        stage_ranges: Vec<RawStageRange>,
    },
    /// Seasonal selection: each stage maps to a model via its season index.
    Seasonal {
        /// Fallback model for seasons not listed in `seasons`. One of
        /// `"constant_productivity"`, `"linearized_head"`, or `"fpha"`.
        default_model: String,
        /// Season-specific model overrides.
        seasons: Vec<RawSeasonConfig>,
    },
}

/// Stage range descriptor for the `stage_ranges` selection mode.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawStageRange {
    /// First stage (inclusive) to which this entry applies. Must be <=
    /// `end_stage_id` when `end_stage_id` is set.
    start_stage_id: i32,
    /// Last stage (inclusive) to which this entry applies. `null` = until end
    /// of horizon.
    end_stage_id: Option<i32>,
    /// Model name: `"constant_productivity"`, `"linearized_head"`, or `"fpha"`.
    model: String,
    /// FPHA configuration. Required when `model` is `"fpha"`. Absent or null
    /// otherwise.
    fpha_config: Option<RawFphaColumnLayout>,
    /// Reference operating volume for this stage range, a sibling of
    /// `fpha_config` (not nested). Set exactly one of `volume_hm3` (absolute,
    /// hm³) or `percentile` (`[0.0, 1.0]`). Absent or null = no reference volume
    /// declared.
    reference_volume: Option<RawReferenceVolume>,
    /// Per-stage productivity coefficient [MW/(m³/s)]. Optional for
    /// `"constant_productivity"` and `"linearized_head"` models; when absent or
    /// null the value is expected from `system/hydro_energy_productivity.parquet`.
    /// When present must be `> 0.0` and finite. Must be absent or null for `"fpha"`.
    productivity_mw_per_m3s: Option<f64>,
}

/// Season-specific model descriptor for the `seasonal` selection mode.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSeasonConfig {
    /// Season index (0-based, matching the `stages.json` season map).
    season_id: i32,
    /// Model name: `"constant_productivity"`, `"linearized_head"`, or `"fpha"`.
    model: String,
    /// FPHA configuration. Required when `model` is `"fpha"`. Absent or null
    /// otherwise.
    fpha_config: Option<RawFphaColumnLayout>,
    /// Reference operating volume for this season, a sibling of `fpha_config`
    /// (not nested). Set exactly one of `volume_hm3` (absolute, hm³) or
    /// `percentile` (`[0.0, 1.0]`). Absent or null = no reference volume
    /// declared.
    reference_volume: Option<RawReferenceVolume>,
    /// Per-season productivity coefficient [MW/(m³/s)]. Optional for
    /// `"constant_productivity"` and `"linearized_head"` models; when absent or
    /// null the value is expected from `system/hydro_energy_productivity.parquet`.
    /// When present must be `> 0.0` and finite. Must be absent or null for `"fpha"`.
    productivity_mw_per_m3s: Option<f64>,
}

/// Configuration for the FPHA production function model.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFphaColumnLayout {
    /// Hyperplane source: `"computed"` (fit from topology) or
    /// `"precomputed"` (from `fpha_hyperplanes.parquet`).
    source: String,
    /// Number of volume discretization points used when computing hyperplanes.
    /// Absent = algorithm default (5).
    volume_discretization_points: Option<i32>,
    /// Number of turbine flow discretization points used when computing
    /// hyperplanes. Absent = algorithm default (5).
    turbine_discretization_points: Option<i32>,
    /// Number of spillage discretization points used when computing
    /// hyperplanes. Absent = algorithm default (5).
    spillage_discretization_points: Option<i32>,
    /// Maximum number of planes per hydro after heuristic selection. Absent =
    /// algorithm default (10).
    max_planes_per_hydro: Option<i32>,
    /// Optional volume fitting window for hyperplane computation. Absent or
    /// null = full operating range.
    fitting_window: Option<RawFittingWindow>,
}

/// File-level FPHA plane-reduction block, discriminated by the `method` JSON
/// field.
///
/// An internally-tagged union: `{ "method": "angle", "tolerance_deg": <f64> }`
/// merges planes whose normals are within `tolerance_deg` degrees, while
/// `{ "method": "distance", "tolerance_pct": <f64>, "n_samples": <u32> }` merges
/// planes whose sampled mean-squared distance stays within `tolerance_pct`. The
/// tag selects exactly one method; `deny_unknown_fields` rejects a tolerance
/// field belonging to the other method.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
enum RawPlaneReductionConfig {
    /// Normal-vector angle method. Merges planes whose normals lie within
    /// `tolerance_deg` of each other.
    Angle {
        /// Maximum angle (degrees) between plane normals to treat them as
        /// parallel. Must be finite and in `[0.0, 90.0]` inclusive.
        tolerance_deg: f64,
    },
    /// Mean-squared-distance method. Merges planes whose sampled MSE distance
    /// stays within `tolerance_pct`.
    Distance {
        /// Maximum relative MSE distance (fraction) to treat two planes as
        /// coincident. Must be finite and `>= 0.0`.
        tolerance_pct: f64,
        /// Number of sample points used to estimate the distance. Must be `>= 1`.
        n_samples: u32,
    },
}

/// Volume fitting window restricting the range used for FPHA hyperplane
/// computation.
///
/// Absolute bounds (`volume_min_hm3` / `volume_max_hm3`) and percentile bounds
/// (`volume_min_percentile` / `volume_max_percentile`) are mutually exclusive:
/// set one pair or the other, not both for the same bound.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[allow(clippy::struct_field_names)]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFittingWindow {
    /// Explicit minimum volume for fitting [hm³]. Mutually exclusive with
    /// `volume_min_percentile`.
    volume_min_hm3: Option<f64>,
    /// Explicit maximum volume for fitting [hm³]. Mutually exclusive with
    /// `volume_max_percentile`.
    volume_max_hm3: Option<f64>,
    /// Minimum as a percentile of the operating range. Mutually exclusive
    /// with `volume_min_hm3`.
    volume_min_percentile: Option<f64>,
    /// Maximum as a percentile of the operating range. Mutually exclusive
    /// with `volume_max_hm3`.
    volume_max_percentile: Option<f64>,
}

/// Reference operating volume declared on a stage range or season.
///
/// Set exactly one of `volume_hm3` (absolute, hm³) or `percentile` (a fraction
/// of the operating range). The two are mutually exclusive; setting both, or
/// neither, is rejected during validation.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawReferenceVolume {
    /// Absolute reference volume [hm³]. Mutually exclusive with `percentile`.
    /// When present must be finite and `> 0.0`.
    volume_hm3: Option<f64>,
    /// Reference volume as a percentile of the operating range. Mutually
    /// exclusive with `volume_hm3`. When present must be finite and in
    /// `[0.0, 1.0]`.
    percentile: Option<f64>,
}

// ── Parser ────────────────────────────────────────────────────────────────────

/// Parse `system/hydro_production_models.json` into a [`ProductionModelFile`].
///
/// # Errors
///
/// | Condition                                                   | Error variant              |
/// |------------------------------------------------------------ |--------------------------- |
/// | File not found or permission denied                         | [`LoadError::IoError`]     |
/// | Invalid JSON syntax or unrecognised `selection_mode`        | [`LoadError::ParseError`] / [`LoadError::SchemaError`] |
/// | Duplicate `hydro_id`                                        | [`LoadError::SchemaError`] |
/// | `start_stage_id > end_stage_id` (when `end_stage_id` set)  | [`LoadError::SchemaError`] |
/// | Both absolute and percentile fitting bounds set             | [`LoadError::SchemaError`] |
/// | `fpha_plane_reduction` tolerance out of range / `n_samples < 1` | [`LoadError::SchemaError`] |
///
/// # Examples
///
/// ```no_run
/// use cobre_io::extensions::parse_production_models;
/// use std::path::Path;
///
/// let file = parse_production_models(Path::new("system/hydro_production_models.json"))
///     .expect("valid production models file");
/// println!("loaded {} hydro model configs", file.configs.len());
/// ```
pub fn parse_production_models(path: &Path) -> Result<ProductionModelFile, LoadError> {
    let raw_text = std::fs::read_to_string(path).map_err(|e| LoadError::io(path, e))?;

    let raw: RawProductionModelFile = serde_json::from_str(&raw_text).map_err(|e| {
        let msg = e.to_string();
        if msg.contains("unknown variant") {
            LoadError::SchemaError {
                path: path.to_path_buf(),
                field: "selection_mode".to_string(),
                message: msg,
            }
        } else {
            LoadError::parse(path, msg)
        }
    })?;

    validate_production_models(
        &raw.production_models,
        raw.fpha_plane_reduction.as_ref(),
        path,
    )?;

    let mut configs: Vec<ProductionModelConfig> = raw
        .production_models
        .into_iter()
        .map(convert_production_model)
        .collect();

    configs.sort_by_key(|c| c.hydro_id.0);

    let plane_reduction = raw
        .fpha_plane_reduction
        .as_ref()
        .map(convert_plane_reduction);

    Ok(ProductionModelFile {
        configs,
        plane_reduction,
    })
}

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

/// Validate all cross-entry and per-entry constraints on raw production model data.
fn validate_production_models(
    models: &[RawProductionModel],
    plane_reduction: Option<&RawPlaneReductionConfig>,
    path: &Path,
) -> Result<(), LoadError> {
    let mut seen_ids: HashSet<i32> = HashSet::new();

    for (entry_idx, model) in models.iter().enumerate() {
        if !seen_ids.insert(model.hydro_id) {
            return Err(LoadError::SchemaError {
                path: path.to_path_buf(),
                field: format!("production_models[{entry_idx}].hydro_id"),
                message: format!(
                    "duplicate hydro_id {} — each hydro may appear at most once",
                    model.hydro_id
                ),
            });
        }

        match &model.selection {
            RawSelectionMode::StageRanges { stage_ranges } => {
                for (range_idx, range) in stage_ranges.iter().enumerate() {
                    validate_stage_range(range, entry_idx, range_idx, path)?;
                }
            }
            RawSelectionMode::Seasonal { seasons, .. } => {
                for (season_idx, season) in seasons.iter().enumerate() {
                    let field_base = format!(
                        "production_models[{entry_idx}].seasons[{season_idx}].productivity_mw_per_m3s"
                    );

                    if season.model == "fpha" && season.productivity_mw_per_m3s.is_some() {
                        return Err(LoadError::SchemaError {
                            path: path.to_path_buf(),
                            field: field_base,
                            message: "productivity_mw_per_m3s must not be set when model is 'fpha'"
                                .to_string(),
                        });
                    }

                    // `0.0` is a planned-outage marker; reject only negative or non-finite.
                    if season.model != "fpha"
                        && let Some(val) = season.productivity_mw_per_m3s
                        && (val < 0.0 || !val.is_finite())
                    {
                        return Err(LoadError::SchemaError {
                            path: path.to_path_buf(),
                            field: field_base,
                            message: format!(
                                "productivity_mw_per_m3s must be finite and non-negative, got {val}"
                            ),
                        });
                    }

                    if let Some(cfg) = &season.fpha_config {
                        validate_fitting_window(
                            cfg,
                            &format!(
                                "production_models[{entry_idx}].seasons[{season_idx}].fpha_config.fitting_window"
                            ),
                            path,
                        )?;
                    }

                    if let Some(rv) = &season.reference_volume {
                        validate_reference_volume(
                            rv,
                            &format!(
                                "production_models[{entry_idx}].seasons[{season_idx}].reference_volume"
                            ),
                            path,
                        )?;
                    }
                }
            }
        }
    }

    if let Some(reduction) = plane_reduction {
        validate_plane_reduction(reduction, path)?;
    }

    Ok(())
}

/// Validate one stage range descriptor.
fn validate_stage_range(
    range: &RawStageRange,
    entry_idx: usize,
    range_idx: usize,
    path: &Path,
) -> Result<(), LoadError> {
    if let Some(end) = range.end_stage_id
        && range.start_stage_id > end
    {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: format!(
                "production_models[{entry_idx}].stage_ranges[{range_idx}].start_stage_id"
            ),
            message: format!(
                "stage_ranges entry has start_stage_id ({}) > end_stage_id ({}); \
                     start_stage_id must be <= end_stage_id",
                range.start_stage_id, end
            ),
        });
    }

    let field_base =
        format!("production_models[{entry_idx}].stage_ranges[{range_idx}].productivity_mw_per_m3s");

    if range.model == "fpha" && range.productivity_mw_per_m3s.is_some() {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_base,
            message: "productivity_mw_per_m3s must not be set when model is 'fpha'".to_string(),
        });
    }

    // `0.0` is a planned-outage marker; reject only negative or non-finite.
    if range.model != "fpha"
        && let Some(val) = range.productivity_mw_per_m3s
        && (val < 0.0 || !val.is_finite())
    {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_base,
            message: format!("productivity_mw_per_m3s must be finite and non-negative, got {val}"),
        });
    }

    if let Some(cfg) = &range.fpha_config {
        validate_fitting_window(
            cfg,
            &format!(
                "production_models[{entry_idx}].stage_ranges[{range_idx}].fpha_config.fitting_window"
            ),
            path,
        )?;
    }

    if let Some(rv) = &range.reference_volume {
        validate_reference_volume(
            rv,
            &format!("production_models[{entry_idx}].stage_ranges[{range_idx}].reference_volume"),
            path,
        )?;
    }

    Ok(())
}

/// Reject a fitting window that sets an absolute bound and its percentile
/// counterpart together (the two are mutually exclusive per bound).
fn validate_fitting_window(
    cfg: &RawFphaColumnLayout,
    field_prefix: &str,
    path: &Path,
) -> Result<(), LoadError> {
    let Some(fw) = &cfg.fitting_window else {
        return Ok(());
    };

    if fw.volume_min_hm3.is_some() && fw.volume_min_percentile.is_some() {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: "mutually exclusive bounds: volume_min_hm3 and volume_min_percentile \
                      cannot both be set; use absolute bounds OR percentiles, not both"
                .to_string(),
        });
    }

    if fw.volume_max_hm3.is_some() && fw.volume_max_percentile.is_some() {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: "mutually exclusive bounds: volume_max_hm3 and volume_max_percentile \
                      cannot both be set; use absolute bounds OR percentiles, not both"
                .to_string(),
        });
    }

    Ok(())
}

/// Validate a reference-volume entry's absolute-XOR-percentile invariant.
///
/// A value that passes here has exactly one of `volume_hm3` / `percentile` set —
/// `convert_reference_volume` relies on this to disambiguate.
fn validate_reference_volume(
    rv: &RawReferenceVolume,
    field_prefix: &str,
    path: &Path,
) -> Result<(), LoadError> {
    if rv.volume_hm3.is_some() && rv.percentile.is_some() {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: "mutually exclusive fields: volume_hm3 and percentile cannot both be \
                      set; use an absolute volume OR a percentile, not both"
                .to_string(),
        });
    }

    if rv.volume_hm3.is_none() && rv.percentile.is_none() {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: "reference_volume must set exactly one of volume_hm3 or percentile"
                .to_string(),
        });
    }

    if let Some(vol) = rv.volume_hm3
        && (!vol.is_finite() || vol <= 0.0)
    {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: format!("volume_hm3 must be finite and > 0.0, got {vol}"),
        });
    }

    if let Some(pct) = rv.percentile
        && (!pct.is_finite() || !(0.0..=1.0).contains(&pct))
    {
        return Err(LoadError::SchemaError {
            path: path.to_path_buf(),
            field: field_prefix.to_string(),
            message: format!("percentile must be finite and in [0.0, 1.0], got {pct}"),
        });
    }

    Ok(())
}

/// Validate the per-method tolerance ranges of the file-level plane-reduction
/// block.
///
/// Method exclusivity is already enforced structurally by serde's `method` tag
/// and `deny_unknown_fields`; this is the config-layer range check.
fn validate_plane_reduction(
    reduction: &RawPlaneReductionConfig,
    path: &Path,
) -> Result<(), LoadError> {
    match reduction {
        RawPlaneReductionConfig::Angle { tolerance_deg } => {
            if !tolerance_deg.is_finite() || *tolerance_deg < 0.0 || *tolerance_deg > 90.0 {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: "fpha_plane_reduction".to_string(),
                    message: format!(
                        "angle tolerance_deg must be finite and in [0, 90], got {tolerance_deg}"
                    ),
                });
            }
        }
        RawPlaneReductionConfig::Distance {
            tolerance_pct,
            n_samples,
        } => {
            if !tolerance_pct.is_finite() || *tolerance_pct < 0.0 {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: "fpha_plane_reduction".to_string(),
                    message: format!(
                        "distance tolerance_pct must be finite and >= 0, got {tolerance_pct}"
                    ),
                });
            }
            if *n_samples < 1 {
                return Err(LoadError::SchemaError {
                    path: path.to_path_buf(),
                    field: "fpha_plane_reduction".to_string(),
                    message: format!("distance n_samples must be >= 1, got {n_samples}"),
                });
            }
        }
    }

    Ok(())
}

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

/// Convert a validated raw production model entry into the public type.
fn convert_production_model(raw: RawProductionModel) -> ProductionModelConfig {
    let selection_mode = match raw.selection {
        RawSelectionMode::StageRanges { stage_ranges } => SelectionMode::StageRanges {
            ranges: stage_ranges.into_iter().map(convert_stage_range).collect(),
        },
        RawSelectionMode::Seasonal {
            default_model,
            seasons,
        } => SelectionMode::Seasonal {
            default_model,
            seasons: seasons.into_iter().map(convert_season_config).collect(),
        },
    };

    ProductionModelConfig {
        hydro_id: EntityId::from(raw.hydro_id),
        selection_mode,
    }
}

fn convert_stage_range(raw: RawStageRange) -> StageRange {
    StageRange {
        start_stage_id: raw.start_stage_id,
        end_stage_id: raw.end_stage_id,
        model: raw.model,
        fpha_config: raw.fpha_config.map(convert_fpha_column_layout),
        reference_volume: raw.reference_volume.as_ref().map(convert_reference_volume),
        productivity_mw_per_m3s: raw.productivity_mw_per_m3s,
    }
}

fn convert_season_config(raw: RawSeasonConfig) -> SeasonConfig {
    SeasonConfig {
        season_id: raw.season_id,
        model: raw.model,
        fpha_config: raw.fpha_config.map(convert_fpha_column_layout),
        reference_volume: raw.reference_volume.as_ref().map(convert_reference_volume),
        productivity_mw_per_m3s: raw.productivity_mw_per_m3s,
    }
}

/// Pick the public variant from whichever field is `Some`.
///
/// `validate_reference_volume` guarantees exactly one field is `Some`, so the
/// `volume_hm3` priority is unambiguous and the `unwrap_or` default is
/// unreachable — it only keeps the conversion total without a panic.
fn convert_reference_volume(raw: &RawReferenceVolume) -> ReferenceVolume {
    match raw.volume_hm3 {
        Some(vol) => ReferenceVolume::AbsoluteHm3(vol),
        None => ReferenceVolume::Percentile(raw.percentile.unwrap_or_default()),
    }
}

fn convert_fpha_column_layout(raw: RawFphaColumnLayout) -> FphaColumnLayout {
    FphaColumnLayout {
        source: raw.source,
        volume_discretization_points: raw.volume_discretization_points,
        turbine_discretization_points: raw.turbine_discretization_points,
        spillage_discretization_points: raw.spillage_discretization_points,
        max_planes_per_hydro: raw.max_planes_per_hydro,
        fitting_window: raw.fitting_window.map(|fw| FittingWindow {
            volume_min_hm3: fw.volume_min_hm3,
            volume_max_hm3: fw.volume_max_hm3,
            volume_min_percentile: fw.volume_min_percentile,
            volume_max_percentile: fw.volume_max_percentile,
        }),
    }
}

fn convert_plane_reduction(raw: &RawPlaneReductionConfig) -> PlaneReductionConfig {
    match raw {
        RawPlaneReductionConfig::Angle { tolerance_deg } => PlaneReductionConfig::Angle {
            tolerance_deg: *tolerance_deg,
        },
        RawPlaneReductionConfig::Distance {
            tolerance_pct,
            n_samples,
        } => PlaneReductionConfig::Distance {
            tolerance_pct: *tolerance_pct,
            n_samples: *n_samples,
        },
    }
}

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

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

    // ── helpers ───────────────────────────────────────────────────────────────

    fn write_json(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    // ── AC: valid stage_ranges mode ───────────────────────────────────────────

    /// Given a valid file with one hydro using `stage_ranges` mode, returns Ok with
    /// one entry containing the correct SelectionMode variant.
    #[test]
    fn test_valid_stage_ranges_mode() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "fpha",
                "fpha_config": {
                  "source": "computed",
                  "volume_discretization_points": 7,
                  "turbine_discretization_points": 15,
                  "fitting_window": { "volume_min_hm3": null, "volume_max_hm3": null }
                }
              },
              {
                "start_stage_id": 25, "end_stage_id": null,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.9
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;

        assert_eq!(models.len(), 1);
        let m = &models[0];
        assert_eq!(m.hydro_id, EntityId::from(0));
        match &m.selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert_eq!(ranges.len(), 2);
                assert_eq!(ranges[0].start_stage_id, 0);
                assert_eq!(ranges[0].end_stage_id, Some(24));
                assert_eq!(ranges[0].model, "fpha");
                let fpha = ranges[0].fpha_config.as_ref().unwrap();
                assert_eq!(fpha.source, "computed");
                assert_eq!(fpha.volume_discretization_points, Some(7));
                assert_eq!(fpha.turbine_discretization_points, Some(15));
                // Fitting window present but both bounds null
                let fw = fpha.fitting_window.as_ref().unwrap();
                assert!(fw.volume_min_hm3.is_none());
                assert!(fw.volume_max_hm3.is_none());

                assert_eq!(ranges[1].start_stage_id, 25);
                assert!(ranges[1].end_stage_id.is_none());
                assert_eq!(ranges[1].model, "constant_productivity");
                assert!(ranges[1].fpha_config.is_none());
                assert_eq!(ranges[1].productivity_mw_per_m3s, Some(0.9));
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    // ── AC: valid seasonal mode ───────────────────────────────────────────────

    /// Given a valid file with one hydro using `seasonal` mode, returns Ok with one
    /// entry containing the correct SelectionMode variant with default_model and seasons.
    #[test]
    fn test_valid_seasonal_mode() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 5,
            "selection_mode": "seasonal",
            "default_model": "linearized_head",
            "seasons": [
              {
                "season_id": 0,
                "model": "fpha",
                "fpha_config": { "source": "computed", "volume_discretization_points": 5 }
              },
              {
                "season_id": 1, "model": "fpha",
                "fpha_config": { "source": "computed", "turbine_discretization_points": 10 }
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;

        assert_eq!(models.len(), 1);
        let m = &models[0];
        assert_eq!(m.hydro_id, EntityId::from(5));
        match &m.selection_mode {
            SelectionMode::Seasonal {
                default_model,
                seasons,
            } => {
                assert_eq!(default_model, "linearized_head");
                assert_eq!(seasons.len(), 2);
                assert_eq!(seasons[0].season_id, 0);
                assert_eq!(seasons[0].model, "fpha");
                let fpha0 = seasons[0].fpha_config.as_ref().unwrap();
                assert_eq!(fpha0.source, "computed");
                assert_eq!(fpha0.volume_discretization_points, Some(5));
                assert!(fpha0.turbine_discretization_points.is_none());

                assert_eq!(seasons[1].season_id, 1);
                let fpha1 = seasons[1].fpha_config.as_ref().unwrap();
                assert_eq!(fpha1.turbine_discretization_points, Some(10));
                assert!(fpha1.volume_discretization_points.is_none());
            }
            other => panic!("expected Seasonal, got: {other:?}"),
        }
    }

    // ── AC: mixed — one stage_ranges, one seasonal ────────────────────────────

    /// Given a valid file with one hydro in stage_ranges mode and one in seasonal mode,
    /// returns Ok with 2 entries sorted by hydro_id.
    #[test]
    fn test_mixed_modes_sorted_by_hydro_id() {
        let json = r#"{
          "production_models": [
            {
              "hydro_id": 10,
              "selection_mode": "seasonal",
              "default_model": "constant_productivity",
              "seasons": []
            },
            {
              "hydro_id": 3,
              "selection_mode": "stage_ranges",
              "stage_ranges": [
                {
                  "start_stage_id": 0, "end_stage_id": null,
                  "model": "constant_productivity",
                  "productivity_mw_per_m3s": 0.8
                }
              ]
            }
          ]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;

        assert_eq!(models.len(), 2);
        // Sorted by hydro_id ascending
        assert_eq!(models[0].hydro_id, EntityId::from(3));
        assert_eq!(models[1].hydro_id, EntityId::from(10));
        assert!(matches!(
            models[0].selection_mode,
            SelectionMode::StageRanges { .. }
        ));
        assert!(matches!(
            models[1].selection_mode,
            SelectionMode::Seasonal { .. }
        ));
    }

    // ── AC: duplicate hydro_id -> SchemaError ─────────────────────────────────

    /// Duplicate hydro_id in the file -> SchemaError mentioning the duplicate.
    #[test]
    fn test_duplicate_hydro_id() {
        let json = r#"{
          "production_models": [
            {
              "hydro_id": 5,
              "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "fpha", "fpha_config": { "source": "computed" } }]
            },
            {
              "hydro_id": 5,
              "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }]
            }
          ]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("hydro_id"),
                    "field should mention hydro_id, got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should mention duplicate, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: invalid stage range (start > end) -> SchemaError ─────────────────

    /// stage_ranges with start_stage_id > end_stage_id -> SchemaError with
    /// field containing "stage_ranges" and message containing "start_stage_id".
    #[test]
    fn test_invalid_stage_range_start_greater_than_end() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 25, "end_stage_id": 10,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.9
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("stage_ranges"),
                    "field should contain 'stage_ranges', got: {field}"
                );
                assert!(
                    message.contains("start_stage_id"),
                    "message should contain 'start_stage_id', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── AC: equal start == end is valid ───────────────────────────────────────

    /// start_stage_id == end_stage_id is valid (single-stage range).
    #[test]
    fn test_stage_range_start_equals_end_is_valid() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 5, "end_stage_id": 5,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.9
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let result = parse_production_models(f.path());
        assert!(
            result.is_ok(),
            "equal start==end should be valid, got: {result:?}"
        );
    }

    // ── AC: mutually exclusive fitting window -> SchemaError ─────────────────

    /// Both volume_min_hm3 and volume_min_percentile set -> SchemaError with
    /// message containing "mutually exclusive".
    #[test]
    fn test_mutually_exclusive_fitting_window_min() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "fpha",
              "fpha_config": {
                "source": "computed",
                "fitting_window": {
                  "volume_min_hm3": 1000.0,
                  "volume_max_hm3": null,
                  "volume_min_percentile": 0.1,
                  "volume_max_percentile": null
                }
              }
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("mutually exclusive"),
                    "message should contain 'mutually exclusive', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Both volume_max_hm3 and volume_max_percentile set -> SchemaError with
    /// message containing "mutually exclusive".
    #[test]
    fn test_mutually_exclusive_fitting_window_max() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "fpha",
              "fpha_config": {
                "source": "computed",
                "fitting_window": {
                  "volume_min_hm3": null,
                  "volume_max_hm3": 8000.0,
                  "volume_min_percentile": null,
                  "volume_max_percentile": 0.9
                }
              }
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("mutually exclusive"),
                    "message should contain 'mutually exclusive', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Both absolute and percentile set in seasonal mode -> SchemaError.
    #[test]
    fn test_mutually_exclusive_fitting_window_seasonal() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 1,
            "selection_mode": "seasonal",
            "default_model": "constant_productivity",
            "seasons": [{
              "season_id": 0,
              "model": "fpha",
              "fpha_config": {
                "source": "computed",
                "fitting_window": {
                  "volume_min_hm3": 500.0,
                  "volume_min_percentile": 0.2
                }
              }
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        assert!(
            matches!(err, LoadError::SchemaError { .. }),
            "expected SchemaError, got: {err:?}"
        );
    }

    // ── AC: None path wrapper returns empty vec ───────────────────────────────
    // (tested in extensions/mod.rs — see load_production_models)

    // ── AC: file not found -> IoError ────────────────────────────────────────

    /// Non-existent path -> IoError.
    #[test]
    fn test_file_not_found() {
        let path = Path::new("/nonexistent/path/hydro_production_models.json");
        let err = parse_production_models(path).unwrap_err();
        match &err {
            LoadError::IoError { path: p, .. } => {
                assert_eq!(p, path);
            }
            other => panic!("expected IoError, got: {other:?}"),
        }
    }

    // ── AC: unknown selection_mode -> SchemaError ─────────────────────────────

    /// Unknown selection_mode -> SchemaError (tagged union deserialization failure).
    #[test]
    fn test_unknown_selection_mode() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "unknown_mode"
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        assert!(
            matches!(err, LoadError::SchemaError { .. }),
            "expected SchemaError for unknown selection_mode, got: {err:?}"
        );
    }

    // ── AC: empty production_models array -> Ok(vec![]) ──────────────────────

    /// An empty `production_models` array deserialises to `Ok(Vec::new())`.
    #[test]
    fn test_empty_array_returns_empty_vec() {
        let json = r#"{ "production_models": [] }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        assert!(models.is_empty());
    }

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

    /// Reordering the entries in the JSON does not change the output ordering.
    #[test]
    fn test_declaration_order_invariance() {
        let json_asc = r#"{
          "production_models": [
            { "hydro_id": 1, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] },
            { "hydro_id": 5, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] },
            { "hydro_id": 99, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] }
          ]
        }"#;
        let json_desc = r#"{
          "production_models": [
            { "hydro_id": 99, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] },
            { "hydro_id": 5, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] },
            { "hydro_id": 1, "selection_mode": "stage_ranges",
              "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "constant_productivity", "productivity_mw_per_m3s": 0.9 }] }
          ]
        }"#;
        let f_asc = write_json(json_asc);
        let f_desc = write_json(json_desc);
        let models_asc = parse_production_models(f_asc.path()).unwrap().configs;
        let models_desc = parse_production_models(f_desc.path()).unwrap().configs;

        let ids_asc: Vec<i32> = models_asc.iter().map(|m| m.hydro_id.0).collect();
        let ids_desc: Vec<i32> = models_desc.iter().map(|m| m.hydro_id.0).collect();
        assert_eq!(
            ids_asc, ids_desc,
            "output order must be hydro_id-sorted regardless of input"
        );
        assert_eq!(ids_asc, vec![1, 5, 99]);
    }

    // ── AC: fpha_config without fitting_window is valid ───────────────────────

    /// FPHA config with no fitting_window field at all is valid.
    #[test]
    fn test_fpha_config_without_fitting_window() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "fpha",
              "fpha_config": { "source": "precomputed" }
            }]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        assert_eq!(models.len(), 1);
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                let fpha = ranges[0].fpha_config.as_ref().unwrap();
                assert_eq!(fpha.source, "precomputed");
                assert!(fpha.fitting_window.is_none());
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    // ── productivity_mw_per_m3s tests ─────────────────────────────────────────

    /// `constant_productivity` stage range with a positive value parses OK and
    /// exposes `productivity_mw_per_m3s = Some(0.85)`.
    #[test]
    fn constant_productivity_requires_coefficient() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.85
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert_eq!(ranges[0].productivity_mw_per_m3s, Some(0.85));
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    /// Non-FPHA stage range with `productivity_mw_per_m3s` omitted parses to `Ok` with
    /// `productivity_mw_per_m3s: None`. The parquet override is expected to supply the value.
    #[test]
    fn test_non_fpha_stage_range_without_productivity_is_accepted() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "constant_productivity"
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert!(
                    ranges[0].productivity_mw_per_m3s.is_none(),
                    "expected None when field is omitted, got: {:?}",
                    ranges[0].productivity_mw_per_m3s
                );
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    /// Non-FPHA stage range with `productivity_mw_per_m3s: null` parses to `Ok` with
    /// `productivity_mw_per_m3s: None`. The parquet override is expected to supply the value.
    #[test]
    fn test_non_fpha_stage_range_with_null_productivity_is_accepted() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "linearized_head",
                "productivity_mw_per_m3s": null
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert!(
                    ranges[0].productivity_mw_per_m3s.is_none(),
                    "expected None when field is null, got: {:?}",
                    ranges[0].productivity_mw_per_m3s
                );
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    /// `fpha` stage range with `productivity_mw_per_m3s` set -> `SchemaError`
    /// with the exact message `"productivity_mw_per_m3s must not be set when model is 'fpha'"`.
    #[test]
    fn fpha_rejects_coefficient() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "fpha",
                "fpha_config": { "source": "computed" },
                "productivity_mw_per_m3s": 1.0
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("productivity_mw_per_m3s"),
                    "field should contain 'productivity_mw_per_m3s', got: {field}"
                );
                assert_eq!(
                    message, "productivity_mw_per_m3s must not be set when model is 'fpha'",
                    "message must match exactly"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Validation rejects non-positive `productivity_mw_per_m3s`.
    #[test]
    fn test_productivity_negative_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": -1.0
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        assert!(
            matches!(err, LoadError::SchemaError { .. }),
            "expected SchemaError, got: {err:?}"
        );
    }

    /// `productivity_mw_per_m3s = 0.0` is accepted as a planned-outage marker.
    #[test]
    fn test_productivity_zero_accepted() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.0
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let parsed = parse_production_models(f.path())
            .expect("zero productivity must be accepted as a planned-outage marker")
            .configs;
        let SelectionMode::StageRanges { ranges } = &parsed[0].selection_mode else {
            panic!("expected StageRanges");
        };
        assert_eq!(ranges[0].productivity_mw_per_m3s, Some(0.0));
    }

    /// Seasonal mode with `productivity_mw_per_m3s` parses correctly.
    #[test]
    fn test_seasonal_productivity_mw_per_m3s() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "seasonal",
            "default_model": "constant_productivity",
            "seasons": [
              {
                "season_id": 0,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": 0.75
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::Seasonal { seasons, .. } => {
                assert_eq!(seasons[0].productivity_mw_per_m3s, Some(0.75));
            }
            other => panic!("expected Seasonal, got: {other:?}"),
        }
    }

    /// Non-FPHA seasonal entry with `productivity_mw_per_m3s` omitted parses to `Ok` with
    /// `productivity_mw_per_m3s: None`. The parquet override is expected to supply the value.
    #[test]
    fn test_non_fpha_seasonal_without_productivity_is_accepted() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "seasonal",
            "default_model": "constant_productivity",
            "seasons": [
              {
                "season_id": 0,
                "model": "constant_productivity"
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::Seasonal { seasons, .. } => {
                assert!(
                    seasons[0].productivity_mw_per_m3s.is_none(),
                    "expected None when field is omitted, got: {:?}",
                    seasons[0].productivity_mw_per_m3s
                );
            }
            other => panic!("expected Seasonal, got: {other:?}"),
        }
    }

    /// Regression guard: FPHA stage range with `productivity_mw_per_m3s` set is still rejected.
    #[test]
    fn test_fpha_stage_range_with_productivity_still_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "fpha",
                "fpha_config": { "source": "computed" },
                "productivity_mw_per_m3s": 0.9
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("must not be set when model is 'fpha'"),
                    "message should mention fpha rejection, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// Regression guard: negative `productivity_mw_per_m3s` is still rejected when present.
    #[test]
    fn test_negative_productivity_still_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [
              {
                "start_stage_id": 0, "end_stage_id": 24,
                "model": "constant_productivity",
                "productivity_mw_per_m3s": -0.1
              }
            ]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("productivity_mw_per_m3s must be finite and non-negative"),
                    "message should mention non-negative requirement, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    // ── fpha_plane_reduction tests ────────────────────────────────────────────

    /// A file with no `fpha_plane_reduction` key parses to `plane_reduction == None`.
    #[test]
    fn test_plane_reduction_absent_is_none() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{ "start_stage_id": 0, "end_stage_id": null, "model": "fpha", "fpha_config": { "source": "computed" } }]
          }]
        }"#;
        let f = write_json(json);
        let file = parse_production_models(f.path()).unwrap();
        assert!(
            file.plane_reduction.is_none(),
            "absent block must resolve to None, got: {:?}",
            file.plane_reduction
        );
        assert_eq!(file.configs.len(), 1);
    }

    /// A valid `angle` block parses to `Some(Angle { tolerance_deg })`.
    #[test]
    fn test_plane_reduction_angle_valid() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "angle", "tolerance_deg": 5.0 }
        }"#;
        let f = write_json(json);
        let file = parse_production_models(f.path()).unwrap();
        assert_eq!(
            file.plane_reduction,
            Some(PlaneReductionConfig::Angle { tolerance_deg: 5.0 })
        );
    }

    /// A valid `distance` block parses to `Some(Distance { tolerance_pct, n_samples })`.
    #[test]
    fn test_plane_reduction_distance_valid() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "distance", "tolerance_pct": 0.5, "n_samples": 64 }
        }"#;
        let f = write_json(json);
        let file = parse_production_models(f.path()).unwrap();
        assert_eq!(
            file.plane_reduction,
            Some(PlaneReductionConfig::Distance {
                tolerance_pct: 0.5,
                n_samples: 64
            })
        );
    }

    /// `angle` with `tolerance_deg = 95.0` is rejected with a SchemaError naming the range.
    #[test]
    fn test_plane_reduction_angle_out_of_range() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "angle", "tolerance_deg": 95.0 }
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert_eq!(field, "fpha_plane_reduction");
                assert!(
                    message.contains("[0, 90]"),
                    "message should name the [0, 90] range, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// `distance` with negative `tolerance_pct` is rejected with a SchemaError.
    #[test]
    fn test_plane_reduction_distance_negative_tolerance() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "distance", "tolerance_pct": -1.0, "n_samples": 64 }
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert_eq!(field, "fpha_plane_reduction");
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// `distance` with `n_samples = 0` is rejected with a SchemaError.
    #[test]
    fn test_plane_reduction_distance_zero_samples() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "distance", "tolerance_pct": 0.5, "n_samples": 0 }
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, .. } => {
                assert_eq!(field, "fpha_plane_reduction");
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// A distance field on an `angle` method is rejected by serde `deny_unknown_fields`.
    #[test]
    fn test_plane_reduction_cross_method_field_rejected() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "angle", "tolerance_pct": 5.0 }
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        assert!(
            matches!(
                err,
                LoadError::SchemaError { .. } | LoadError::ParseError { .. }
            ),
            "cross-method field must be rejected, got: {err:?}"
        );
    }

    /// An `angle` method carrying BOTH its own required `tolerance_deg` AND the
    /// foreign `tolerance_pct` is rejected — isolating the `deny_unknown_fields`
    /// guarantee from the missing-required-field path (both fields are present,
    /// so the only rejection reason is the unknown `tolerance_pct`).
    #[test]
    fn test_plane_reduction_foreign_field_alongside_required_is_rejected() {
        let json = r#"{
          "production_models": [],
          "fpha_plane_reduction": { "method": "angle", "tolerance_deg": 2.0, "tolerance_pct": 5.0 }
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        assert!(
            matches!(
                err,
                LoadError::SchemaError { .. } | LoadError::ParseError { .. }
            ),
            "a foreign field alongside the required one must be rejected by deny_unknown_fields, got: {err:?}"
        );
    }

    // ── reference_volume ──────────────────────────────────────────────────────

    /// `{ volume_hm3 }` on a stage range parses to the absolute-volume variant.
    #[test]
    fn reference_volume_absolute_parses() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": { "volume_hm3": 1234.5 }
            }]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert_eq!(
                    ranges[0].reference_volume,
                    Some(ReferenceVolume::AbsoluteHm3(1234.5))
                );
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    /// `{ percentile }` on a stage range parses to the percentile variant.
    #[test]
    fn reference_volume_percentile_parses() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": { "percentile": 0.5 }
            }]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::StageRanges { ranges } => {
                assert_eq!(
                    ranges[0].reference_volume,
                    Some(ReferenceVolume::Percentile(0.5))
                );
            }
            other => panic!("expected StageRanges, got: {other:?}"),
        }
    }

    /// Both `volume_hm3` and `percentile` set (on a season entry) -> SchemaError
    /// whose message contains "mutually exclusive" and whose field names seasons.
    #[test]
    fn reference_volume_both_set_is_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "seasonal",
            "default_model": "constant_productivity",
            "seasons": [{
              "season_id": 0,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": { "volume_hm3": 1.0, "percentile": 0.5 }
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    message.contains("mutually exclusive"),
                    "message should contain 'mutually exclusive', got: {message}"
                );
                assert!(
                    field.contains("seasons"),
                    "field should name seasons, got: {field}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// An empty `reference_volume: {}` (neither field set) -> SchemaError.
    #[test]
    fn reference_volume_neither_set_is_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": {}
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("exactly one"),
                    "message should require exactly one field, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// `percentile` outside `[0.0, 1.0]` -> SchemaError naming the range.
    #[test]
    fn reference_volume_percentile_out_of_range_is_rejected() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 0,
            "selection_mode": "stage_ranges",
            "stage_ranges": [{
              "start_stage_id": 0, "end_stage_id": null,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": { "percentile": 1.5 }
            }]
          }]
        }"#;
        let f = write_json(json);
        let err = parse_production_models(f.path()).unwrap_err();
        match &err {
            LoadError::SchemaError { message, .. } => {
                assert!(
                    message.contains("[0.0, 1.0]"),
                    "message should cite the [0.0, 1.0] range, got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    /// `volume_hm3` of `0.0` (and negative) -> SchemaError.
    #[test]
    fn reference_volume_nonpositive_volume_is_rejected() {
        for bad in ["0.0", "-5.0"] {
            let json = format!(
                r#"{{
              "production_models": [{{
                "hydro_id": 0,
                "selection_mode": "stage_ranges",
                "stage_ranges": [{{
                  "start_stage_id": 0, "end_stage_id": null,
                  "model": "constant_productivity",
                  "productivity_mw_per_m3s": 0.9,
                  "reference_volume": {{ "volume_hm3": {bad} }}
                }}]
              }}]
            }}"#
            );
            let f = write_json(&json);
            let err = parse_production_models(f.path()).unwrap_err();
            match &err {
                LoadError::SchemaError { message, .. } => {
                    assert!(
                        message.contains("> 0.0"),
                        "message should require > 0.0, got: {message}"
                    );
                }
                other => panic!("expected SchemaError for volume_hm3={bad}, got: {other:?}"),
            }
        }
    }

    /// `{ volume_hm3 }` on a season entry parses to the absolute-volume variant.
    #[test]
    fn reference_volume_on_season_entry_parses() {
        let json = r#"{
          "production_models": [{
            "hydro_id": 7,
            "selection_mode": "seasonal",
            "default_model": "constant_productivity",
            "seasons": [{
              "season_id": 0,
              "model": "constant_productivity",
              "productivity_mw_per_m3s": 0.9,
              "reference_volume": { "volume_hm3": 800.0 }
            }]
          }]
        }"#;
        let f = write_json(json);
        let models = parse_production_models(f.path()).unwrap().configs;
        match &models[0].selection_mode {
            SelectionMode::Seasonal { seasons, .. } => {
                assert_eq!(
                    seasons[0].reference_volume,
                    Some(ReferenceVolume::AbsoluteHm3(800.0))
                );
            }
            other => panic!("expected Seasonal, got: {other:?}"),
        }
    }

    /// With the `schema` feature, the generated schema for `RawProductionModelFile`
    /// exposes a `reference_volume` property under both entry schemas.
    #[cfg(feature = "schema")]
    #[test]
    fn reference_volume_appears_in_generated_schema() {
        let schema = schemars::schema_for!(RawProductionModelFile);
        let value = serde_json::to_value(&schema).unwrap();
        let text = serde_json::to_string(&value).unwrap();
        assert!(
            text.contains("reference_volume"),
            "generated schema must expose the reference_volume property"
        );
    }
}