eeg-billing 0.20.0

Pure EEG/KWKG feed-in settlement for German energy markets — EEG 2017–2024 and § 7 KWKG 2023. Zero I/O, no float money.
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
//! Pure settlement formula — [`calculate_settlement`].

use crate::EuroAmount;
use crate::rounding::RoundMoney;
use rust_decimal::Decimal;
use rust_decimal::dec;

use crate::model::{SettleInput, SettleOutput, SettlePosition, SettlementStatus};
use crate::scheme::SettlementScheme;

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Round a settlement amount to 5 decimal places via [`EuroAmount`].
///
/// # Panics
///
/// Panics when the amount exceeds the `EuroAmount` range (≈ 9.2 × 10¹³ EUR).
/// This is the same contract as the `Decimal` arithmetic that produces the
/// amount — it panics on overflow one step earlier. No physical EEG
/// settlement can reach this range; reaching it means the input data is
/// corrupt, and a silently altered amount would be worse than the panic.
fn validated_eur(d: Decimal) -> Decimal {
    // `checked_from_decimal` is exact — it errors on excess precision rather than
    // rounding. This helper's job is to *round* the high-precision settlement
    // product down to the 5-dp money resolution, so it uses the explicit
    // `from_decimal_rounded`; the remaining error arm is a true range overflow,
    // which no physical EEG settlement can reach.
    EuroAmount::from_decimal_rounded(d, billing::RoundingStrategy::MidpointAwayFromZero)
        .map(crate::EuroAmount::into_decimal)
        .unwrap_or_else(|_| panic!("settlement amount {d} EUR exceeds the EuroAmount range"))
}

/// Build a single [`SettlePosition`] from its components.
fn pos(
    description: impl Into<String>,
    legal_basis: impl Into<String>,
    kwh: Decimal,
    rate_ct_kwh: Decimal,
) -> SettlePosition {
    let eur = validated_eur(kwh * rate_ct_kwh / Decimal::from(100));
    SettlePosition {
        description: description.into(),
        legal_basis: legal_basis.into(),
        kwh,
        rate_ct_kwh,
        eur,
    }
}

/// Sum `positions` to a total, returning `None` when the slice is empty.
fn total(positions: &[SettlePosition]) -> Option<Decimal> {
    if positions.is_empty() {
        None
    } else {
        Some(positions.iter().map(|p| p.eur).sum())
    }
}

/// §51b Satz 2 — whether §§ 51 and 51a are displaced for this settlement.
///
/// The displacement rides on § 51b applying at all: § 101 Abs. 2 Satz 1 puts
/// § 51b under a state-aid Genehmigungsvorbehalt and names no earlier version to
/// fall back on, so for a supply period before the approval § 51b reduces
/// nothing and §§ 51 and 51a govern the plant like any other.
fn sect51b_verdraengt_sect51(input: &SettleInput) -> bool {
    input.tariff_source.is_biogas_sect51b() && crate::version::sect51b_anwendbar(input.billing_date)
}

/// Whether §51 actually bites for this plant in this period.
///
/// Two independent gates: something has to have been fed in during a qualifying
/// negative-price period, and the plant must not be exempt on size / technology
/// grounds. The **run-length** gate (4-3-2-1 h, 6 h, or the first quarter-hour)
/// is not re-checked here — it is a property of the interval series and is
/// applied by [`crate::negativpreis::derive_negativpreis`], which is what
/// produced `kwh_during_negative_epex` in the first place.
///
/// `leistung_kwp` must be the **aggregated** plant capacity: §51 Abs. 2 Satz 2
/// applies §24 to the size test, so §24-linked capacity blocks count as one
/// plant. Passing a single block's capacity would let a 180 kWp plant split into
/// three 60 kWp blocks escape §51 entirely.
fn sect51_greift(
    kwh_during_negative_epex: Option<Decimal>,
    leistung_kwp: Option<Decimal>,
    regime: crate::negativpreis::NegativpreisRegime,
    erzeugungsart: Option<crate::technology::ErzeugungsArt>,
    has_imesys: bool,
    ist_pilotwindanlage: bool,
    ist_biogas_sect51b: bool,
) -> bool {
    // §51b Satz 2: „Die §§ 51 und 51a sind auf diese Anlagen nicht anzuwenden."
    // A biogas Ausschreibungsanlage is reduced by §51b's own 2-ct threshold
    // instead, so §51 must not also bite.
    if ist_biogas_sect51b {
        return false;
    }
    if kwh_during_negative_epex.is_none_or(|k| k <= Decimal::ZERO) {
        return false;
    }
    !regime.ist_befreit(leistung_kwp, erzeugungsart, has_imesys, ist_pilotwindanlage)
}

/// §52 Abs. 5 EEG 2023 — the Pflichtzahlung after the per-Kalendermonat cap.
///
/// „Wenn in demselben Kalendermonat Zahlungen aufgrund von mehreren
/// Pflichtverstößen nach Absatz 1 geleistet werden müssen, sind die Zahlungen
/// nach den Absätzen 2 bis 4 insgesamt auf 10 Euro pro Kilowatt installierter
/// Leistung der Anlage und Kalendermonat begrenzt."
///
/// The cap binds **each** calendar month on its own. Summing first and capping
/// against ten euros times a month count lets a month that stays under the
/// ceiling pay for one that runs over it, which the words „und Kalendermonat"
/// do not allow: a month carrying one 2-€/kW violation has 8 €/kW of unused
/// ceiling, and that headroom is not transferable.
///
/// So each violation is spread over the calendar months it actually runs in,
/// the months are capped one by one, and the capped months are summed.
///
/// A violation with no [`beginn`](crate::Pflichtverstoss::beginn) cannot be
/// placed in the calendar. It is laid down from the earliest month any dated
/// violation occupies, which makes it as concurrent with the rest as its
/// duration allows — the placement that maximises the overlap, and therefore the
/// capping, is the one that cannot overcharge the operator.
fn sect52_abs5_gedeckelt(verstoesse: &[&crate::model::Pflichtverstoss]) -> Decimal {
    use std::collections::BTreeMap;

    // §52 Abs. 5 caps „pro Kilowatt installierter Leistung der Anlage" — one
    // plant, one capacity. Violations carrying different figures are a caller
    // error; the largest is the one that cannot cap below the statutory ceiling.
    let leistung_kw = verstoesse
        .iter()
        .map(|v| v.leistung_kw)
        .fold(Decimal::ZERO, Decimal::max);
    let monatsdeckel = dec!(10) * leistung_kw;

    let monatsschluessel = |d: time::Date| d.year() * 12 + (d.month() as i32 - 1);
    let erster_datierter = verstoesse
        .iter()
        .filter_map(|v| v.beginn)
        .map(monatsschluessel)
        .min()
        .unwrap_or(0);

    let mut je_monat: BTreeMap<i32, Decimal> = BTreeMap::new();
    for v in verstoesse {
        let (satz_eur, monate) = crate::foerderdauer::pflichtzahlung_je_monat(v);
        if monate == 0 {
            continue;
        }
        let start = v.beginn.map_or(erster_datierter, monatsschluessel);
        for offset in 0..i32::try_from(monate).unwrap_or(i32::MAX) {
            *je_monat.entry(start + offset).or_default() += satz_eur;
        }
    }

    je_monat
        .into_values()
        .map(|monat| monat.min(monatsdeckel))
        .sum()
}

/// Apply §51 EEG deduction: subtract kWh during negative-price hours.
/// Only called after `should_apply_negativpreis` returns `true`.
fn apply_negativpreis(kwh: Decimal, negative_kwh: Decimal) -> Decimal {
    (kwh - negative_kwh).max(Decimal::ZERO)
}

/// The plant capacity the size-dependent rules test against.
///
/// §51 Abs. 2 Satz 2 EEG 2023 applies §24 to the §51 size test, so §24-linked
/// capacity blocks are one plant. Returns `None` only when nothing is known.
fn aggregierte_leistung_kwp(input: &SettleInput) -> Option<Decimal> {
    if input.capacity_blocks.is_empty() {
        return input.leistung_kwp;
    }
    let blocks: Decimal = input.capacity_blocks.iter().map(|b| b.leistung_kwp).sum();
    Some(input.leistung_kwp.unwrap_or(Decimal::ZERO) + blocks)
}

/// Resolve the effective §36h wind onshore Korrekturfaktor.
///
/// Priority:
/// 1. explicit `wind_korrekturfaktor` override (always wins)
/// 2. `wind_standort.korrekturfaktor` (struct-based)
/// 3. `None` — no correction applied
fn resolve_wind_korrekturfaktor(
    wind_korrekturfaktor: Option<Decimal>,
    wind_standort: Option<&crate::wind::WindStandort>,
) -> Option<Decimal> {
    wind_korrekturfaktor.or_else(|| wind_standort.map(|ws| ws.korrekturfaktor))
}

// ── Multi-block settlement (§24 EEG Anlagenerweiterung) ──────────────────────

/// Settle a primary block (from `SettleInput`) plus additional `capacity_blocks`.
///
/// Called when `!input.capacity_blocks.is_empty()`.
fn calculate_with_capacity_blocks(input: &SettleInput, total_kwh: Decimal) -> SettleOutput {
    let billing_date = input.billing_date;

    // Collect all blocks: primary (from SettleInput) + additional blocks
    // leistung_kwp MUST be set when capacity_blocks are non-empty; return NoData if missing.
    let Some(primary_kwp) = input.leistung_kwp.filter(|kw| *kw > Decimal::ZERO) else {
        // §24 configuration error: cannot allocate proportionally without leistung_kwp.
        return SettleOutput {
            settlement_eur: None,
            eligible_kwh: None,
            positions: vec![crate::model::SettlePosition {
                description: "§24 Konfigurationsfehler: leistung_kwp fehlt oder ist null"
                    .to_owned(),
                legal_basis: "§24 EEG 2023".to_owned(),
                kwh: Decimal::ZERO,
                rate_ct_kwh: Decimal::ZERO,
                eur: Decimal::ZERO,
            }],
            status: SettlementStatus::NoData,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    };
    let additional_total_kwp: Decimal = input.capacity_blocks.iter().map(|b| b.leistung_kwp).sum();
    let total_kwp = primary_kwp + additional_total_kwp;

    // §21 EEG needs a rate per block. `verguetungssatz_ct()` is `None` for the
    // market- and capacity-based schemes, and settling those at zero would report
    // a €0 claim as `Calculated` — a §24-extended Direktvermarktung plant would
    // silently lose its whole Marktprämie.
    let Some(primary_rate) = input.scheme.verguetungssatz_ct() else {
        return SettleOutput {
            settlement_eur: None,
            eligible_kwh: None,
            positions: vec![crate::model::SettlePosition {
                description: "§24 Anlagenerweiterung: das Abrechnungsmodell führt keinen \
                     Vergütungssatz je Block (Marktprämie/Post-EEG) — kein Preis ermittelbar"
                    .to_owned(),
                legal_basis: "§24 EEG 2023".to_owned(),
                kwh: Decimal::ZERO,
                rate_ct_kwh: Decimal::ZERO,
                eur: Decimal::ZERO,
            }],
            status: SettlementStatus::PriceMissing,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    };

    let mut positions: Vec<SettlePosition> = Vec::new();
    let mut total_eligible = Decimal::ZERO;

    // §24 makes the blocks **one** plant, so the metered Einspeisemenge is split
    // across them by installed capacity — and the parts have to add back up to
    // it. Computing each block from its own rounded share does not: three equal
    // blocks of 1500 kWh each take 500.000 and the plant is settled for a
    // quantity it never fed in. `proportional_split` allocates by largest
    // remainder, so the parts sum to the total exactly at kWh scale 3.
    //
    // Expired blocks are allocated and then dropped rather than excluded from
    // the split: their capacity still counts towards the plant, and the energy
    // that falls to them is simply no longer eligible.
    //
    // The shares are kept at full `Decimal` precision — `proportional_split`
    // requires them to sum to 1, and rounding them first is what breaks that.
    let shares: Vec<Decimal> = std::iter::once(primary_kwp)
        .chain(input.capacity_blocks.iter().map(|b| b.leistung_kwp))
        .map(|kwp| kwp / total_kwp)
        .collect();
    let split = |quantity: Decimal| billing::proportional_split(quantity, &shares, 3);
    let (Ok(block_kwh_split), Ok(negative_kwh_split)) = (
        split(total_kwh),
        input
            .kwh_during_negative_epex
            .map_or_else(|| Ok(vec![Decimal::ZERO; shares.len()]), split),
    ) else {
        // `primary_kwp > 0` and the shares are derived from it, so the only
        // input that reaches here is a negative Einspeisemenge — which is not a
        // settleable figure, and paying every block zero for it would settle
        // nothing without saying so.
        return SettleOutput {
            settlement_eur: None,
            eligible_kwh: None,
            positions: vec![crate::model::SettlePosition {
                description: format!(
                    "§24 Anlagenerweiterung: {total_kwh} kWh lassen sich nicht \
                     verteilungsgenau auf die Leistungsblöcke aufteilen"
                ),
                legal_basis: "§24 EEG 2023".to_owned(),
                kwh: Decimal::ZERO,
                rate_ct_kwh: Decimal::ZERO,
                eur: Decimal::ZERO,
            }],
            status: SettlementStatus::NoData,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    };

    // ── Primary block ────────────────────────────────────────────────────────
    let primary_expired =
        billing_date.is_some_and(|d| input.foerderendedatum.is_some_and(|fed| d > fed));
    if !primary_expired {
        let mut block_kwh = block_kwh_split[0];

        // §51 Negativpreisregel — the size test runs on the aggregated plant
        // (§51 Abs. 2 Satz 2 i.V.m. §24), the deduction on this block's share.
        if sect51_greift(
            input.kwh_during_negative_epex,
            Some(total_kwp),
            input.negativpreis_regime(),
            input.erzeugungsart,
            input.has_imesys,
            input.ist_pilotwindanlage,
            sect51b_verdraengt_sect51(input),
        ) {
            // This block's share of the negative-price hours, split the same
            // way the energy is.
            let neg_share = negative_kwh_split[0];
            block_kwh = apply_negativpreis(block_kwh, neg_share);
        }

        if block_kwh > Decimal::ZERO || primary_rate != Decimal::ZERO {
            let ibn_label = input
                .inbetriebnahme
                .map(|d| format!(" (IBN {d})"))
                .unwrap_or_default();
            positions.push(pos(
                format!("Einspeiseverg\u{00fc}tung {primary_kwp}\u{202f}kWp-Block{ibn_label}"),
                "\u{00a7}21 EEG",
                block_kwh,
                primary_rate,
            ));
        }
        total_eligible += block_kwh;
    }

    // ── Additional blocks ────────────────────────────────────────────────────
    for (idx, block) in input.capacity_blocks.iter().enumerate() {
        let block_expired = billing_date.is_some_and(|d| d > block.foerderendedatum);
        if block_expired {
            continue;
        }
        let mut block_kwh = block_kwh_split[idx + 1];

        // §51 per-block: each block carries its own commissioning date, and the
        // §51 regime is keyed on that date — a block added after the
        // Solarspitzengesetz is governed by it even when the primary block is not.
        if sect51_greift(
            input.kwh_during_negative_epex,
            Some(total_kwp),
            crate::negativpreis::NegativpreisRegime::fuer_inbetriebnahme(block.inbetriebnahme),
            input.erzeugungsart,
            input.has_imesys,
            input.ist_pilotwindanlage,
            sect51b_verdraengt_sect51(input),
        ) {
            let neg_share = negative_kwh_split[idx + 1];
            block_kwh = apply_negativpreis(block_kwh, neg_share);
        }

        let block_num = idx + 1;
        if block_kwh > Decimal::ZERO || block.verguetungssatz_ct != Decimal::ZERO {
            positions.push(pos(
                format!(
                    "Einspeiseverg\u{00fc}tung {}\u{202f}kWp-Block\u{202f}{} (IBN {})",
                    block.leistung_kwp, block_num, block.inbetriebnahme
                ),
                "\u{00a7}21 EEG",
                block_kwh,
                block.verguetungssatz_ct,
            ));
        }
        total_eligible += block_kwh;
    }

    let is_empty = positions.is_empty();
    let settlement_eur = total(&positions);
    SettleOutput {
        settlement_eur,
        eligible_kwh: Some(total_eligible),
        positions,
        status: if is_empty {
            SettlementStatus::FoerderungBeendet
        } else {
            SettlementStatus::Calculated
        },
        pflichtzahlung_eur: None,
        pflichtzahlung_faelligkeitsdatum: None,
        verlaengerungsanspruch_qh: 0,
        dezentrale_einspeisung_anspruch_verloren: false,
        billing_days_fraction_applied: None,
        faelligkeitsdatum: None,
    }
}

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

/// Calculate the settlement amount and billing positions for one period.
///
/// This function is **pure** — it performs no I/O and has no side effects.
/// All input rates are in `ct/kWh`; output amounts are in EUR.
///
/// ## Multi-EEG-version support
///
/// Supply `inbetriebnahme` and `leistung_kwp` for automatic version-aware
/// rule enforcement (§51 EEG Negativpreisregel, §8 KWKG Förderdauer limits).
/// The correct `verguetungssatz_ct` must be supplied by the caller (use
/// `eeg_billing::rates` or `einsd`'s rate lookup table).
///
/// ## Förderdauer auto-detection
///
/// Supply `billing_date` and `foerderendedatum` to enable automatic
/// `FoerderungBeendet` status when the billing period starts after the
/// subsidy end date. Without these, the caller must check expiry manually.
///
/// # Examples
///
/// ```rust
/// use eeg_billing::{SettleInput, SettlementScheme, calculate_settlement, SettlementStatus};
/// use rust_decimal::Decimal;
/// use std::str::FromStr;
///
/// fn d(s: &str) -> Decimal { Decimal::from_str(s).unwrap() }
///
/// // §21 EEG 2023 — 100 kWh × 8.11 ct/kWh = 8.11 EUR
/// let out = calculate_settlement(&SettleInput {
///     scheme: eeg_billing::SettlementScheme::FeedInTariff { verguetungssatz_ct: d("8.11") },
///     einspeisemenge_kwh: Some(d("100")),
///     ..SettleInput::default()
/// });
/// assert_eq!(out.status, SettlementStatus::Calculated);
/// assert_eq!(out.settlement_eur, Some(d("8.11")));
/// ```
pub fn calculate_settlement(input: &SettleInput) -> SettleOutput {
    // ── §52 EEG 2023 Pflichtzahlungen (multiple violations, §52 Abs. 5 cap) ────
    // Every violation is spread over the calendar months it runs in and each
    // month is capped on its own at 10 €/kW — see `sect52_abs5_gedeckelt`.
    //
    // Dedup: if the same SanktionsTyp appears more than once, only the entry with
    // the most months is counted (double-reporting the same violation type is a
    // caller error; we guard against it here to prevent over-charging operators).
    let deduplicated_pflichtverstoss: Vec<_> = {
        use std::collections::HashMap;
        let mut by_typ: HashMap<u8, &crate::model::Pflichtverstoss> = HashMap::new();
        for v in &input.pflichtverstoss {
            let key = v.typ as u8;
            let entry = by_typ.entry(key).or_insert(v);
            if v.monate_des_verstosses > entry.monate_des_verstosses {
                *entry = v;
            }
        }
        by_typ.into_values().collect()
    };
    let pflichtzahlung_eur = if deduplicated_pflichtverstoss.is_empty() {
        None
    } else {
        Some(sect52_abs5_gedeckelt(&deduplicated_pflichtverstoss))
    };

    // Delegate to inner function.
    let mut result = calculate_settlement_inner(input);
    result.pflichtzahlung_eur = pflichtzahlung_eur;

    // ── §52 Abs. 6 Satz 1 EEG 2023 — Pflichtzahlung Fälligkeitsdatum ─────────
    // The §52 penalty is due on the 15th of the month following the billing month,
    // same computation as §26 Abs. 1 Vergütung Fälligkeitsdatum.
    // Only set when there is actually a Pflichtzahlung.
    if result
        .pflichtzahlung_eur
        .is_some_and(|p| p > rust_decimal::Decimal::ZERO)
    {
        result.pflichtzahlung_faelligkeitsdatum = result.faelligkeitsdatum; // same formula
    }

    // ── §51a — Verlängerung des Vergütungszeitraums ──────────────────────────
    // §51a Abs. 1: the extension is "für Strom aus Anlagen, für den sich der
    // anzulegende Wert nach Maßgabe des § 51 verringert" — so it accrues only
    // where §51 actually bit. A plant under the Abs. 2 exemption, or on a scheme
    // §51 does not reach, was paid in full and gets no extension.
    //
    // Before the Solarspitzengesetz the extension existed only for
    // ausschreibungspflichtige Anlagen; a statutory-AW plant commissioned in 2024
    // loses the quarter-hours without compensation. §51a never applies to §51b
    // biogas Ausschreibungsanlagen (§51b Satz 2).
    if !sect51b_verdraengt_sect51(input)
        && let Some(lost_qh) = input.negative_price_quarter_hours.filter(|&q| q > 0)
        && input.scheme.negativpreis_rule_applicable()
        && input
            .negativpreis_regime()
            .verlaengerungsanspruch(input.tariff_source.is_auction())
        && sect51_greift(
            input.kwh_during_negative_epex,
            aggregierte_leistung_kwp(input),
            input.negativpreis_regime(),
            input.erzeugungsart,
            input.has_imesys,
            input.ist_pilotwindanlage,
            sect51b_verdraengt_sect51(input),
        )
    {
        let is_solar = input.erzeugungsart.is_some_and(|a| a.is_solar());
        result.verlaengerungsanspruch_qh =
            crate::foerderdauer::verguetungszeitraum_verlaengerung_qh(lost_qh, is_solar);
    }

    // ── §51 Abs. 3 EEG — Ausfallvergütung: unreported negative-price feed-in ──
    // "verringert sich der Anspruch ... um 5 Prozent für jeden Kalendertag, an
    // dem der Zeitraum ... ganz oder teilweise lag." A per-day reduction of the
    // month's claim, floored at zero — twenty such days extinguish it.
    //
    // Sequenced before the §25 proration because it reduces the claim itself,
    // and after the scheme dispatch because it applies to whatever that produced.
    if matches!(input.scheme, SettlementScheme::TemporaryFeedInTariff { .. })
        && input.sect51_abs3_unreported_days > 0
        && !matches!(
            result.status,
            SettlementStatus::NoData | SettlementStatus::PriceMissing
        )
    {
        let tage = Decimal::from(input.sect51_abs3_unreported_days);
        let faktor = (Decimal::ONE - dec!(0.05) * tage).max(Decimal::ZERO);
        if let Some(eur) = result.settlement_eur {
            let gekuerzt = validated_eur(eur * faktor);
            result.positions.push(crate::model::SettlePosition {
                description: format!(
 "\u{00a7}51 Abs. 3 EEG: Meldung der Einspeisung w\u{00e4}hrend negativer Preise unterblieben \u{2014} {} % K\u{00fc}rzung ({tage} Kalendertage)",
                    (Decimal::ONE - faktor) * Decimal::from(100)
                ),
                legal_basis: "\u{00a7}51 Abs. 3 EEG".to_owned(),
                kwh: Decimal::ZERO,
                rate_ct_kwh: Decimal::ZERO,
                eur: gekuerzt - eur,
            });
            result.settlement_eur = Some(gekuerzt);
        }
    }

    // ── §25 billing_days_fraction — auto-compute or use caller override ──────
    // Legal basis: §25 Abs. 1 Satz 3 EEG 2023 (commissioning day = start of entitlement)
    // When None: auto-compute from billing_date + foerderendedatum. The auto rule
    // narrows the Förderende month only — a meter commissioned mid-month already
    // recorded only the eligible days, so prorating it again would bill a
    // fraction of a fraction. See `compute_billing_days_fraction`.
    // When Some(x): use provided value directly (caller override for edge cases).
    let billing_days_fraction = input.billing_days_fraction.or_else(|| {
        crate::foerderdauer::compute_billing_days_fraction(
            input.foerderendedatum,
            input.billing_date,
        )
    });

    // Apply billing_days_fraction when < 1.0 (partial month)
    if let Some(fraction) =
        billing_days_fraction.filter(|&f| f > Decimal::ZERO && f < rust_decimal::Decimal::ONE)
    {
        if let Some(eur) = result.settlement_eur {
            result.settlement_eur = Some(validated_eur(eur * fraction));
        }
        if let Some(kwh) = result.eligible_kwh {
            result.eligible_kwh = Some((kwh * fraction).round_kfm(3));
        }
        // Annotate all positions with the fraction
        for p in &mut result.positions {
            p.eur = validated_eur(p.eur * fraction);
            p.kwh = (p.kwh * fraction).round_kfm(3);
        }
    }

    // Record the applied fraction in SettleOutput for audit trail (§ 147 AO / GoBD)
    result.billing_days_fraction_applied =
        billing_days_fraction.filter(|&f| f > Decimal::ZERO && f < rust_decimal::Decimal::ONE);

    // ── §13a EnWG — Einspeisemanagement (curtailment) compensation ───────────
    // Curtailment of EEG plants is Redispatch 2.0: the entschädigungspflichtige
    // Abregelung under §13a EnWG (historically §15 EEG Härtefallregelung). §51
    // Negativpreisregel does not touch these kWh because they were never fed in
    // (not by virtue of §19 EEG).
    //
    // Sequenced after the §25 proration on purpose: this is actual curtailed
    // energy under a separate EnWG claim, not a share of the month's
    // entitlement, so it must not be scaled by the billing-days fraction.
    if let Some(einsman_kwh) = input.einspeisemanagement_kwh.filter(|k| *k > Decimal::ZERO)
        && !matches!(
            result.status,
            SettlementStatus::NoData | SettlementStatus::PriceMissing
        )
        && !matches!(
            input.scheme,
            crate::scheme::SettlementScheme::Eigenverbrauch
        )
    {
        let comp_rate_ct = match &input.scheme {
            crate::scheme::SettlementScheme::MarketPremium {
                direktverm_aw_ct,
                wind_korrekturfaktor,
                wind_standort,
                ..
            } => {
                let raw_aw = *direktverm_aw_ct;
                if let Some(k) =
                    resolve_wind_korrekturfaktor(*wind_korrekturfaktor, wind_standort.as_ref())
                {
                    (raw_aw * k).round_kfm(5)
                } else {
                    raw_aw
                }
            }
            _ => {
                // §13a EnWG compensates the curtailed kWh at the rate the plant
                // would have earned for them. A scheme that carries no such rate
                // (PostEeg, sonstige Direktvermarktung) prices the Abregelung
                // nowhere, and paying it at 0 ct/kWh would report the whole
                // settlement as complete while the Entschädigung is dropped.
                let Some(rate) = input.scheme.verguetungssatz_ct() else {
                    result.status = SettlementStatus::PriceMissing;
                    return result;
                };
                rate
            }
        };
        let comp_eur = validated_eur(einsman_kwh * comp_rate_ct / Decimal::from(100));
        result.positions.push(crate::model::SettlePosition {
            description: format!("Einspeisemanagement-Ausfall §13a EnWG ({einsman_kwh} kWh)"),
            legal_basis: "§13a EnWG (Redispatch 2.0)".to_owned(),
            kwh: einsman_kwh,
            rate_ct_kwh: comp_rate_ct,
            eur: comp_eur,
        });
        result.settlement_eur = Some(result.settlement_eur.unwrap_or(Decimal::ZERO) + comp_eur);
        result.eligible_kwh = Some(result.eligible_kwh.unwrap_or(Decimal::ZERO) + einsman_kwh);
        // The status stays whatever the EEG rules made it: a §13a EnWG
        // compensation rides alongside, it does not undo a §43 substrate-cap or
        // §52 sanction, and reporting `Calculated` would conceal one.
    }

    // ── §26 Abs. 1 EEG 2023 — Fälligkeitsdatum ───────────────────────────────────
    // §26 Abs. 1: "monatlich jeweils zum 15. Kalendertag für den Vormonat" —
    // advance payments for the prior (billing) month are due on the 15th of the
    // FOLLOWING calendar month.
    if let Some(bd) = input.billing_date {
        let m = bd.month();
        let y = bd.year();
        let (next_year, next_month) = if m == time::Month::December {
            (y + 1, time::Month::January)
        } else {
            (y, m.next())
        };
        result.faelligkeitsdatum = time::Date::from_calendar_date(next_year, next_month, 15).ok();
    }

    // ── §52 Abs. 7 EEG 2023 — dezentrale Einspeisung (§18 StromNEV) ─────────
    // When any §52 violation penalty is due, the operator also loses the §18 StromNEV
    // dezentrale Einspeisung entgelt for the entire calendar year.
    if result
        .pflichtzahlung_eur
        .is_some_and(|p| p > rust_decimal::Decimal::ZERO)
    {
        result.dezentrale_einspeisung_anspruch_verloren = true;
    }

    // ── §44b Abs. 1 EEG 2023 — Biogas >100kW: 45% Bemessungsleistung cap ─────
    // Only eligible kWh receive normal EEG payment; excess receives:
    //   - MarketPremium: AW → 0, Marktprämie = 0
    //   - FeedInTariff/Tenant/Flex: paid at EPEX Marktwert (§44b Abs. 1 Satz 2)
    if let Some(sect44b_eligible) = input.biogas_sect44b_eligible_kwh {
        let effective_kwh = result.eligible_kwh.unwrap_or(rust_decimal::Decimal::ZERO);
        if effective_kwh > rust_decimal::Decimal::ZERO && sect44b_eligible < effective_kwh {
            let excess_kwh = effective_kwh - sect44b_eligible;
            let ratio = (sect44b_eligible / effective_kwh).min(rust_decimal::Decimal::ONE);

            // Scale all positions to the eligible fraction
            if let Some(eur) = result.settlement_eur {
                result.settlement_eur = Some(validated_eur(eur * ratio));
            }
            for p in &mut result.positions {
                p.eur = validated_eur(p.eur * ratio);
                p.kwh = (p.kwh * ratio).round_kfm(3);
            }

            // Add excess position per scheme
            match &input.scheme {
                crate::scheme::SettlementScheme::FeedInTariff { .. }
                | crate::scheme::SettlementScheme::TenantElectricity { .. }
                | crate::scheme::SettlementScheme::TemporaryFeedInTariff { .. }
                | crate::scheme::SettlementScheme::FlexibilityPremium { .. } => {
                    // §44b Abs. 1 Satz 2: Einspeisevergütung → Marktwert for excess
                    // Without a Marktwert there is no price for the excess —
                    // settling it at zero would silently expropriate the operator.
                    let Some(excess_rate) = input.marktwert_ct_kwh else {
                        result.status = SettlementStatus::PriceMissing;
                        return result;
                    };
                    let excess_eur =
                        validated_eur(excess_kwh * excess_rate / rust_decimal::Decimal::from(100));
                    result.positions.push(crate::model::SettlePosition {
                        description: format!("§44b Abs. 1 Überschuss Marktwert ({excess_kwh} kWh)"),
                        legal_basis: "§44b Abs. 1 EEG 2023".to_owned(),
                        kwh: excess_kwh,
                        rate_ct_kwh: excess_rate,
                        eur: excess_eur,
                    });
                    result.settlement_eur = Some(
                        result.settlement_eur.unwrap_or(rust_decimal::Decimal::ZERO) + excess_eur,
                    );
                }
                crate::scheme::SettlementScheme::MarketPremium { .. } => {
                    // §44b Abs. 1 Satz 2: Marktprämie → 0 for excess (AW = null)
                    result.positions.push(crate::model::SettlePosition {
                        description: format!("§44b Abs. 1 Überschuss (AW = 0, {excess_kwh} kWh)"),
                        legal_basis: "§44b Abs. 1 EEG 2023".to_owned(),
                        kwh: excess_kwh,
                        rate_ct_kwh: rust_decimal::Decimal::ZERO,
                        eur: rust_decimal::Decimal::ZERO,
                    });
                }
                _ => {} // §44b does not apply to Eigenverbrauch, KwkSurcharge, etc.
            }
        }
    }

    result
}

/// Inner implementation — all SettleOutput constructions use `pflichtzahlung_eur: None`
/// as a placeholder; the public wrapper overwrites it.
fn calculate_settlement_inner(input: &SettleInput) -> SettleOutput {
    use crate::model::SanktionAlt;

    // ── § 39i Abs. 1 EEG 2023 — Getreidekorn und Mais ────────────────────────
    // „Ein durch einen Zuschlag erworbener Anspruch nach § 19 Absatz 1 für Strom
    // aus Biogas besteht nur, wenn der … eingesetzte Anteil von Getreidekorn und
    // Mais … höchstens X Masseprozent beträgt." The condition reaches only a
    // plant holding a Zuschlag, measures those two feedstocks, and steps down by
    // Gebotstermin. Failing it leaves no claim to settle — the operator is owed
    // nothing rather than being penalised, so the Gutschrift states the reason
    // at a zero rate.
    if let Some(biomasse) = &input.biomasse
        && !biomasse.sect39i_eingehalten()
    {
        let grenze =
            (biomasse.sect39i_hoechstanteil().unwrap_or(Decimal::ZERO) * dec!(100)).normalize();
        return SettleOutput {
            settlement_eur: Some(Decimal::ZERO),
            eligible_kwh: input.einspeisemenge_kwh,
            positions: vec![crate::model::SettlePosition {
                description: format!(
                    "§39i Abs. 1 EEG 2023: Anteil von Getreidekorn und Mais über \
                     {grenze} Masseprozent — kein Anspruch nach §19 Abs. 1"
                ),
                legal_basis: "§39i Abs. 1 EEG 2023".to_owned(),
                kwh: input.einspeisemenge_kwh.unwrap_or(Decimal::ZERO),
                rate_ct_kwh: Decimal::ZERO,
                eur: Decimal::ZERO,
            }],
            status: SettlementStatus::KeinAnspruch,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    }

    // ── §52 EEG ≤2021 three-tier sanction dispatch ────────────────────────────
    //
    // Abs. 1 → Vergütung = 0   (VerguetungAufNull)
    // Abs. 2 → Vergütung = EPEX Marktwert (VerguetungAufMarktwert)
    // Abs. 3 → Vergütung × 0.80 (VerguetungReduziert20Prozent)
    match input.sanktion {
        Some(SanktionAlt::VerguetungAufNull) => {
            // §52 Abs. 1 EEG ≤2021: anzulegender Wert verringert sich auf null.
            // The zero is stated as a position so the Gutschrift says why nothing
            // is paid rather than arriving empty.
            return SettleOutput {
                settlement_eur: Some(Decimal::ZERO),
                eligible_kwh: input.einspeisemenge_kwh,
                positions: vec![pos(
                    "Verg\u{00fc}tung auf null verringert \u{2014} \u{00a7}52 Abs. 1 EEG 2021",
                    "\u{00a7}52 Abs. 1 EEG 2021",
                    input.einspeisemenge_kwh.unwrap_or(Decimal::ZERO),
                    Decimal::ZERO,
                )],
                status: SettlementStatus::Sanctioned,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            };
        }
        Some(SanktionAlt::VerguetungAufMarktwert) => {
            // §52 Abs. 2 EEG ≤2021: verringert sich auf den Monatsmarktwert (EPEX).
            // Same formula as PostEegSpot but within Förderdauer.
            let Some(epex_ct) = input.marktwert_ct_kwh else {
                return SettleOutput {
                    settlement_eur: None,
                    eligible_kwh: None,
                    positions: vec![],
                    status: SettlementStatus::PriceMissing,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            };
            let Some(kwh) = input.einspeisemenge_kwh else {
                return SettleOutput {
                    settlement_eur: None,
                    eligible_kwh: None,
                    positions: vec![],
                    status: SettlementStatus::NoData,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            };
            // No §23b cap here (only for PostEegSpot ausgeförderte Anlagen).
            let positions = vec![pos(
                "Einspeisevergütung §52 Abs. 2 EEG (auf Marktwert verringert)",
                "§52 Abs. 2 EEG",
                kwh,
                epex_ct,
            )];
            return SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(kwh),
                positions,
                status: SettlementStatus::Sanctioned,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            };
        }
        Some(SanktionAlt::VerguetungReduziert20Prozent) => {
            // §52 Abs. 3 EEG ≤2021: verringert sich um 20 Prozent, „wobei das
            // Ergebnis auf zwei Stellen nach dem Komma gerundet wird".
            //
            // The cut is on the Vergütung, so it lands on every position's rate:
            // carrying the un-reduced positions alongside a reduced total would
            // put a Gutschrift on the wire whose lines do not add up to what is
            // paid.
            let base = settle_normal_body(input);
            let positions: Vec<crate::model::SettlePosition> = base
                .positions
                .into_iter()
                .map(|p| {
                    let rate = p.rate_ct_kwh * dec!(0.80);
                    crate::model::SettlePosition {
                        rate_ct_kwh: rate,
                        eur: validated_eur(p.kwh * rate / dec!(100)),
                        ..p
                    }
                })
                .collect();
            let reduced_eur = base.settlement_eur.map(|e| (e * dec!(0.80)).round_kfm(2));
            return SettleOutput {
                settlement_eur: reduced_eur,
                eligible_kwh: base.eligible_kwh,
                positions,
                status: SettlementStatus::Sanctioned,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            };
        }
        None => {} // no sanction → normal settlement
    }
    settle_normal_body(input)
}

/// Apply §§53b–54 to an anzulegender Wert, using the input's context.
///
/// Returns the reduced AW and the list of cuts that fired. Reductions act on the
/// AW rather than the settled amount because that is what the statutes say and
/// because the Marktprämie floors at zero — see [`crate::aw_reductions`].
fn apply_aw_cuts(
    aw_ct: Decimal,
    input: &SettleInput,
) -> (Decimal, Vec<crate::aw_reductions::AwReductionApplied>) {
    // §100 EEG — a Bestandsanlage that opted into the Solarspitzengesetz regime
    // is paid 0,6 ct/kWh more on everything it does feed in, in exchange for
    // forgoing payment during negative prices. The uplift is on the AW and so
    // comes before the §§53b–54 cuts, which are also AW-level.
    let aw_ct = if sect51_optin_active(input) {
        aw_ct + crate::negativpreis::SECT51_OPTIN_ZUSCHLAG_CT_KWH
    } else {
        aw_ct
    };
    if input.aw_reductions.is_empty() {
        return (aw_ct, Vec::new());
    }
    crate::aw_reductions::apply_aw_reductions(
        aw_ct,
        &input.aw_reductions,
        &input.tariff_source,
        input.erzeugungsart.unwrap_or_default(),
    )
}

/// Whether the §100 Solarspitzengesetz opt-in is in force for this period.
fn sect51_optin_active(input: &SettleInput) -> bool {
    matches!(
        (input.sect51_optin_wirksam_ab, input.billing_date),
        (Some(ab), Some(bd)) if bd >= ab
    )
}

/// Render each AW cut as a zero-euro audit position.
///
/// The euro effect is already inside the reduced rate on the main position, so
/// these carry the deduction as a negative `rate_ct_kwh` and `eur: 0` — double
/// counting the money would misstate the settlement. They exist so the
/// Gutschrift names every statute that touched the AW.
fn aw_cut_positions(
    cuts: &[crate::aw_reductions::AwReductionApplied],
    kwh: Decimal,
) -> Vec<crate::model::SettlePosition> {
    cuts.iter()
        .map(|c| crate::model::SettlePosition {
            description: c.description.clone(),
            legal_basis: c.legal_basis.clone(),
            kwh,
            rate_ct_kwh: -c.deduction_ct_kwh,
            eur: Decimal::ZERO,
        })
        .collect()
}

/// Refusal for a scheme whose own surcharge rate is absent.
///
/// Choosing the scheme *is* the statement that the provision applies. Falling
/// back to zero keeps the base Vergütung and drops the surcharge without a
/// trace, so the settlement reports `Calculated` for an amount the statute does
/// not allow. The rate is a required price: absent, the settlement refuses.
fn satz_fehlt(description: impl Into<String>, legal_basis: impl Into<String>) -> SettleOutput {
    SettleOutput {
        settlement_eur: None,
        eligible_kwh: None,
        positions: vec![SettlePosition {
            description: description.into(),
            legal_basis: legal_basis.into(),
            kwh: Decimal::ZERO,
            rate_ct_kwh: Decimal::ZERO,
            eur: Decimal::ZERO,
        }],
        status: SettlementStatus::PriceMissing,
        pflichtzahlung_eur: None,
        pflichtzahlung_faelligkeitsdatum: None,
        verlaengerungsanspruch_qh: 0,
        dezentrale_einspeisung_anspruch_verloren: false,
        billing_days_fraction_applied: None,
        faelligkeitsdatum: None,
    }
}

/// §50a refusal — the Flexibilitätszuschlag has no capacity to price.
///
/// §50a pays `leistung_kwp × rate / 12` on the *flexible* installed capacity, so
/// that capacity is the whole basis of the claim. Absent it there is nothing to
/// price: a zero would be settled as `Calculated` and rendered as a clean
/// €0,00 Gutschrift, which is indistinguishable from a plant that is genuinely
/// owed nothing. Same refusal the §24 block allocation makes for the same
/// missing field.
fn sect50a_ohne_leistung() -> SettleOutput {
    SettleOutput {
        settlement_eur: None,
        eligible_kwh: None,
        positions: vec![SettlePosition {
            description: "§50a Flexibilitätszuschlag: leistung_kwp (flexible Leistung) fehlt — \
                 keine Bemessungsgrundlage"
                .to_owned(),
            legal_basis: "§50a EEG 2023".to_owned(),
            kwh: Decimal::ZERO,
            rate_ct_kwh: Decimal::ZERO,
            eur: Decimal::ZERO,
        }],
        status: SettlementStatus::NoData,
        pflichtzahlung_eur: None,
        pflichtzahlung_faelligkeitsdatum: None,
        verlaengerungsanspruch_qh: 0,
        dezentrale_einspeisung_anspruch_verloren: false,
        billing_days_fraction_applied: None,
        faelligkeitsdatum: None,
    }
}

/// Core settlement body — executes AFTER all §52 sanction checks.
/// Also called directly by the §52 Abs. 3 (-20%) path.
fn settle_normal_body(input: &SettleInput) -> SettleOutput {
    // ── Automatic FoerderungBeendet detection ────────────────────────────────
    // Only applies for single-block plants. Multi-block plants handle per-block
    // expiry inside calculate_with_capacity_blocks().
    if input.capacity_blocks.is_empty()
        && let (Some(billing), Some(fed)) = (input.billing_date, input.foerderendedatum)
        && billing > fed
    {
        return SettleOutput {
            settlement_eur: Some(Decimal::ZERO),
            eligible_kwh: input.einspeisemenge_kwh,
            positions: vec![],
            status: SettlementStatus::FoerderungBeendet,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    }

    // ── No meter data ─────────────────────────────────────────────────────────
    // §50a FlexibilitaetZuschlag is capacity-based (not kWh-based) — bypass this check.
    let Some(kwh) = input.einspeisemenge_kwh else {
        if let SettlementScheme::FlexibilitySurcharge {
            rate_eur_per_kw_year,
        } = &input.scheme
        {
            let Some(kw) = input.leistung_kwp else {
                return sect50a_ohne_leistung();
            };
            let rate_eur_per_kw_year = *rate_eur_per_kw_year;
            let monthly_eur = validated_eur(kw * rate_eur_per_kw_year / dec!(12));
            let positions = vec![SettlePosition {
                description: format!(
                    "Flexibilit\u{00e4}tszuschlag \u{00a7}50a EEG 2023 \
                    ({kw}\u{202f}kW \u{00d7} {rate_eur_per_kw_year}\u{202f}EUR/kW/Jahr \u{00f7} 12)"
                ),
                legal_basis: "\u{00a7}50a EEG 2023".to_owned(),
                kwh: kw,
                rate_ct_kwh: rate_eur_per_kw_year,
                eur: monthly_eur,
            }];
            return SettleOutput {
                settlement_eur: Some(monthly_eur),
                eligible_kwh: Some(kw),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            };
        }
        return SettleOutput {
            settlement_eur: None,
            eligible_kwh: None,
            positions: vec![],
            status: SettlementStatus::NoData,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        };
    };

    // ── Multi-block (§24 Anlagenerweiterung) ─────────────────────────────────
    if !input.capacity_blocks.is_empty() {
        return calculate_with_capacity_blocks(input, kwh);
    }

    // ── Effective §51 application ─────────────────────────────────────────────
    let apply_neg = input.scheme.negativpreis_rule_applicable()
        && sect51_greift(
            input.kwh_during_negative_epex,
            aggregierte_leistung_kwp(input),
            input.negativpreis_regime(),
            input.erzeugungsart,
            input.has_imesys,
            input.ist_pilotwindanlage,
            sect51b_verdraengt_sect51(input),
        );
    let neg_kwh = if apply_neg {
        input.kwh_during_negative_epex
    } else {
        None
    };

    // ══ SETTLEMENT PIPELINE ══════════════════════════════════════════════
    // 1. §52 sanction check (short-circuits to EUR 0 or EPEX Marktwert)
    // 2. FoerderungBeendet detection (billing_date > foerderendedatum)
    // 3. Scheme dispatch → gross settlement positions
    // 4. §51a verlängerungsanspruch (output field, informational)
    // 5. §13a EnWG EInsMan compensation (separate position)
    // 6. §§53b–54 AW-level reductions (applied to the AW, not the result)
    // Output: SettleOutput with all positions summed
    match &input.scheme {
        // ── EUR 0 — Eigenverbrauch ────────────────────────────────────────────
        SettlementScheme::Eigenverbrauch => SettleOutput {
            settlement_eur: Some(Decimal::ZERO),
            eligible_kwh: Some(kwh),
            positions: vec![],
            status: SettlementStatus::Calculated,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        },

        // ── EUR 0 — §21a Sonstige Direktvermarktung ───────────────────────────
        // The operator exercises their §21a EEG 2023 right to sell directly to a
        // third party (not via Marktprämie and not via Einspeisevergütung).
        // No NB payment for this period. Records the period for settlement history.
        SettlementScheme::SonstigeDirektvermarktung => SettleOutput {
            settlement_eur: Some(Decimal::ZERO),
            eligible_kwh: Some(kwh),
            positions: vec![crate::model::SettlePosition {
                description:
                    "Sonstige Direktvermarktung \u{00a7}21a EEG 2023 (kein EEG-Zahlungsanspruch)"
                        .to_owned(),
                legal_basis: "\u{00a7}21a EEG 2023".to_owned(),
                kwh,
                rate_ct_kwh: Decimal::ZERO,
                eur: Decimal::ZERO,
            }],
            status: SettlementStatus::Calculated,
            pflichtzahlung_eur: None,
            pflichtzahlung_faelligkeitsdatum: None,
            verlaengerungsanspruch_qh: 0,
            dezentrale_einspeisung_anspruch_verloren: false,
            billing_days_fraction_applied: None,
            faelligkeitsdatum: None,
        },

        // ── §21 EEG — Einspeisevergütung und Ausfallvergütung ────────────────
        SettlementScheme::TemporaryFeedInTariff { verguetungssatz_ct }
        | SettlementScheme::FeedInTariff { verguetungssatz_ct } => {
            let ist_ausfallverguetung =
                matches!(input.scheme, SettlementScheme::TemporaryFeedInTariff { .. });
            let effective = match neg_kwh {
                Some(n) => apply_negativpreis(kwh, n),
                None => kwh,
            };
            // §53 Abs. 1 EEG 2023: subtract the flat AW deduction only when the
            // supplied rate is the GROSS AW. Default net → no change.
            let rate_ct = if input.aw_is_gross
                && !ist_ausfallverguetung
                && let Some(art) = input.erzeugungsart
            {
                (*verguetungssatz_ct - crate::rates::sect53_deduction(art)).max(Decimal::ZERO)
            } else {
                *verguetungssatz_ct
            };
            // §53 Abs. 3 EEG 2023 — Ausfallvergütung: "verringert sich der
            // anzulegende Wert um 20 Prozent", rounded to two decimals.
            //
            // The **engine** applies it, not the caller. Left to the caller,
            // the plant's ordinary tariff passes straight through and a plant on
            // the Ausfallvergütung is paid the full rate — 25 % more than the
            // statute allows, on the one scheme that exists because the
            // operator's Direktvermarkter dropped out.
            let rate_ct = if ist_ausfallverguetung {
                (rate_ct * dec!(0.8)).round_kfm(2)
            } else {
                rate_ct
            };
            // §§53b–54 reduce the anzulegender Wert itself, after §53.
            let (rate_ct, aw_cuts) = apply_aw_cuts(rate_ct, input);
            let (desc, basis) = match (ist_ausfallverguetung, neg_kwh.is_some()) {
                (true, true) => (
                    "Ausfallverg\u{00fc}tung \u{00a7}21 Abs. 1 Satz 1 Nr. 3 EEG (\u{2212}20 % nach \u{00a7}53 Abs. 3; \u{00a7}51 Negativpreisregel angewendet)",
                    "\u{00a7}21 Abs. 1 Satz 1 Nr. 3 EEG 2023",
                ),
                (true, false) => (
                    "Ausfallverg\u{00fc}tung \u{00a7}21 Abs. 1 Satz 1 Nr. 3 EEG (\u{2212}20 % nach \u{00a7}53 Abs. 3)",
                    "\u{00a7}21 Abs. 1 Satz 1 Nr. 3 EEG 2023",
                ),
                (false, true) => (
                    "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG (\u{00a7}51 Negativpreisregel angewendet)",
                    "\u{00a7}21 EEG 2023",
                ),
                (false, false) => (
                    "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG",
                    "\u{00a7}21 EEG 2023",
                ),
            };
            let mut positions = vec![pos(desc, basis, effective, rate_ct)];
            positions.extend(aw_cut_positions(&aw_cuts, effective));
            SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(effective),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── §21 Abs. 3 EEG — Mieterstrom ────────────────────────────────────────────
        SettlementScheme::TenantElectricity {
            verguetungssatz_ct,
            mieter_zuschlag_ct,
        } => {
            let effective = match neg_kwh {
                Some(n) => apply_negativpreis(kwh, n),
                None => kwh,
            };
            let Some(zuschlag) = *mieter_zuschlag_ct else {
                return satz_fehlt(
                    "§21 Abs. 3 Mieterstrom: mieter_zuschlag_ct fehlt — der Zuschlag ist \
                     Bestandteil des Anspruchs, kein Aufschlag nach Ermessen",
                    "§21 Abs. 3 EEG 2023",
                );
            };
            let base_desc = if neg_kwh.is_some() {
                "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG (\u{00a7}51 Negativpreisregel angewendet)"
            } else {
                "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG"
            };
            let mut positions = vec![pos(
                base_desc,
                "\u{00a7}21 EEG 2023",
                effective,
                *verguetungssatz_ct,
            )];
            if zuschlag != Decimal::ZERO {
                positions.push(pos(
                    "Mieterstrom-Zuschlag \u{00a7}21 Abs. 3 EEG 2023",
                    "\u{00a7}21 Abs. 3 EEG 2023",
                    effective,
                    zuschlag,
                ));
            }
            SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(effective),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── §20 EEG — Gleitende Marktprämie ──────────────────────────────────
        // ── §§22a,28 EEG — Ausschreibungsanlagen ─────────────────────────────
        SettlementScheme::MarketPremium {
            direktverm_aw_ct,
            wind_korrekturfaktor,
            wind_standort,
        } => {
            // §51 Abs. 1 zeroes the anzulegender Wert for the negative-price
            // intervals, and Anlage 1 Nr. 1 defines "AW" as the anzulegender Wert
            // "unter Berücksichtigung der §§ 19 bis 54" — so those kWh earn no
            // Marktprämie. Excluding them is the same arithmetic as AW = 0.
            let effective = match neg_kwh {
                Some(n) => apply_negativpreis(kwh, n),
                None => kwh,
            };
            // §20 Abs. 2 + Anlage 1 EEG 2023: Jahresmarktwert takes precedence over monthly EPEX
            // when provided. The ÜNB publishes technology-specific annual market values.
            let epex_source = input.marktwert_ct_kwh;
            let Some(epex_ct) = epex_source else {
                return SettleOutput {
                    settlement_eur: None,
                    eligible_kwh: None,
                    positions: vec![],
                    status: SettlementStatus::PriceMissing,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            };
            let raw_aw_ct = *direktverm_aw_ct;

            // A Marktprämie plant with no anzulegender Wert is not a plant owed
            // nothing — it is a plant whose AW nobody supplied. `max(0, 0 − MW)`
            // is zero for every market price, so settling it produced a
            // `Calculated` EUR 0 and a payout event for that amount, which reads
            // downstream as "correctly settled, nothing due". A missing AW is
            // exactly as fatal as a missing Marktwert and is reported the same way.
            //
            // Zero is only ever a *derived* AW: §54 Abs. 4, §51b and §51 all set it
            // to null explicitly, and each does so after this point.
            if raw_aw_ct <= Decimal::ZERO {
                return SettleOutput {
                    settlement_eur: None,
                    eligible_kwh: None,
                    positions: vec![crate::model::SettlePosition {
 description: "Marktpr\u{00e4}mie ohne anzulegenden Wert: direktverm_aw_ct fehlt oder ist null"
                            .to_owned(),
                        legal_basis: "\u{00a7}20 EEG 2023 i.V.m. Anlage 1".to_owned(),
                        kwh: Decimal::ZERO,
                        rate_ct_kwh: Decimal::ZERO,
                        eur: Decimal::ZERO,
                    }],
                    status: SettlementStatus::PriceMissing,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            }

            // ── §51b EEG 2023 — Biogas Ausschreibung at slightly-positive prices ──
            // For biogas plants (excl. biomethane) whose AW was set by auction:
            // the AW reduces to ZERO when EPEX ≤ 2 ct/kWh.
            // §51 and §51a do NOT apply to these plants (§51b Satz 2 EEG 2023).
            //
            // Source: EEG 2023 §51b, Clearingstelle EEG|KWKG Working Text 23.12.2025.
            // "verringert sich der anzulegende Wert auf null für Zeiträume, in denen
            //  der Spotmarktpreis 2 Cent pro Kilowattstunde oder weniger beträgt."
            //
            // § 101 Abs. 2 put § 51b under a Genehmigungsvorbehalt; the European
            // Commission granted it on 18.09.2025, and § 51b names no fallback
            // version, so there was nothing to apply before that day. A
            // settlement of an earlier period must not zero the AW — near-zero
            // spot prices were common well before then, and doing so withholds a
            // payment that was owed.
            if input.tariff_source.is_biogas_sect51b()
                && crate::version::sect51b_anwendbar(input.billing_date)
                && epex_ct <= dec!(2)
            {
                // AW = 0 for this period; payment is zero.
                return SettleOutput {
                    settlement_eur: Some(Decimal::ZERO),
                    eligible_kwh: input.einspeisemenge_kwh,
                    positions: vec![pos(
                        "\u{00a7}51b EEG 2023 Biogasanlage Ausschreibung \
                         (Spotmarktpreis \u{2264} 2\u{202f}ct/kWh \u{2192} AW = 0)",
                        "\u{00a7}51b EEG 2023",
                        kwh,
                        Decimal::ZERO,
                    )],
                    status: SettlementStatus::Calculated,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            }

            // ── §36h EEG — Wind onshore Korrekturfaktor ───────────────────────
            // When supplied (via wind_korrekturfaktor or wind_standort), multiply
            // the base AW by the location correction factor.
            // Applies only to wind onshore plants; §36h Abs. 4: no correction for ≤EEG2012.
            let aw_ct = if let Some(k) =
                resolve_wind_korrekturfaktor(*wind_korrekturfaktor, wind_standort.as_ref())
            {
                (raw_aw_ct * k).round_kfm(5)
            } else {
                raw_aw_ct
            };
            // §§53b–54 cut the AW before the max(0, …) floor below, so a plant
            // whose Marktwert already exceeds its AW is not driven negative.
            let (aw_ct, aw_cuts) = apply_aw_cuts(aw_ct, input);
            // ── §39n EEG 2023 — Innovationsausschreibung: feste Marktprämie ───
            // Innovation-auction awards pay a FIXED premium (the Zuschlagswert per
            // kWh, §3 InnAusV) on top of the market sale — it is not reduced by the
            // Monatsmarktwert like the gleitende Marktprämie. §39n Abs. 3 delegates
            // the mechanism to the Innovationsausschreibungsverordnung (§88d); the
            // fixed-premium rule is the defining InnAusV feature. §51 still zeroes
            // the AW for negative-price intervals, which `effective` already
            // carries, so no separate handling is needed here.
            if input.tariff_source.is_innovation_auction() {
                let feste_praemie_eur = validated_eur(effective * aw_ct / Decimal::from(100));
                let mut positions = vec![pos(
                    "Feste Marktpr\u{00e4}mie \u{00a7}39n EEG 2023 (Innovationsausschreibung, \u{00a7}3 InnAusV)",
                    "\u{00a7}39n EEG 2023 i.V.m. \u{00a7}3 InnAusV",
                    effective,
                    aw_ct,
                )];
                positions.extend(aw_cut_positions(&aw_cuts, effective));
                return SettleOutput {
                    settlement_eur: Some(feste_praemie_eur),
                    eligible_kwh: Some(effective),
                    positions,
                    status: SettlementStatus::Calculated,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            }

            // ── Anlage 1 Nr. 3.1.2 / 4.1.2 EEG 2023 — MP = AW − MW ────────────
            // Floored at zero: "Ergibt sich bei der Berechnung ein Wert kleiner
            // null, wird … der Wert 'MP' mit null festgesetzt."
            let praemie_ct = (aw_ct - epex_ct).max(Decimal::ZERO);

            let (praemie_desc, praemie_basis) = if input.tariff_source.is_auction() {
                (
                    "Gleitende Marktpr\u{00e4}mie \u{00a7}\u{00a7}22a,28 EEG 2023 (Ausschreibung)",
                    "\u{00a7}\u{00a7}22a,28 EEG 2023",
                )
            } else if neg_kwh.is_some() {
                (
                    "Gleitende Marktpr\u{00e4}mie \u{00a7}23a EEG 2023 (\u{00a7}51 Negativpreisregel angewendet)",
                    "\u{00a7}23a EEG 2023 i.V.m. Anlage 1",
                )
            } else {
                (
                    "Gleitende Marktpr\u{00e4}mie \u{00a7}23a EEG 2023",
                    "\u{00a7}23a EEG 2023 i.V.m. Anlage 1",
                )
            };

            // A zero premium still gets a position: MW ≥ AW is a settled result,
            // not a missing one, and the Gutschrift has to show the period.
            let mut positions = vec![pos(praemie_desc, praemie_basis, effective, praemie_ct)];
            // Name every statute that cut the AW, even where the floor absorbed it.
            positions.extend(aw_cut_positions(&aw_cuts, effective));

            let total_eur = positions.iter().map(|p| p.eur).sum();
            SettleOutput {
                settlement_eur: Some(total_eur),
                eligible_kwh: Some(effective),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── Post-EEG Spot (§21 post-Förderung + §23b cap) ─────────────────────
        // Negative EPEX → negative EUR (plant pays). No floor.
        // §23b EEG 2023: Jahresmarktwert capped at 10 ct/kWh for ausgeförderte Anlagen.
        SettlementScheme::PostEeg { price_floor } => {
            let Some(epex_ct) = input.marktwert_ct_kwh else {
                return SettleOutput {
                    settlement_eur: None,
                    eligible_kwh: None,
                    positions: vec![],
                    status: SettlementStatus::PriceMissing,
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            };
            // §23b EEG 2023: "ab dem Kalenderjahr 2023 höchstens jedoch 10 Cent pro kWh"
            // The cap only applies when EPEX is POSITIVE (the plant gets at most 10 ct).
            //
            // Negative EPEX: whether the plant pays depends on the post-EEG marketing
            // contract — NOT a statutory rule. Use post_eeg_price_floor to configure:
            //   None            = full market exposure (default, EPEX used as-is)
            //   Some(ZERO)      = floor at 0 (no obligation for negative periods)
            //   Some(custom)    = contract-defined floor
            let epex_floored = if let Some(floor) = *price_floor {
                epex_ct.max(floor)
            } else {
                epex_ct
            };
            let effective_ct = if epex_floored > dec!(10) {
                dec!(10)
            } else {
                epex_floored
            };
            let was_capped = epex_floored > dec!(10);
            let desc = if was_capped {
                format!(
                    "Einspeiseverg\u{00fc}tung Post-EEG Spot \
                    (\u{00a7}23b Jahresmarktwert-Deckel: EPEX {:.2}\u{202f}ct \u{2192} 10\u{202f}ct)",
                    epex_ct
                )
            } else {
                "Einspeiseverg\u{00fc}tung Post-EEG Spot (\u{00a7}21 EEG, nach F\u{00f6}rderungsende)".to_owned()
            };
            let positions = vec![pos(
                desc,
                "\u{00a7}21 EEG (post-F\u{00f6}rderung)",
                kwh,
                effective_ct,
            )];
            SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(kwh),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── §7 KWKG 2023 — KWK-Zuschlag ──────────────────────────────────────
        SettlementScheme::KwkSurcharge {
            verguetungssatz_ct,
            kwh_paid_gesamt,
            max_kwh,
            jahres_restkontingent_kwh,
        } => {
            use crate::foerderdauer::kwk_eligible_kwh;

            let (eligible, limit_reached) = match (*kwh_paid_gesamt, *max_kwh) {
                (Some(paid), Some(max)) => kwk_eligible_kwh(kwh, paid, max),
                _ => (kwh, false),
            };
            // § 8 Abs. 4: „Der Zuschlag wird pro Kalenderjahr gezahlt für bis zu
            // … Vollbenutzungsstunden." The annual cap bounds the period on its
            // own; exhausting it ends the year, not the Förderung, so it does
            // not set `limit_reached` and it reports its own status.
            let nach_lifetime = eligible;
            let eligible = match *jahres_restkontingent_kwh {
                Some(rest) => eligible.min(rest.max(Decimal::ZERO)),
                None => eligible,
            };
            // Which counter ran out decides whether the plant is finished or
            // merely paused until 1 January.
            let jahreskontingent_erschoepft =
                eligible <= Decimal::ZERO && nach_lifetime > Decimal::ZERO;

            if eligible <= Decimal::ZERO {
                return SettleOutput {
                    settlement_eur: Some(Decimal::ZERO),
                    eligible_kwh: Some(Decimal::ZERO),
                    positions: vec![],
                    status: if jahreskontingent_erschoepft {
                        SettlementStatus::JahreskontingentErschoepft
                    } else {
                        SettlementStatus::FoerderungBeendet
                    },
                    pflichtzahlung_eur: None,
                    pflichtzahlung_faelligkeitsdatum: None,
                    verlaengerungsanspruch_qh: 0,
                    dezentrale_einspeisung_anspruch_verloren: false,
                    billing_days_fraction_applied: None,
                    faelligkeitsdatum: None,
                };
            }

            let desc = if limit_reached {
                format!(
                    "KWK-Zuschlag \u{00a7}7 KWKG 2023 (F\u{00f6}rderdauer-Endabrechnung: {eligible} von {kwh} kWh)"
                )
            } else {
                "KWK-Zuschlag \u{00a7}7 KWKG 2023".to_owned()
            };
            let positions = vec![pos(
                desc,
                "\u{00a7}7 KWKG 2023",
                eligible,
                *verguetungssatz_ct,
            )];
            let status = if limit_reached {
                SettlementStatus::FoerderungBeendet
            } else {
                SettlementStatus::Calculated
            };
            SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(eligible),
                positions,
                status,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── §50b EEG — Flexibilitätsprämie (bestehende Anlagen) ──────────────
        SettlementScheme::FlexibilityPremium {
            verguetungssatz_ct,
            flex_praemie_ct_kwh,
        } => {
            let effective = match neg_kwh {
                Some(n) => apply_negativpreis(kwh, n),
                None => kwh,
            };
            let Some(flex_ct) = *flex_praemie_ct_kwh else {
                return satz_fehlt(
                    "§50b Flexibilitätsprämie: flex_praemie_ct_kwh fehlt — die Prämie ist \
                     Bestandteil des Anspruchs, kein Aufschlag nach Ermessen",
                    "§50b EEG 2023",
                );
            };
            let base_desc = if neg_kwh.is_some() {
                "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG (\u{00a7}51 Negativpreisregel angewendet)"
            } else {
                "Einspeiseverg\u{00fc}tung \u{00a7}21 EEG"
            };
            let mut positions = vec![pos(
                base_desc,
                "\u{00a7}21 EEG 2023",
                effective,
                *verguetungssatz_ct,
            )];
            if flex_ct != Decimal::ZERO {
                positions.push(pos(
                    "Flexibilit\u{00e4}tspr\u{00e4}mie \u{00a7}50b EEG 2023 (bestehende Anlage)",
                    "\u{00a7}50b EEG 2023",
                    effective,
                    flex_ct,
                ));
            }
            SettleOutput {
                settlement_eur: total(&positions),
                eligible_kwh: Some(effective),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }

        // ── §50a EEG 2023 — Flexibilitätszuschlag (neue Anlagen) ─────────────
        // Capacity-based payment: EUR/kW/year (statutory: 100 EUR/kW/year).
        // leistung_kwp = additional flexible capacity in kW.
        // rate_eur_per_kw_year = annual rate per kW in EUR (100 EUR/kW/year).
        // Monthly = leistung_kwp × rate / 12.
        SettlementScheme::FlexibilitySurcharge {
            rate_eur_per_kw_year,
        } => {
            let Some(kw) = input.leistung_kwp else {
                return sect50a_ohne_leistung();
            };
            let rate_eur_per_kw_year = *rate_eur_per_kw_year;
            let monthly_eur = validated_eur(kw * rate_eur_per_kw_year / dec!(12));
            let positions = vec![SettlePosition {
                description: format!(
                    "Flexibilit\u{00e4}tszuschlag \u{00a7}50a EEG 2023 \
                    ({kw}\u{202f}kW \u{00d7} {rate_eur_per_kw_year}\u{202f}EUR/kW/Jahr \u{00f7} 12)"
                ),
                legal_basis: "\u{00a7}50a EEG 2023".to_owned(),
                kwh: kw,                           // semantic: kW flexible capacity, not kWh
                rate_ct_kwh: rate_eur_per_kw_year, // semantic: EUR/kW/year
                eur: monthly_eur,
            }];
            SettleOutput {
                settlement_eur: Some(monthly_eur),
                eligible_kwh: Some(kw),
                positions,
                status: SettlementStatus::Calculated,
                pflichtzahlung_eur: None,
                pflichtzahlung_faelligkeitsdatum: None,
                verlaengerungsanspruch_qh: 0,
                dezentrale_einspeisung_anspruch_verloren: false,
                billing_days_fraction_applied: None,
                faelligkeitsdatum: None,
            }
        }
    }
}

#[cfg(test)]
mod refusal_tests {
    use super::*;
    use crate::model::SettleInput;

    /// §50a prices the flexible capacity, so a settlement without it has no
    /// basis: it refuses instead of reporting a €0,00 Gutschrift as calculated.
    #[test]
    fn sect50a_ohne_leistung_kwp_verweigert_statt_null_euro() {
        for einspeisemenge_kwh in [None, Some(dec!(1000))] {
            let out = crate::calculate_settlement(&SettleInput {
                scheme: SettlementScheme::FlexibilitySurcharge {
                    rate_eur_per_kw_year: dec!(100),
                },
                leistung_kwp: None,
                einspeisemenge_kwh,
                ..SettleInput::default()
            });
            assert_eq!(out.status, SettlementStatus::NoData);
            assert_eq!(out.settlement_eur, None);
            assert!(out.positions[0].legal_basis.contains("50a"));
        }
    }

    /// A known flexible capacity settles §50a as `kw × rate / 12`.
    #[test]
    fn sect50a_mit_leistung_kwp_rechnet() {
        let out = crate::calculate_settlement(&SettleInput {
            scheme: SettlementScheme::FlexibilitySurcharge {
                rate_eur_per_kw_year: dec!(120),
            },
            leistung_kwp: Some(dec!(200)),
            ..SettleInput::default()
        });
        assert_eq!(out.status, SettlementStatus::Calculated);
        assert_eq!(out.settlement_eur, Some(dec!(2000)));
    }

    /// Choosing §21 Abs. 3 Mieterstrom asserts the Zuschlag is owed, so an
    /// absent rate refuses rather than degrading to the plain Einspeisevergütung.
    #[test]
    fn mieterstrom_ohne_zuschlagssatz_verweigert() {
        let out = crate::calculate_settlement(&SettleInput {
            scheme: SettlementScheme::TenantElectricity {
                verguetungssatz_ct: dec!(8.11),
                mieter_zuschlag_ct: None,
            },
            einspeisemenge_kwh: Some(dec!(500)),
            ..SettleInput::default()
        });
        assert_eq!(out.status, SettlementStatus::PriceMissing);
        assert_eq!(out.settlement_eur, None);
    }

    /// Choosing §50b asserts the Flexibilitätsprämie is owed, so an absent rate
    /// refuses rather than degrading to the plain Einspeisevergütung.
    #[test]
    fn flexibilitaetspraemie_ohne_satz_verweigert() {
        let out = crate::calculate_settlement(&SettleInput {
            scheme: SettlementScheme::FlexibilityPremium {
                verguetungssatz_ct: dec!(18.4),
                flex_praemie_ct_kwh: None,
            },
            einspeisemenge_kwh: Some(dec!(500)),
            ..SettleInput::default()
        });
        assert_eq!(out.status, SettlementStatus::PriceMissing);
        assert_eq!(out.settlement_eur, None);
    }

    /// §13a EnWG pays the curtailed kWh at the rate the plant would have earned.
    /// A scheme that carries no such rate refuses instead of compensating the
    /// Abregelung at 0 ct/kWh.
    #[test]
    fn einspeisemanagement_ohne_satz_verweigert() {
        for scheme in [
            SettlementScheme::PostEeg { price_floor: None },
            SettlementScheme::SonstigeDirektvermarktung,
        ] {
            let out = crate::calculate_settlement(&SettleInput {
                scheme,
                einspeisemenge_kwh: Some(dec!(1000)),
                marktwert_ct_kwh: Some(dec!(6.0)),
                einspeisemanagement_kwh: Some(dec!(300)),
                ..SettleInput::default()
            });
            assert_eq!(out.status, SettlementStatus::PriceMissing);
            assert!(
                out.positions
                    .iter()
                    .all(|p| !p.legal_basis.contains("13a") || p.rate_ct_kwh != Decimal::ZERO),
                "no §13a position may be booked at 0 ct/kWh"
            );
        }
    }
}