mako-mabis 0.20.0

MABIS process engine for German electricity market balance group accounting (Marktprozesse Bilanzkreisverantwortlicher)
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
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
//! MaBiS-Zählpunkt lifecycle — activation and deactivation of MaBiS-ZP,
//! Zuordnungsermächtigung, and the Ausfallarbeitsüberführungszeitreihen (AAÜZ)
//! series.
//!
//! # Process overview
//!
//! Every process in this family has the same shape: one party sends an
//! **Anfrage** that activates or deactivates a MaBiS-Zählpunkt for a given
//! series, and — depending on the family — the counterparty returns an
//! **Antwort**, after which the receiving party may forward a
//! **Weiterleitung** to a third party.
//!
//! ```text
//! Anfrage ──→ (Antwort) ──→ (Weiterleitung)
//!  step 1        step 2          step 4
//! ```
//!
//! # Both directions live here
//!
//! Which side of that line a deployment stands on is a property of the
//! *series*, not of the workflow, so this module models both:
//!
//! - **Requester** — [`ZpLifecycleCommand::SendAnfrage`] raises the
//!   Aktivierung/Deaktivierung and [`ZpLifecycleCommand::ReceiveAntwort`]
//!   consumes the answer. A Netzbetreiber activates its own MaBiS-Zählpunkte
//!   at the BIKO (BK6-24-174 Anlage 3 Kap. 5.2.2, 9.2.2, 10.4.2, 11.2.2,
//!   12.2.2, 17.3.3.1.2, 17.3.3.2.2, 17.3.5.1.2, 17.3.5.2.2, Nr. 1).
//! - **Answering party** — [`ZpLifecycleCommand::ReceiveAnfrage`],
//!   [`ZpLifecycleCommand::SendAntwort`] and
//!   [`ZpLifecycleCommand::SendWeiterleitung`].
//!
//! Both are reachable in one deployment because the **Netzzeitreihe axis is
//! NB → NB**: the verantwortlicher NB activates the MaBiS-ZP at the
//! benachbarter NB, so a Netzbetreiber both sends 55062/55063 and receives
//! them (Kap. 5.2.2 Nr. 1 and Nr. 4).
//!
//! ## Prozessschritt 2 is a published 1-Werktag window
//!
//! Every Use-Case in this family that has an Antwort step states it as
//! „Unverzüglich, spätestens jedoch **1 WT nach Erhalt** der Aktivierung"
//! resp. „der Deaktivierung", and the Hinweis adds that an Ablehnung „erfolgt
//! … **mit einer Begründung**". Hence [`ZpLifecycleCommand::ReceiveAntwort`]
//! refuses a rejection that carries none, exactly as
//! [`ZpLifecycleCommand::SendAntwort`] does.
//!
//! The window itself is published per Anfrage PID in
//! [`mako_fristen::antwort`] for the four monatliche-AAÜZ Use-Cases, whose
//! Anfrage codes belong to one series each. It is **not** published for
//! 55062/55063: those are shared by eleven series, five of which have no
//! Antwort step at all, and the „1 WT" that appears in *their* SD is a
//! Vorlauffrist „1 WT **vor** dem Versand" — a different clock in the opposite
//! direction.
//!
//! Only three of the six families carry an Antwort PID, and only two carry a
//! Weiterleitung. A family without an Antwort is **record-only**: the message
//! is validated and stored, and the process is terminal on arrival. Modelling
//! those as request/response would manufacture a deadline the AHB never
//! defines.
//!
//! # Prüfidentifikatoren
//!
//! Verified against the BDEW *Anwendungsübersicht Prüfidentifikatoren 4.0*
//! (01.04.2026), sheet *Prüf-ID Prozessschritt* — the Prozessschritt column is
//! what distinguishes an Anfrage (1) from an Antwort (2) and a Weiterleitung
//! (4).
//!
//! ## 55062 / 55063 / 55064 are generic codes, not one process
//!
//! This is the trap the family table exists to close. **55062 „Aktivierung von
//! ZP" and 55063 „Deaktivierung von ZP" are used for eleven different
//! Summenzeitreihen.** Six of the eleven owe a 55064 „Antwort" and five are
//! record-only, and the six are answered out of **twelve different
//! Entscheidungsbäumen** — a series with two directions gets one tree per
//! direction:
//!
//! | Serie | Achse | Antwort | EBD Aktivierung | EBD Deaktivierung |
//! |-------|-------|--------:|-----------------|-------------------|
//! | Netzzeitreihe | NB (verantw.) → NB (benachbart) | 55064 | `E_0020` | `E_0010` |
//! | Netzzeitreihe | NB (verantw.) → BIKO | 55064 | `E_0024` | `E_0009` |
//! | Lieferantensummenzeitreihe | NB → LF | — | — | — |
//! | Lieferantensummenzeitreihe | ÜNB → LF | — | — | — |
//! | Bilanzierungsgebietssummenzeitreihe | ÜNB → BIKO | 55064 | `E_0015` | `E_0035` |
//! | Bilanzkreissummenzeitreihe | NB → BIKO | 55064 | `E_0034` | `E_0018` |
//! | Bilanzkreissummenzeitreihe | ÜNB → BIKO | 55064 | `E_0011` | `E_0012` |
//! | Deltazeitreihenübertrag | ÜNB → BIKO | 55064 | `E_0027` | `E_0028` |
//! | Abrechnungssummenzeitreihe | BIKO → NB / BKV / ÜNB | — | — | — |
//! | tägliche Bilanzierungsgebietssummenzeitreihe | ÜNB → NB | — | — | — |
//! | tägliche Bilanzkreissummenzeitreihe | ÜNB → BKV | — | — | — |
//!
//! Three consequences follow, and none of them is derivable from the PID:
//!
//! - **Whether an Antwort is owed at all** varies by series. Six of the eleven
//!   owe a 55064 and five are record-only. A model that answers "55062 → 55064"
//!   invents five obligations; one that never answers drops six real ones.
//! - **Which Codeliste the answer comes from** varies by series *and*
//!   direction. A code read against the wrong tree means something else there —
//!   the same trap `A02` sets across the GPKE trees.
//! - **The Weiterleitung re-uses the request code.** For the four series that
//!   have one, Prozessschritt 4 is another 55062/55063 addressed to the
//!   downstream party, not a distinct PID.
//!
//! [`ZpSerie`] therefore carries the series *and* its axis, and it is an
//! explicit input: the MaBiS-Zählpunkt is created **for** one Summenzeitreihe,
//! so the caller always knows which.
//!
//! ## The series with their own codes
//!
//! | Serie | Anfrage | Antwort | EBD | Weiterleitung |
//! |-------|--------:|--------:|-----|--------------:|
//! | Zuordnungsermächtigung (BKV → NB) | 55071 / 55072 | — | — | — |
//! | tägliche AAÜZ (NB (ANB) → ÜNB) | 55197 / 55198 | — | — | — |
//! | LF-AASZR (NB (ANB) → LF) | 55199 / 55200 | — | — | — |
//! | monatliche AAÜZ, BKV des LF (NB (ANB) → BIKO) | 55203 / 55206 | 55204 / 55207 | `E_0071` / `E_0072` | 55205 / 55208 |
//! | monatliche AAÜZ, BKV des anfNB (NB (ANB) → BIKO) | 55209 / 55212 | 55210 / 55213 | `E_0078` / `E_0079` | 55211 / 55214 |
//!
//! ## The tägliche AAÜZ expires on 30.09.2026
//!
//! 55197/55198 implement MaBiS Anlage 1 **Kapitel 17.2**, which BK6-23-241
//! Tenorziffer 5 repeals with the end of **30.09.2026**. Unlike the rest of
//! Kapitel 17 it is *not* republished as the Anlage zur BilAReM: 17.2 and
//! 17.3.2.1 are the two parts that simply stop. [`ZpSerie::endet_am`] carries
//! the date so a deployment can refuse to activate a Zählpunkt for a series
//! that will not exist when the month it settles is due.
//!
//! # Not in this family
//!
//! 55218 and 55220 (Abr.-Daten NNA) sit in the same numeric neighbourhood but
//! belong to **GPKE Teil 2**, not MaBiS. 55215–55217, 55219, 55221 and 55222
//! are unassigned. Neither group is routed here.
//!
//! # Regulatory basis
//!
//! - **BNetzA BK6-24-174 Anlage 3 (MaBiS)** — Bilanzkreisabrechnung, ZP
//!   activation and the AAÜZ series
//! - **UTILMD AHB Strom S2.1 / S2.2** — message format
//!
//! # State machine
//!
//! Two arms leave `New`, one per direction.
//!
//! ```text
//! New
//!  ├─ AnfrageErhalten ─┬─ (validation failed) ─→ ValidationFailed  (terminal)
//!  │   (we answer)     ├─ (no Antwort PID)    ─→ Erfasst           (terminal)
//!  │                   └─ AntwortGesendet ────┬─ (abgelehnt) ──────→ Abgelehnt (terminal)
//!  │                                          └─ (bestätigt) ──────→ Bestaetigt
//!  │                                               └─ WeiterleitungGesendet → Weitergeleitet (terminal)
//!  └─ AnfrageGesendet ─── AntwortErhalten ────┬─ (abgelehnt) ──────→ Abgelehnt         (terminal)
//!      (we ask)                               └─ (bestätigt) ──────→ AntwortBestaetigt (terminal)
//! ```
//!
//! The two positive outcomes are separate states because only the **answering**
//! party forwards. `SendWeiterleitung` is Prozessschritt 4 of the party that
//! ran the Prüfung — „Der BIKO leitet nur den nicht abgelehnten MaBiS-ZP an den
//! BKV … weiter" — so a requester that reached agreement by *receiving* an
//! Antwort must not be able to reach it. Folding both into `Bestaetigt` would
//! make that dispatch representable.

//! # On the wire
//!
//! `BGM+Z07` „Aktivierung/Deaktivierung von MaBiS-ZP" — not the `E01` an
//! Anmeldung uses, because a Zählpunkt is activated rather than angemeldet.
//! The object is a **MaBiS-Zählpunkt** in `SG5 LOC+Z15` and no Marktlokation;
//! the date is `SG4 DTM+158` Bilanzierungsbeginn on an Aktivierung and
//! `DTM+159` Bilanzierungsende on a Deaktivierung, never a Vertragsdatum
//! (UTILMD AHB Strom 2.2 Kap. 13.3).
//!
//! The 55064 answer carries `SG4 STS+E01` DE 1131 — which of the twelve
//! Entscheidungsbäume decided it — but **not** DE 9013. Only `E_0010` and
//! `E_0020` have walks in `mako_pruefung::mabis::zp`; the other ten publish
//! codes this workspace has not catalogued, and a fabricated Prüfschritt on a
//! message that settles a Bilanzkreisabrechnung is worse than an absent one.
//!

use mako_engine::{
    error::WorkflowError,
    outbox::PendingOutbox,
    types::{BillingPeriod, MarktpartnerCode, MessageRef, Pruefidentifikator},
    workflow::{CommandPayload, EventPayload, Workflow, WorkflowOutput},
};

// ── Family table ──────────────────────────────────────────────────────────────

/// Whether the Anfrage activates or deactivates the series.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ZpVorgang {
    /// Aktivierung — the MaBiS-ZP starts contributing to the series.
    Aktivierung,
    /// Deaktivierung — the MaBiS-ZP stops contributing.
    Deaktivierung,
}

/// Which MaBiS series — and on which axis — the Anfrage activates or
/// deactivates.
///
/// The axis is part of the identity, not decoration: the Netzzeitreihe is
/// activated twice, once toward the neighbouring NB and once toward the BIKO,
/// and the two are answered out of different Entscheidungsbäume.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ZpSerie {
    /// Netzzeitreihe, verantwortlicher NB → benachbarter NB.
    NetzzeitreiheNachbarNb,
    /// Netzzeitreihe, verantwortlicher NB → BIKO.
    NetzzeitreiheBiko,
    /// Lieferantensummenzeitreihe (Kategorie A), NB → LF.
    LieferantensummenzeitreiheNb,
    /// Lieferantensummenzeitreihe (Kategorie B), ÜNB → LF.
    LieferantensummenzeitreiheUenb,
    /// Bilanzierungsgebietssummenzeitreihe, ÜNB → BIKO, weitergeleitet an den NB.
    Bilanzierungsgebietssummenzeitreihe,
    /// Bilanzkreissummenzeitreihe (Kategorie A), NB → BIKO, weitergeleitet an den BKV.
    BilanzkreissummenzeitreiheNb,
    /// Bilanzkreissummenzeitreihe (Kategorie B), ÜNB → BIKO, weitergeleitet an den BKV.
    BilanzkreissummenzeitreiheUenb,
    /// Deltazeitreihenübertrag, ÜNB → BIKO, weitergeleitet an den NB.
    Deltazeitreihenuebertrag,
    /// Abrechnungssummenzeitreihe, BIKO → NB / BKV / ÜNB.
    Abrechnungssummenzeitreihe,
    /// Tägliche Bilanzierungsgebietssummenzeitreihe, ÜNB → NB.
    TaeglicheBgSzr,
    /// Tägliche Bilanzkreissummenzeitreihe, ÜNB → BKV.
    TaeglicheBkSzr,
    /// Zuordnungsermächtigung des BKV beim NB (55071/55072).
    Zuordnungsermaechtigung,
    /// Tägliche Ausfallarbeitsüberführungszeitreihe (55197/55198), NB (ANB) → ÜNB.
    ///
    /// MaBiS Kap. 17.2 — repealed with the end of 30.09.2026 and **not**
    /// republished as the Anlage zur BilAReM.
    TaeglicheAauez,
    /// Lieferantenausfallarbeitssummenzeitreihe (55199/55200), NB (ANB) → LF.
    LfAaszr,
    /// Monatliche AAÜZ, forwarded to the BKV of the Lieferant (55203–55208).
    MonatlicheAauezBkvLf,
    /// Monatliche AAÜZ, forwarded to the BKV of the anfordernder NB (55209–55214).
    MonatlicheAauezBkvAnfNb,
    /// Zuordnung des Zählpunkts der **Netzgangzeitreihe** zur Netzzeitreihe
    /// (55235/55236/55237), verantwortlicher NB → benachbarter NB, informiert
    /// an den ÜNB.
    ///
    /// The NZR-EMob leg: a Modell-2 Übergabestelle's Netzgangzeitreihe has to
    /// be assigned to the receiving NB's Netzzeitreihe before any value flows
    /// (BDEW AWH Ergänzung MaBiS Netzgangzeitreihe Kap. 1.8.2). It is **MaBiS
    /// rather than Modell 2** — UTILMD AHB Strom 2.2 Kap. 13.16, answered from
    /// `E_0102`/`E_0103` — which is why it lives here and not in `mako-emob`.
    ///
    /// Unlike the 55062/55063 families this one has its own Anfrage codes, so
    /// [`Self::from_wire`] never returns it: there is nothing to disambiguate.
    NetzgangzeitreiheNzr,
}

/// Last day the tägliche AAÜZ process exists — BK6-23-241 Tenorziffer 5 repeals
/// MaBiS Anlage 1 Kap. 17.2 with the end of this day.
///
/// The tägliche AAÜZ **is** Kap. 17.2, so this is
/// [`crate::zeitreihen::KAPITEL_17_2_ENDE`] under the name the Zählpunkt side
/// asks for it by, not a second reading of the Tenor.
pub const TAEGLICHE_AAUEZ_ENDE: time::Date = crate::zeitreihen::KAPITEL_17_2_ENDE;

impl ZpSerie {
    /// Canonical BDEW name of the series, including its axis.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::NetzzeitreiheNachbarNb => "Netzzeitreihe (NB → benachbarter NB)",
            Self::NetzzeitreiheBiko => "Netzzeitreihe (NB → BIKO)",
            Self::LieferantensummenzeitreiheNb => "Lieferantensummenzeitreihe (NB → LF)",
            Self::LieferantensummenzeitreiheUenb => "Lieferantensummenzeitreihe (ÜNB → LF)",
            Self::Bilanzierungsgebietssummenzeitreihe => "Bilanzierungsgebietssummenzeitreihe",
            Self::BilanzkreissummenzeitreiheNb => "Bilanzkreissummenzeitreihe (NB → BIKO)",
            Self::BilanzkreissummenzeitreiheUenb => "Bilanzkreissummenzeitreihe (ÜNB → BIKO)",
            Self::Deltazeitreihenuebertrag => "Deltazeitreihenübertrag",
            Self::Abrechnungssummenzeitreihe => "Abrechnungssummenzeitreihe",
            Self::TaeglicheBgSzr => "tägliche Bilanzierungsgebietssummenzeitreihe",
            Self::TaeglicheBkSzr => "tägliche Bilanzkreissummenzeitreihe",
            Self::Zuordnungsermaechtigung => "Zuordnungsermächtigung",
            Self::TaeglicheAauez => "tägliche AAÜZ",
            Self::LfAaszr => "LF-AASZR",
            Self::MonatlicheAauezBkvLf => "monatliche AAÜZ (BKV des LF)",
            Self::MonatlicheAauezBkvAnfNb => "monatliche AAÜZ (BKV des anfordernden NB)",
            Self::NetzgangzeitreiheNzr => "Zuordnung ZP der NGZ zur NZR",
        }
    }

    /// The last day this series exists, where a Festlegung ends it.
    ///
    /// Only the tägliche AAÜZ has one: BK6-23-241 Tenorziffer 5 repeals MaBiS
    /// Anlage 1 Kap. 17.2 with the end of 30.09.2026, and — unlike Kap. 17.1
    /// and 17.3 — it is not republished as the Anlage zur BilAReM.
    #[must_use]
    pub fn endet_am(self) -> Option<time::Date> {
        match self {
            Self::TaeglicheAauez => Some(TAEGLICHE_AAUEZ_ENDE),
            _ => None,
        }
    }

    /// Whether the series still exists on `date`.
    #[must_use]
    pub fn gilt_am(self, date: time::Date) -> bool {
        self.endet_am().is_none_or(|ende| date <= ende)
    }

    /// Resolve the series from what the UTILMD actually carries.
    ///
    /// The two codes together are the discriminator 55062/55063 lack:
    ///
    /// - `cav` — `SG10 CCI+++ZB4` / `CAV` DE 7111 „Bezeichnung der
    ///   Summenzeitreihe" ([`crate::zeitreihen::zeitreihe_aus_cav`]).
    /// - `verantwortlicher` — `SG10 CCI+6` DE 7037, the role responsible for
    ///   the series ([`crate::zeitreihen::rolle_aus_cci`]).
    ///
    /// The Verantwortliche is needed because two pairs of families share a CAV
    /// code and differ only in who owns the series: the BK-SZR is `Z97`/`Z99`
    /// whether the NB or the ÜNB aggregates it, and the LF-SZR likewise. Those
    /// pairs answer out of different Entscheidungsbäume, so collapsing them
    /// would send a code from the wrong tree.
    ///
    /// Returns `None` when the pair names no family here — including every
    /// series with its own Anfrage PID (Zuordnungsermächtigung, AAÜZ, LF-AASZR),
    /// which is not activated with 55062/55063 at all.
    #[must_use]
    pub fn from_wire(cav: &str, verantwortlicher: &str) -> Option<Self> {
        use crate::zeitreihen::{Aggregationsebene as E, Familie as F, Kategorie as K, Rolle};
        let (zeitreihe, ebene) = crate::zeitreihen::zeitreihe_aus_cav(cav)?;
        let rolle = crate::zeitreihen::rolle_aus_cci(verantwortlicher)?;
        Some(
            match (zeitreihe.familie(), zeitreihe.kategorie(), ebene, rolle) {
                (F::Nzr, _, _, Rolle::Nb) => {
                    // Both Netzzeitreihe legs are the verantwortlicher NB's, and
                    // the AHB does not distinguish them here — the recipient
                    // does. `from_wire` therefore returns the BIKO leg, and a
                    // caller that knows it is answering a neighbouring NB names
                    // `NetzzeitreiheNachbarNb` explicitly.
                    Self::NetzzeitreiheBiko
                }
                (F::LfSzr, Some(K::A), _, _) => Self::LieferantensummenzeitreiheNb,
                (F::LfSzr, Some(K::B), _, _) => Self::LieferantensummenzeitreiheUenb,
                (F::BgSzr, Some(K::B), _, _) => Self::Bilanzierungsgebietssummenzeitreihe,
                (F::BgSzr, Some(K::C), _, _) => Self::TaeglicheBgSzr,
                (F::BkSzr, Some(K::A), _, _) => Self::BilanzkreissummenzeitreiheNb,
                (F::BkSzr, Some(K::B), Some(E::Bilanzierungsgebiet), _) => {
                    Self::BilanzkreissummenzeitreiheUenb
                }
                (F::BkSzr, Some(K::C), _, _) => Self::TaeglicheBkSzr,
                (F::Dzue, _, _, _) => Self::Deltazeitreihenuebertrag,
                (F::Abrechnungssummenzeitreihe, _, _, _) => Self::Abrechnungssummenzeitreihe,
                _ => return None,
            },
        )
    }
}

/// One row of the Anfrage → Antwort → Weiterleitung table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZpFamilie {
    /// Series and axis this row describes.
    pub serie: ZpSerie,
    /// Whether this row activates or deactivates.
    pub vorgang: ZpVorgang,
    /// Inbound Anfrage Prüfidentifikator (Prozessschritt 1).
    pub anfrage: u32,
    /// Outbound Antwort PID (Prozessschritt 2), when the AHB defines one.
    pub antwort: Option<u32>,
    /// EBD the answering party runs to build that Antwort.
    ///
    /// Always `Some` exactly when [`Self::antwort`] is: an answer PID without a
    /// decision tree would be a code with no Codeliste to read it against.
    pub antwort_ebd: Option<&'static str>,
    /// Outbound Weiterleitung PID (Prozessschritt 4), when the AHB defines one.
    ///
    /// For the series that share 55062/55063 this is the **same code again**,
    /// re-addressed to the downstream party.
    pub weiterleitung: Option<u32>,
}

/// Every Anfrage this workflow accepts, with its answer tree and forwarding PID.
///
/// This table is the single source of truth: the workflow never computes an
/// answer PID or an EBD from the request. BDEW does not number these `+1/+2` —
/// 55062 and 55063 share the Antwort 55064 across eleven series, and each
/// (series, axis, direction) reads it out of a different tree.
pub const ZP_FAMILIEN: &[ZpFamilie] = &[
    // ── Series sharing the generic 55062 / 55063 / 55064 codes ──────────────
    ZpFamilie {
        serie: ZpSerie::NetzzeitreiheNachbarNb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0020"),
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::NetzzeitreiheNachbarNb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0010"),
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::NetzzeitreiheBiko,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0024"),
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::NetzzeitreiheBiko,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0009"),
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LieferantensummenzeitreiheNb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LieferantensummenzeitreiheNb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LieferantensummenzeitreiheUenb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LieferantensummenzeitreiheUenb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::Bilanzierungsgebietssummenzeitreihe,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0015"),
        // Prozessschritt 4: the BIKO re-sends 55062 to the NB.
        weiterleitung: Some(55062),
    },
    ZpFamilie {
        serie: ZpSerie::Bilanzierungsgebietssummenzeitreihe,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0035"),
        weiterleitung: Some(55063),
    },
    ZpFamilie {
        serie: ZpSerie::BilanzkreissummenzeitreiheNb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0034"),
        weiterleitung: Some(55062),
    },
    ZpFamilie {
        serie: ZpSerie::BilanzkreissummenzeitreiheNb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0018"),
        weiterleitung: Some(55063),
    },
    ZpFamilie {
        serie: ZpSerie::BilanzkreissummenzeitreiheUenb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0011"),
        weiterleitung: Some(55062),
    },
    ZpFamilie {
        serie: ZpSerie::BilanzkreissummenzeitreiheUenb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0012"),
        weiterleitung: Some(55063),
    },
    ZpFamilie {
        serie: ZpSerie::Deltazeitreihenuebertrag,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: Some(55064),
        antwort_ebd: Some("E_0027"),
        weiterleitung: Some(55062),
    },
    ZpFamilie {
        serie: ZpSerie::Deltazeitreihenuebertrag,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: Some(55064),
        antwort_ebd: Some("E_0028"),
        weiterleitung: Some(55063),
    },
    ZpFamilie {
        serie: ZpSerie::Abrechnungssummenzeitreihe,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::Abrechnungssummenzeitreihe,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheBgSzr,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheBgSzr,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheBkSzr,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55062,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheBkSzr,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55063,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    // ── Series with their own codes ─────────────────────────────────────────
    ZpFamilie {
        serie: ZpSerie::Zuordnungsermaechtigung,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55071,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::Zuordnungsermaechtigung,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55072,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheAauez,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55197,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::TaeglicheAauez,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55198,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LfAaszr,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55199,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::LfAaszr,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55200,
        antwort: None,
        antwort_ebd: None,
        weiterleitung: None,
    },
    ZpFamilie {
        serie: ZpSerie::MonatlicheAauezBkvLf,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55203,
        antwort: Some(55204),
        antwort_ebd: Some("E_0071"),
        weiterleitung: Some(55205),
    },
    ZpFamilie {
        serie: ZpSerie::MonatlicheAauezBkvLf,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55206,
        antwort: Some(55207),
        antwort_ebd: Some("E_0072"),
        weiterleitung: Some(55208),
    },
    ZpFamilie {
        serie: ZpSerie::MonatlicheAauezBkvAnfNb,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55209,
        antwort: Some(55210),
        antwort_ebd: Some("E_0078"),
        weiterleitung: Some(55211),
    },
    ZpFamilie {
        serie: ZpSerie::MonatlicheAauezBkvAnfNb,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55212,
        antwort: Some(55213),
        antwort_ebd: Some("E_0079"),
        weiterleitung: Some(55214),
    },
    // ── NZR-EMob: Zuordnung des ZP der NGZ zur NZR (AHB Strom 2.2 Kap. 13.16) ─
    //
    // One Antwort code for both directions — 55237 answers the Zuordnung out of
    // `E_0102` and the Beendigung out of `E_0103`, which is exactly why the
    // Antwort PID and the EBD are separate columns in this table.
    //
    // The Weiterleitung is the **same code re-addressed to the ÜNB**: the AHB
    // gives 55235/55236 two recipients („NB an NB" and „NB an ÜNB") while 55237
    // is „NB an NB" only, and the AWH sequences the ÜNB copy *after* the answer
    // (Lfd 19150 follows 19130). `SendWeiterleitung` requires `Bestaetigt`, so
    // that ordering is the state machine's rather than a convention.
    ZpFamilie {
        serie: ZpSerie::NetzgangzeitreiheNzr,
        vorgang: ZpVorgang::Aktivierung,
        anfrage: 55235,
        antwort: Some(55237),
        antwort_ebd: Some("E_0102"),
        weiterleitung: Some(55235),
    },
    ZpFamilie {
        serie: ZpSerie::NetzgangzeitreiheNzr,
        vorgang: ZpVorgang::Deaktivierung,
        anfrage: 55236,
        antwort: Some(55237),
        antwort_ebd: Some("E_0103"),
        weiterleitung: Some(55236),
    },
];

/// Look up the family for one series and Vorgang.
///
/// This is the only lookup: the Anfrage PID alone does **not** identify a
/// family, because 55062/55063 are shared by eleven series with five different
/// answer obligations between them.
#[must_use]
pub fn familie_for(serie: ZpSerie, vorgang: ZpVorgang) -> Option<&'static ZpFamilie> {
    ZP_FAMILIEN
        .iter()
        .find(|f| f.serie == serie && f.vorgang == vorgang)
}

/// Every series that uses `anfrage` as its Anfrage PID.
///
/// Useful for diagnostics — an inbound 55062 is ambiguous until the caller says
/// which Summenzeitreihe its MaBiS-Zählpunkt belongs to.
#[must_use]
pub fn serien_fuer_pid(anfrage: u32) -> Vec<ZpSerie> {
    ZP_FAMILIEN
        .iter()
        .filter(|f| f.anfrage == anfrage)
        .map(|f| f.serie)
        .collect()
}

/// Whether `pid` is an **Antwort** code of some family (Prozessschritt 2).
///
/// Asked after [`serien_fuer_pid`]: the two spaces do not overlap today, and
/// the Anfrage question is the one that must be answered first, because for the
/// eleven generic series Prozessschritt 4 re-uses the *request* code.
#[must_use]
pub fn ist_antwort_pid(pid: u32) -> bool {
    ZP_FAMILIEN.iter().any(|f| f.antwort == Some(pid))
}

/// Whether `pid` is a **Weiterleitung** code of some family (Prozessschritt 4).
///
/// `true` for 55062/55063/55235/55236 as well, which are Anfrage codes
/// re-addressed downstream — so a caller routing an inbound message asks
/// [`serien_fuer_pid`] first and this only for what is left.
#[must_use]
pub fn ist_weiterleitung_pid(pid: u32) -> bool {
    ZP_FAMILIEN.iter().any(|f| f.weiterleitung == Some(pid))
}

/// Every PID this workflow is registered for — Anfragen, Antworten and
/// Weiterleitungen alike.
///
/// The Antwort and Weiterleitung PIDs are registered because mako may sit on
/// either side: as the answering party it *emits* them, and as the requesting
/// party it *receives* them.
#[must_use]
pub fn all_pids() -> Vec<u32> {
    let mut v: Vec<u32> = ZP_FAMILIEN
        .iter()
        .flat_map(|f| [Some(f.anfrage), f.antwort, f.weiterleitung])
        .flatten()
        .collect();
    v.sort_unstable();
    v.dedup();
    v
}

/// Whether the Antwortcode `code`, read against the Entscheidungsbaum `ebd`,
/// agrees with the Anfrage.
///
/// `None` when `ebd` is a tree this workspace has not catalogued, or when the
/// tree publishes no such code. Both mean the same thing to a caller: the
/// Cluster is **unknown**, and it must not be assumed. The code alone cannot
/// supply it — `A01` is an Ablehnung in `E_0071` and a Zustimmung elsewhere —
/// so a caller that reads `None` as „Ablehnung" refuses answers that agreed.
///
/// Of the sixteen trees [`ZP_FAMILIEN`] names, `mako_pruefung::mabis` publishes
/// `E_0010`, `E_0020`, `E_0102` and `E_0103`.
#[must_use]
pub fn antwort_ist_zustimmung(ebd: &str, code: &str) -> Option<bool> {
    mako_pruefung::mabis::codes::lookup(ebd, code).and_then(|c| c.ist_zustimmung())
}

/// Stable workflow name for process routing.
pub const WORKFLOW_NAME: &str = "mabis-zp-lifecycle";

// ── Domain data ───────────────────────────────────────────────────────────────

/// Data captured when a lifecycle Anfrage is received.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZpLifecycleData {
    /// Prüfidentifikator of the inbound Anfrage.
    pub pruefidentifikator: Pruefidentifikator,
    /// Activation or deactivation.
    pub vorgang: ZpVorgang,
    /// Series affected.
    pub serie: ZpSerie,
    /// MaBiS-Zählpunkt the Anfrage refers to.
    pub mabis_zp_id: String,
    /// GLN of the requesting party.
    pub sender: MarktpartnerCode,
    /// GLN of the receiving party.
    pub receiver: MarktpartnerCode,
    /// Billing period the activation takes effect in.
    pub billing_period: BillingPeriod,
    /// EDIFACT document date (`YYYYMMDD`).
    pub document_date: String,
    /// EDIFACT message reference of the Anfrage.
    pub message_ref: MessageRef,
}

// ── Domain events ─────────────────────────────────────────────────────────────

/// Events emitted by the MaBiS-ZP lifecycle workflow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum ZpLifecycleEvent {
    /// Inbound Anfrage received and recorded.
    AnfrageErhalten {
        /// Prüfidentifikator of the Anfrage.
        pruefidentifikator: Pruefidentifikator,
        /// Activation or deactivation.
        vorgang: ZpVorgang,
        /// Series affected.
        serie: ZpSerie,
        /// MaBiS-Zählpunkt the Anfrage refers to.
        mabis_zp_id: String,
        /// GLN of the requesting party.
        sender: MarktpartnerCode,
        /// GLN of the receiving party.
        receiver: MarktpartnerCode,
        /// Billing period the activation takes effect in.
        billing_period: BillingPeriod,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
    },
    /// Outbound Anfrage dispatched to the answering party.
    AnfrageGesendet {
        /// Prüfidentifikator of the Anfrage, taken from [`ZP_FAMILIEN`].
        pruefidentifikator: Pruefidentifikator,
        /// Activation or deactivation.
        vorgang: ZpVorgang,
        /// Series affected.
        serie: ZpSerie,
        /// MaBiS-Zählpunkt the Anfrage names.
        mabis_zp_id: crate::MabisZaehlpunktId,
        /// GLN of this participant, the requesting party.
        sender: MarktpartnerCode,
        /// GLN of the answering party.
        empfaenger: MarktpartnerCode,
        /// Billing period the activation takes effect in.
        billing_period: BillingPeriod,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
    },
    /// Inbound Antwort to an Anfrage this participant sent.
    AntwortErhalten {
        /// Antwort Prüfidentifikator that arrived.
        antwort_pid: Pruefidentifikator,
        /// EBD the Antwortcode was read against — `SG4 STS+E01` DE 1131.
        ebd: String,
        /// `true` when the Anfrage was confirmed.
        bestaetigt: bool,
        /// Begründung, when `bestaetigt` is `false`.
        grund: Option<String>,
        /// EDIFACT message reference of the Antwort.
        message_ref: MessageRef,
    },
    /// Anfrage recorded with no Antwort obligation (terminal for that family).
    Erfasst {
        /// Reference of the recorded message.
        message_ref: MessageRef,
    },
    /// Outbound Antwort dispatched.
    AntwortGesendet {
        /// Antwort Prüfidentifikator actually sent.
        antwort_pid: Pruefidentifikator,
        /// EBD the Antwortcode was read against — recorded because 55064 is
        /// answered out of twelve different trees.
        ebd: String,
        /// `true` when the Anfrage was confirmed.
        bestaetigt: bool,
        /// Rejection reason, when `bestaetigt` is `false`.
        grund: Option<String>,
    },
    /// Outbound Weiterleitung dispatched to the downstream BKV.
    WeiterleitungGesendet {
        /// Weiterleitung Prüfidentifikator actually sent.
        weiterleitung_pid: Pruefidentifikator,
        /// GLN of the BKV the Weiterleitung was addressed to.
        empfaenger: MarktpartnerCode,
    },
    /// Inbound message failed AHB validation (terminal).
    ValidationFailed {
        /// Human-readable summary of validation errors.
        reason: String,
    },
}

impl EventPayload for ZpLifecycleEvent {
    fn event_type(&self) -> &'static str {
        match self {
            Self::AnfrageErhalten { .. } => "MabisZpAnfrageErhalten",
            Self::AnfrageGesendet { .. } => "MabisZpAnfrageGesendet",
            Self::AntwortErhalten { .. } => "MabisZpAntwortErhalten",
            Self::Erfasst { .. } => "MabisZpErfasst",
            Self::AntwortGesendet { .. } => "MabisZpAntwortGesendet",
            Self::WeiterleitungGesendet { .. } => "MabisZpWeiterleitungGesendet",
            Self::ValidationFailed { .. } => "MabisZpValidationFailed",
        }
    }
}

// ── Domain state ──────────────────────────────────────────────────────────────

/// Current state of a MaBiS-ZP lifecycle process stream.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
#[serde(tag = "status", content = "data")]
pub enum ZpLifecycleState {
    /// No events yet.
    #[default]
    New,
    /// Anfrage received; an Antwort is owed.
    AnfrageErhalten(Box<ZpLifecycleData>),
    /// Anfrage sent; the answering party owes the Antwort.
    ///
    /// Also the resting state of a family with no Antwort PID: the message was
    /// sent and nothing further is owed in either direction.
    AnfrageGesendet(Box<ZpLifecycleData>),
    /// The answering party confirmed an Anfrage this participant sent
    /// (terminal).
    ///
    /// Distinct from [`Self::Bestaetigt`] because Prozessschritt 4 belongs to
    /// the party that ran the Prüfung, never to the requester.
    AntwortBestaetigt(Box<ZpLifecycleData>),
    /// Anfrage recorded; the family defines no Antwort (terminal).
    Erfasst(Box<ZpLifecycleData>),
    /// Antwort sent confirming the Anfrage.
    Bestaetigt(Box<ZpLifecycleData>),
    /// Antwort sent rejecting the Anfrage (terminal).
    Abgelehnt {
        /// Rejection reason.
        grund: String,
    },
    /// Weiterleitung dispatched to the downstream BKV (terminal).
    Weitergeleitet(Box<ZpLifecycleData>),
    /// Inbound message failed AHB validation (terminal).
    ValidationFailed {
        /// Validation error summary.
        reason: String,
    },
}

impl ZpLifecycleState {
    /// Stable string label for the current variant.
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::New => "New",
            Self::AnfrageErhalten(_) => "AnfrageErhalten",
            Self::AnfrageGesendet(_) => "AnfrageGesendet",
            Self::AntwortBestaetigt(_) => "AntwortBestaetigt",
            Self::Erfasst(_) => "Erfasst",
            Self::Bestaetigt(_) => "Bestaetigt",
            Self::Abgelehnt { .. } => "Abgelehnt",
            Self::Weitergeleitet(_) => "Weitergeleitet",
            Self::ValidationFailed { .. } => "ValidationFailed",
        }
    }

    /// The recorded Anfrage data, when the state carries any.
    #[must_use]
    pub fn data(&self) -> Option<&ZpLifecycleData> {
        match self {
            Self::AnfrageErhalten(d)
            | Self::AnfrageGesendet(d)
            | Self::AntwortBestaetigt(d)
            | Self::Erfasst(d)
            | Self::Bestaetigt(d)
            | Self::Weitergeleitet(d) => Some(d),
            Self::New | Self::Abgelehnt { .. } | Self::ValidationFailed { .. } => None,
        }
    }
}

// ── Domain commands ───────────────────────────────────────────────────────────

/// Commands for the MaBiS-ZP lifecycle workflow.
///
/// `Workflow::handle()` is pure — no I/O, no EDIFACT parsing, no store access.
#[derive(Clone)]
pub enum ZpLifecycleCommand {
    /// Inbound Anfrage received from the AS4 layer.
    ReceiveAnfrage {
        /// Prüfidentifikator of the inbound UTILMD.
        ///
        /// Checked against the family, not used to find it: 55062/55063 are
        /// shared by eleven series.
        pid: Pruefidentifikator,
        /// Which Summenzeitreihe — and axis — the MaBiS-Zählpunkt belongs to.
        ///
        /// An explicit input because the PID does not carry it. A MaBiS-ZP is
        /// created **for** one Summenzeitreihe, so the adapter always knows.
        serie: ZpSerie,
        /// Activation or deactivation, from the message content.
        vorgang: ZpVorgang,
        /// MaBiS-Zählpunkt the Anfrage refers to, as it arrived.
        ///
        /// Deliberately a `String` and not
        /// [`MabisZaehlpunktId`](crate::MabisZaehlpunktId): this is a
        /// counterparty's value. Requiring the validated type would make a
        /// malformed Meldepunkt unconstructible, and the workflow could then
        /// neither record what arrived nor answer it with a proper Ablehnung.
        /// The outbound side — [`crate::Summenzeitreihe`] — uses the type,
        /// because that value is ours to get right.
        mabis_zp_id: String,
        /// GLN of the requesting party.
        sender: MarktpartnerCode,
        /// GLN of the receiving party.
        receiver: MarktpartnerCode,
        /// Billing period the activation takes effect in.
        billing_period: BillingPeriod,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
        /// `true` if AHB profile validation passed.
        validation_passed: bool,
        /// Validation errors collected by the AHB validator.
        validation_errors: Vec<String>,
    },
    /// Raise the Aktivierung/Deaktivierung as the requesting party.
    ///
    /// The Prüfidentifikator is **not** an input: on this side it is ours to
    /// get right, and [`ZP_FAMILIEN`] already pairs it with the (series,
    /// Vorgang) the caller names.
    SendAnfrage {
        /// Which Summenzeitreihe — and axis — the MaBiS-Zählpunkt belongs to.
        serie: ZpSerie,
        /// Activation or deactivation.
        vorgang: ZpVorgang,
        /// MaBiS-Zählpunkt to activate or deactivate.
        ///
        /// The validated [`MabisZaehlpunktId`](crate::MabisZaehlpunktId) rather
        /// than the `String`
        /// [`ReceiveAnfrage`](Self::ReceiveAnfrage) keeps: this value is
        /// **ours**, produced from mako's own master data, so a Bilanzierungs­
        /// gebiet EIC in the Meldepunkt field must be a compile-time
        /// impossibility rather than a settlement filed against the wrong
        /// point. The same reasoning [`crate::Summenzeitreihe`] is built on.
        mabis_zp_id: crate::MabisZaehlpunktId,
        /// GLN of this participant.
        sender: MarktpartnerCode,
        /// GLN of the party that answers — the BIKO, or the benachbarter NB on
        /// the Netzzeitreihe axis.
        empfaenger: MarktpartnerCode,
        /// Billing period the activation takes effect in.
        billing_period: BillingPeriod,
        /// EDIFACT document date (`YYYYMMDD`) — the Bilanzierungsbeginn on an
        /// Aktivierung, the Bilanzierungsende on a Deaktivierung.
        document_date: String,
        /// EDIFACT message reference of the Anfrage.
        message_ref: MessageRef,
    },
    /// Apply the Antwort to an Anfrage this participant sent.
    ///
    /// Prozessschritt 2 of every Use-Case in this family: „Unverzüglich,
    /// spätestens jedoch 1 WT nach Erhalt der Aktivierung" resp. „der
    /// Deaktivierung".
    ReceiveAntwort {
        /// Antwort Prüfidentifikator of the inbound UTILMD.
        ///
        /// Checked against the family the Anfrage was sent for: an answer
        /// carrying another family's code is a routing error, not a variant.
        pid: Pruefidentifikator,
        /// `true` when the Anfrage was confirmed.
        ///
        /// A cluster, not a code. The inbound `SG4 STS+E01` DE 9013 is resolved
        /// against the Entscheidungsbaum DE 1131 names *before* the command is
        /// built, because the same code means opposite things in two trees.
        bestaetigt: bool,
        /// Begründung — required when `bestaetigt` is `false`.
        ///
        /// „Im Falle einer Ablehnung der Aktivierung durch den BIKO, erfolgt
        /// diese mit einer Begründung", so a rejection without one is an
        /// incomplete answer rather than a terse one.
        grund: Option<String>,
        /// EBD the Antwortcode was read against — `SG4 STS+E01` DE 1131.
        ebd: String,
        /// EDIFACT message reference of the Antwort.
        message_ref: MessageRef,
    },
    /// Send the Antwort for a received Anfrage.
    SendAntwort {
        /// `true` to confirm, `false` to reject.
        ///
        /// A cluster, not a code. `SG4 STS+E01` DE 9013 stays unstated until
        /// the twelve Entscheidungsbäume a 55064 is answered out of are
        /// catalogued in `mako_pruefung`: only `E_0010` and `E_0020` have
        /// walks today, and inventing a code for the other ten would put a
        /// fabricated Prüfschritt on a message that settles a
        /// Bilanzkreisabrechnung.
        bestaetigt: bool,
        /// Rejection reason — required when `bestaetigt` is `false`.
        grund: Option<String>,
    },
    /// Forward the confirmed activation to the downstream BKV.
    SendWeiterleitung {
        /// GLN of the BKV to forward to.
        empfaenger: MarktpartnerCode,
    },
}

impl CommandPayload for ZpLifecycleCommand {}

// ── Workflow ──────────────────────────────────────────────────────────────────

/// MaBiS-ZP lifecycle workflow.
///
/// Handles activation and deactivation of the MaBiS-Zählpunkt, the
/// Zuordnungsermächtigung, and the AAÜZ/LF-AASZR series. See the module
/// documentation for the PID table and the state machine.
pub struct MabisZpLifecycleWorkflow;

impl Workflow for MabisZpLifecycleWorkflow {
    type State = ZpLifecycleState;
    type Event = ZpLifecycleEvent;
    type Command = ZpLifecycleCommand;

    fn apply(state: Self::State, event: &Self::Event) -> Self::State {
        match event {
            ZpLifecycleEvent::AnfrageErhalten {
                pruefidentifikator,
                vorgang,
                serie,
                mabis_zp_id,
                sender,
                receiver,
                billing_period,
                document_date,
                message_ref,
            } => ZpLifecycleState::AnfrageErhalten(Box::new(ZpLifecycleData {
                pruefidentifikator: *pruefidentifikator,
                vorgang: *vorgang,
                serie: *serie,
                mabis_zp_id: mabis_zp_id.clone(),
                sender: sender.clone(),
                receiver: receiver.clone(),
                billing_period: billing_period.clone(),
                document_date: document_date.clone(),
                message_ref: message_ref.clone(),
            })),

            ZpLifecycleEvent::AnfrageGesendet {
                pruefidentifikator,
                vorgang,
                serie,
                mabis_zp_id,
                sender,
                empfaenger,
                billing_period,
                document_date,
                message_ref,
            } => ZpLifecycleState::AnfrageGesendet(Box::new(ZpLifecycleData {
                pruefidentifikator: *pruefidentifikator,
                vorgang: *vorgang,
                serie: *serie,
                // One shape for both directions: `ZpLifecycleData` records what
                // is on the wire, and the wire carries a Zählpunktbezeichnung
                // either way. The typed identifier is what the *command* takes,
                // which is where a wrong value can still be refused.
                mabis_zp_id: mabis_zp_id.as_str().to_owned(),
                sender: sender.clone(),
                receiver: empfaenger.clone(),
                billing_period: billing_period.clone(),
                document_date: document_date.clone(),
                message_ref: message_ref.clone(),
            })),

            ZpLifecycleEvent::AntwortErhalten {
                bestaetigt, grund, ..
            } => match state {
                ZpLifecycleState::AnfrageGesendet(d) => {
                    if *bestaetigt {
                        ZpLifecycleState::AntwortBestaetigt(d)
                    } else {
                        ZpLifecycleState::Abgelehnt {
                            grund: grund.clone().unwrap_or_default(),
                        }
                    }
                }
                other => other,
            },

            ZpLifecycleEvent::Erfasst { .. } => match state {
                ZpLifecycleState::AnfrageErhalten(d) => ZpLifecycleState::Erfasst(d),
                other => other,
            },

            ZpLifecycleEvent::AntwortGesendet {
                bestaetigt, grund, ..
            } => match state {
                ZpLifecycleState::AnfrageErhalten(d) => {
                    if *bestaetigt {
                        ZpLifecycleState::Bestaetigt(d)
                    } else {
                        ZpLifecycleState::Abgelehnt {
                            grund: grund.clone().unwrap_or_default(),
                        }
                    }
                }
                other => other,
            },

            ZpLifecycleEvent::WeiterleitungGesendet { .. } => match state {
                ZpLifecycleState::Bestaetigt(d) => ZpLifecycleState::Weitergeleitet(d),
                other => other,
            },

            ZpLifecycleEvent::ValidationFailed { reason } => ZpLifecycleState::ValidationFailed {
                reason: reason.clone(),
            },
        }
    }

    fn handle(
        state: &Self::State,
        command: Self::Command,
    ) -> Result<WorkflowOutput<Self::Event>, WorkflowError> {
        match command {
            ZpLifecycleCommand::ReceiveAnfrage {
                pid,
                serie,
                vorgang,
                mabis_zp_id,
                sender,
                receiver,
                billing_period,
                document_date,
                message_ref,
                validation_passed,
                validation_errors,
            } => {
                if !matches!(state, ZpLifecycleState::New) {
                    // Idempotent: a redelivered Anfrage is a no-op.
                    return Ok(vec![].into());
                }

                let Some(familie) = familie_for(serie, vorgang) else {
                    return Err(WorkflowError::rejected(format!(
                        "{} kennt keinen Vorgang {vorgang:?}",
                        serie.label()
                    )));
                };

                // 55062/55063 are shared by eleven series, so the PID cannot
                // identify the family — but it can still contradict it, and a
                // 55197 filed against the Netzzeitreihe is a routing error, not
                // a variant.
                if familie.anfrage != pid.as_u32() {
                    return Err(WorkflowError::rejected(format!(
                        "PID {pid} passt nicht zu {} / {vorgang:?} — erwartet {}",
                        serie.label(),
                        familie.anfrage
                    )));
                }

                // A series a Festlegung has repealed cannot be activated for a
                // Bilanzierungsmonat that starts after it ends: BK6-23-241
                // Tenorziffer 5 repeals the tägliche AAÜZ with the end of
                // 30.09.2026, and a MaBiS-ZP activated into October contributes
                // to a Summenzeitreihe that no longer exists — the Abrechnung
                // never arrives and nothing else says why.
                if vorgang == ZpVorgang::Aktivierung
                    && let Some(beginn) = abrechnungszeitraum_beginn(billing_period.as_str())
                    && !serie.gilt_am(beginn)
                {
                    return Err(WorkflowError::rejected(format!(
                        "{} endet am {} und kann für den Abrechnungszeitraum {} \
                         nicht mehr aktiviert werden",
                        serie.label(),
                        serie
                            .endet_am()
                            .expect("gilt_am was false, so there is an end date"),
                        billing_period.as_str()
                    )));
                }

                if !validation_passed {
                    return Ok(vec![ZpLifecycleEvent::ValidationFailed {
                        reason: validation_errors.join("; "),
                    }]
                    .into());
                }

                let erhalten = ZpLifecycleEvent::AnfrageErhalten {
                    pruefidentifikator: pid,
                    vorgang: familie.vorgang,
                    serie: familie.serie,
                    mabis_zp_id,
                    sender,
                    receiver,
                    billing_period,
                    document_date,
                    message_ref: message_ref.clone(),
                };

                // A family with no Antwort PID is terminal on arrival. Leaving
                // it in `AnfrageErhalten` would model an obligation the AHB
                // does not define.
                if familie.antwort.is_none() {
                    return Ok(vec![erhalten, ZpLifecycleEvent::Erfasst { message_ref }].into());
                }

                Ok(vec![erhalten].into())
            }

            ZpLifecycleCommand::SendAnfrage {
                serie,
                vorgang,
                mabis_zp_id,
                sender,
                empfaenger,
                billing_period,
                document_date,
                message_ref,
            } => {
                if !matches!(state, ZpLifecycleState::New) {
                    // Idempotent: a retried dispatch is a no-op.
                    return Ok(vec![].into());
                }

                let Some(familie) = familie_for(serie, vorgang) else {
                    return Err(WorkflowError::rejected(format!(
                        "{} kennt keinen Vorgang {vorgang:?}",
                        serie.label()
                    )));
                };

                // The same end-date rule the receiving side applies, and it
                // binds harder here: refusing our *own* Aktivierung inside the
                // submission window is cheaper than a Summenzeitreihe the BIKO
                // will never settle.
                if vorgang == ZpVorgang::Aktivierung
                    && let Some(beginn) = abrechnungszeitraum_beginn(billing_period.as_str())
                    && !serie.gilt_am(beginn)
                {
                    return Err(WorkflowError::rejected(format!(
                        "{} endet am {} und kann für den Abrechnungszeitraum {} \
                         nicht mehr aktiviert werden",
                        serie.label(),
                        serie
                            .endet_am()
                            .expect("gilt_am was false, so there is an end date"),
                        billing_period.as_str()
                    )));
                }

                let pid = Pruefidentifikator::new(familie.anfrage).map_err(|e| {
                    WorkflowError::rejected(format!("invalid Anfrage PID {}: {e}", familie.anfrage))
                })?;

                // The keys are the UTILMD renderer's, and the same ones
                // `SendAntwort` writes: a MaBiS Vorgang names a MaBiS-Zählpunkt
                // and no Marktlokation, and `SG4 DTM+158` carries the
                // Bilanzierungsbeginn on an Aktivierung, `DTM+159` the
                // Bilanzierungsende on a Deaktivierung (UTILMD AHB Strom 2.2
                // Kap. 13.3).
                let mut payload = serde_json::json!({
                    "pid": familie.anfrage,
                    "sender": sender.as_str(),
                    "receiver": empfaenger.as_str(),
                    "mabis_zaehlpunkt": mabis_zp_id.as_str(),
                });
                let datum_key = match vorgang {
                    ZpVorgang::Aktivierung => "bilanzierungsbeginn",
                    ZpVorgang::Deaktivierung => "bilanzierungsende",
                };
                payload[datum_key] = serde_json::Value::String(document_date.clone());
                let outbox = PendingOutbox::new("UTILMD", empfaenger.as_str(), payload);

                Ok(WorkflowOutput {
                    events: vec![ZpLifecycleEvent::AnfrageGesendet {
                        pruefidentifikator: pid,
                        vorgang: familie.vorgang,
                        serie: familie.serie,
                        mabis_zp_id,
                        sender,
                        empfaenger,
                        billing_period,
                        document_date,
                        message_ref,
                    }],
                    outbox: vec![outbox],
                    deadlines: vec![],
                })
            }

            ZpLifecycleCommand::ReceiveAntwort {
                pid,
                bestaetigt,
                grund,
                ebd,
                message_ref,
            } => {
                let data = match state {
                    ZpLifecycleState::AnfrageGesendet(data) => data,
                    // A redelivered Antwort is a no-op, like a redelivered
                    // Anfrage.
                    ZpLifecycleState::AntwortBestaetigt(_) | ZpLifecycleState::Abgelehnt { .. } => {
                        return Ok(vec![].into());
                    }
                    other => {
                        return Err(WorkflowError::rejected(format!(
                            "ReceiveAntwort requires state AnfrageGesendet, got {}",
                            other.label()
                        )));
                    }
                };

                let familie = familie_for(data.serie, data.vorgang).ok_or_else(|| {
                    WorkflowError::rejected(format!(
                        "keine Familie für {} / {:?}",
                        data.serie.label(),
                        data.vorgang
                    ))
                })?;

                // A record-only family has no Prozessschritt 2, so an answer to
                // one is a message the Festlegung does not define. Applying it
                // would close a process on an obligation that never existed.
                let Some(antwort_pid_code) = familie.antwort else {
                    return Err(WorkflowError::rejected(format!(
                        "{} (Anfrage {}) definiert keine Antwort",
                        familie.serie.label(),
                        familie.anfrage
                    )));
                };

                if antwort_pid_code != pid.as_u32() {
                    return Err(WorkflowError::rejected(format!(
                        "Antwort-PID {pid} passt nicht zu {} / {:?} — erwartet {antwort_pid_code}",
                        familie.serie.label(),
                        familie.vorgang
                    )));
                }

                if !bestaetigt && grund.as_ref().is_none_or(|g| g.trim().is_empty()) {
                    return Err(WorkflowError::rejected(
                        "a rejecting Antwort requires a reason".to_owned(),
                    ));
                }

                Ok(vec![ZpLifecycleEvent::AntwortErhalten {
                    antwort_pid: pid,
                    ebd,
                    bestaetigt,
                    grund,
                    message_ref,
                }]
                .into())
            }

            ZpLifecycleCommand::SendAntwort { bestaetigt, grund } => {
                let ZpLifecycleState::AnfrageErhalten(data) = state else {
                    return Err(WorkflowError::rejected(format!(
                        "SendAntwort requires state AnfrageErhalten, got {}",
                        state.label()
                    )));
                };

                let familie = familie_for(data.serie, data.vorgang).ok_or_else(|| {
                    WorkflowError::rejected(format!(
                        "keine Familie für {} / {:?}",
                        data.serie.label(),
                        data.vorgang
                    ))
                })?;

                let (Some(antwort_pid_code), Some(ebd)) = (familie.antwort, familie.antwort_ebd)
                else {
                    return Err(WorkflowError::rejected(format!(
                        "{} (Anfrage {}) definiert keine Antwort",
                        familie.serie.label(),
                        familie.anfrage
                    )));
                };

                if !bestaetigt && grund.as_ref().is_none_or(|g| g.trim().is_empty()) {
                    return Err(WorkflowError::rejected(
                        "a rejecting Antwort requires a reason".to_owned(),
                    ));
                }

                let antwort_pid = Pruefidentifikator::new(antwort_pid_code).map_err(|e| {
                    WorkflowError::rejected(format!("invalid Antwort PID {antwort_pid_code}: {e}"))
                })?;

                // The keys are the UTILMD renderer's. A MaBiS Vorgang names a
                // **MaBiS-Zählpunkt** and no Marktlokation, so the ZP is the
                // primary `SG5 LOC+Z15`; the answer travels back the way the
                // Anfrage came, so the parties swap.
                let mut payload = serde_json::json!({
                    "pid": antwort_pid_code,
                    "sender": data.receiver.as_str(),
                    "receiver": data.sender.as_str(),
                    "mabis_zaehlpunkt": data.mabis_zp_id,
                    // `SG4 STS+E01` DE 1131 — the tree this answer belongs to.
                    // 55064 is answered out of twelve of them, so the Antwort
                    // is unreadable without it. DE 9013 is not stated: see
                    // `SendAntwort`.
                    "antwort_codeliste": ebd,
                });
                // `SG4 DTM+158` on an answer to an Aktivierung, `DTM+159` on
                // one to a Deaktivierung (UTILMD AHB Strom 2.2 Kap. 13.3,
                // Bedingungen `[30]`/`[34]`). The lifecycle has no
                // Vertragsdatum: a Zählpunkt has no contract.
                let datum_key = match data.vorgang {
                    ZpVorgang::Aktivierung => "bilanzierungsbeginn",
                    ZpVorgang::Deaktivierung => "bilanzierungsende",
                };
                payload[datum_key] = serde_json::Value::String(data.document_date.clone());
                if let Some(ref text) = grund {
                    payload["bemerkung"] = serde_json::Value::String(text.clone());
                }
                let outbox = PendingOutbox::new("UTILMD", data.sender.as_str(), payload);

                Ok(WorkflowOutput {
                    events: vec![ZpLifecycleEvent::AntwortGesendet {
                        antwort_pid,
                        ebd: ebd.to_owned(),
                        bestaetigt,
                        grund,
                    }],
                    outbox: vec![outbox],
                    deadlines: vec![],
                })
            }

            ZpLifecycleCommand::SendWeiterleitung { empfaenger } => {
                let ZpLifecycleState::Bestaetigt(data) = state else {
                    return Err(WorkflowError::rejected(format!(
                        "SendWeiterleitung requires state Bestaetigt, got {}",
                        state.label()
                    )));
                };

                let familie = familie_for(data.serie, data.vorgang).ok_or_else(|| {
                    WorkflowError::rejected(format!(
                        "keine Familie für {} / {:?}",
                        data.serie.label(),
                        data.vorgang
                    ))
                })?;

                let Some(weiterleitung) = familie.weiterleitung else {
                    return Err(WorkflowError::rejected(format!(
                        "{} (Anfrage {}) definiert keine Weiterleitung",
                        familie.serie.label(),
                        familie.anfrage
                    )));
                };

                let weiterleitung_pid = Pruefidentifikator::new(weiterleitung).map_err(|e| {
                    WorkflowError::rejected(format!(
                        "invalid Weiterleitung PID {weiterleitung}: {e}"
                    ))
                })?;

                let outbox = PendingOutbox::new(
                    "UTILMD",
                    empfaenger.as_str(),
                    serde_json::json!({
                        "pid": weiterleitung,
                        "sender": data.receiver.as_str(),
                        "receiver": empfaenger.as_str(),
                        "mabis_zaehlpunkt": data.mabis_zp_id,
                        "bilanzierungsbeginn": data.document_date,
                    }),
                );

                Ok(WorkflowOutput {
                    events: vec![ZpLifecycleEvent::WeiterleitungGesendet {
                        weiterleitung_pid,
                        empfaenger,
                    }],
                    outbox: vec![outbox],
                    deadlines: vec![],
                })
            }
        }
    }
}

/// First day of the month a [`BillingPeriod`] names, where it names one.
///
/// The value is a counterparty's and its shape is AHB-dependent — `YYYYMM` or
/// `YYYYMMDD-YYYYMMDD` — so only the leading `YYYYMM` is read, and anything else
/// answers `None`. A period that cannot be read is not evidence of a period out
/// of range.
fn abrechnungszeitraum_beginn(period: &str) -> Option<time::Date> {
    // `YYYYMM`, `YYYY-MM` and `YYYYMMDD-YYYYMMDD` all appear across AHB
    // versions, so the separator is ignored and the leading six digits are read.
    let digits: String = period
        .chars()
        .filter(char::is_ascii_digit)
        .take(6)
        .collect();
    if digits.len() != 6 {
        return None;
    }
    let year: i32 = digits[..4].parse().ok()?;
    let month = time::Month::try_from(digits[4..6].parse::<u8>().ok()?).ok()?;
    time::Date::from_calendar_date(year, month, 1).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn mp(s: &str) -> MarktpartnerCode {
        MarktpartnerCode::new(s)
    }

    fn receive(serie: ZpSerie, vorgang: ZpVorgang) -> ZpLifecycleCommand {
        let pid = familie_for(serie, vorgang).expect("in the table").anfrage;
        receive_with_pid(serie, vorgang, pid)
    }

    fn receive_with_pid(serie: ZpSerie, vorgang: ZpVorgang, pid: u32) -> ZpLifecycleCommand {
        ZpLifecycleCommand::ReceiveAnfrage {
            pid: Pruefidentifikator::new(pid).expect("valid PID"),
            serie,
            vorgang,
            mabis_zp_id: "DE0001112223334445556667778889990".to_owned(),
            sender: mp("9900123456789"),
            receiver: mp("9900987654321"),
            billing_period: BillingPeriod::new("2026-07"),
            document_date: "20260701".to_owned(),
            message_ref: MessageRef::new("MSG-1"),
            validation_passed: true,
            validation_errors: vec![],
        }
    }

    fn receive_for_period(serie: ZpSerie, vorgang: ZpVorgang, period: &str) -> ZpLifecycleCommand {
        let mut cmd = receive(serie, vorgang);
        if let ZpLifecycleCommand::ReceiveAnfrage {
            ref mut billing_period,
            ..
        } = cmd
        {
            *billing_period = BillingPeriod::new(period);
        }
        cmd
    }

    const ZP: &str = "DE0001112223334445556667778889990";

    fn send(serie: ZpSerie, vorgang: ZpVorgang) -> ZpLifecycleCommand {
        ZpLifecycleCommand::SendAnfrage {
            serie,
            vorgang,
            mabis_zp_id: crate::MabisZaehlpunktId::new(ZP).expect("33 characters"),
            sender: mp("9900987654321"),
            empfaenger: mp("9900123456789"),
            billing_period: BillingPeriod::new("2026-07"),
            document_date: "20260701".to_owned(),
            message_ref: MessageRef::new("MSG-OUT-1"),
        }
    }

    /// Drive `serie`/`vorgang` to `AnfrageGesendet`.
    fn gesendet(serie: ZpSerie, vorgang: ZpVorgang) -> ZpLifecycleState {
        let out = MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, send(serie, vorgang))
            .expect("accepted");
        fold(&out.events)
    }

    fn antwort(pid: u32, bestaetigt: bool, grund: Option<&str>) -> ZpLifecycleCommand {
        ZpLifecycleCommand::ReceiveAntwort {
            pid: Pruefidentifikator::new(pid).expect("valid PID"),
            bestaetigt,
            grund: grund.map(ToOwned::to_owned),
            ebd: "E_0071".to_owned(),
            message_ref: MessageRef::new("MSG-IN-1"),
        }
    }

    fn fold(events: &[ZpLifecycleEvent]) -> ZpLifecycleState {
        events.iter().fold(ZpLifecycleState::default(), |s, e| {
            MabisZpLifecycleWorkflow::apply(s, e)
        })
    }

    // ── Table integrity ─────────────────────────────────────────────────────

    #[test]
    fn every_series_has_exactly_one_row_per_vorgang() {
        for f in ZP_FAMILIEN {
            for vorgang in [ZpVorgang::Aktivierung, ZpVorgang::Deaktivierung] {
                let rows = ZP_FAMILIEN
                    .iter()
                    .filter(|r| r.serie == f.serie && r.vorgang == vorgang)
                    .count();
                assert_eq!(rows, 1, "{} / {vorgang:?}", f.serie.label());
            }
        }
    }

    #[test]
    fn an_antwort_pid_always_comes_with_its_tree() {
        // An answer code without a Codeliste to read it against is not an
        // answer — 55064 alone says nothing.
        for f in ZP_FAMILIEN {
            assert_eq!(
                f.antwort.is_some(),
                f.antwort_ebd.is_some(),
                "{} / {:?}",
                f.serie.label(),
                f.vorgang
            );
        }
    }

    #[test]
    fn the_generic_codes_are_shared_by_eleven_series() {
        // This is the fact the whole module is shaped around: 55062/55063 do
        // not identify a process.
        let akt = serien_fuer_pid(55062);
        let deakt = serien_fuer_pid(55063);
        assert_eq!(akt.len(), 11, "55062 is shared: {akt:?}");
        assert_eq!(deakt.len(), 11, "55063 is shared: {deakt:?}");
    }

    #[test]
    fn the_shared_antwort_pid_reads_out_of_twelve_different_trees() {
        let mut ebds: Vec<&str> = ZP_FAMILIEN
            .iter()
            .filter(|f| f.antwort == Some(55064))
            .map(|f| f.antwort_ebd.expect("paired"))
            .collect();
        let total = ebds.len();
        ebds.sort_unstable();
        ebds.dedup();
        assert_eq!(
            total, 12,
            "twelve (series, direction) pairs answer with 55064"
        );
        assert_eq!(ebds.len(), 12, "and no two of them share a tree: {ebds:?}");
    }

    #[test]
    fn six_of_the_eleven_generic_series_answer_and_five_do_not() {
        let generic = |with_antwort: bool| {
            ZP_FAMILIEN
                .iter()
                .filter(|f| f.anfrage == 55062 && f.antwort.is_some() == with_antwort)
                .count()
        };
        assert_eq!(
            generic(true),
            6,
            "an implementation that never answers 55062 drops six obligations"
        );
        assert_eq!(
            generic(false),
            5,
            "modelling 55062 → 55064 invents five obligations"
        );
    }

    #[test]
    fn the_generic_weiterleitung_re_uses_the_request_code() {
        // Prozessschritt 4 is another 55062/55063 to the downstream party, not
        // a distinct PID.
        for f in ZP_FAMILIEN.iter().filter(|f| f.anfrage == 55062) {
            if let Some(w) = f.weiterleitung {
                assert_eq!(w, 55062, "{}", f.serie.label());
            }
        }
    }

    #[test]
    fn all_pids_covers_anfragen_answers_and_weiterleitungen() {
        let pids = all_pids();
        for f in ZP_FAMILIEN {
            assert!(pids.contains(&f.anfrage));
            for p in [f.antwort, f.weiterleitung].into_iter().flatten() {
                assert!(pids.contains(&p), "{p} missing from all_pids()");
            }
        }
        let expected: Vec<u32> = vec![
            55062, 55063, 55064, 55071, 55072, 55197, 55198, 55199, 55200, 55203, 55204, 55205,
            55206, 55207, 55208, 55209, 55210, 55211, 55212, 55213, 55214,
            // NZR-EMob Zuordnung des ZP der NGZ zur NZR (AHB Kap. 13.16).
            55235, 55236, 55237,
        ];
        assert_eq!(pids, expected);
    }

    /// The NZR-EMob Zuordnung des ZP der NGZ zur NZR — its own Anfrage codes,
    /// one shared Antwort code, two different trees.
    #[test]
    fn the_ngz_zuordnung_answers_one_pid_out_of_two_trees() {
        let auf = familie_for(ZpSerie::NetzgangzeitreiheNzr, ZpVorgang::Aktivierung)
            .expect("Zuordnung is a family");
        let ab = familie_for(ZpSerie::NetzgangzeitreiheNzr, ZpVorgang::Deaktivierung)
            .expect("Beendigung is a family");

        assert_eq!((auf.anfrage, ab.anfrage), (55235, 55236));

        // One Antwort code for both directions. Reading the tree off the
        // Antwort PID would therefore be impossible — which is exactly why the
        // EBD is its own column and the workflow never derives it.
        assert_eq!(auf.antwort, ab.antwort, "55237 answers both");
        assert_eq!(auf.antwort, Some(55237));
        assert_eq!(auf.antwort_ebd, Some("E_0102"));
        assert_eq!(ab.antwort_ebd, Some("E_0103"));
        assert_ne!(auf.antwort_ebd, ab.antwort_ebd);

        // The ÜNB copy is the same code re-addressed, sent only once the
        // neighbouring NB has confirmed (AHB Kap. 13.16 gives 55235/55236 two
        // recipients and 55237 one).
        assert_eq!(auf.weiterleitung, Some(55235));
        assert_eq!(ab.weiterleitung, Some(55236));

        // It has its own Anfrage codes, so it is never resolved off the
        // 55062/55063 SG10 discriminator.
        assert!(!serien_fuer_pid(55062).contains(&ZpSerie::NetzgangzeitreiheNzr));
        assert_eq!(serien_fuer_pid(55235), vec![ZpSerie::NetzgangzeitreiheNzr]);

        // MaBiS, not Modell 2 — it outlives no Festlegung end date.
        assert_eq!(ZpSerie::NetzgangzeitreiheNzr.endet_am(), None);
    }

    #[test]
    fn the_two_monatliche_families_forward_to_different_recipients() {
        // Identical process, different Weiterleitung code and a different EBD —
        // the only things separating them, and the reason they are not merged.
        let lf = familie_for(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung).unwrap();
        let nb = familie_for(ZpSerie::MonatlicheAauezBkvAnfNb, ZpVorgang::Aktivierung).unwrap();
        assert_eq!(lf.weiterleitung, Some(55205));
        assert_eq!(nb.weiterleitung, Some(55211));
        assert_eq!(lf.antwort_ebd, Some("E_0071"));
        assert_eq!(nb.antwort_ebd, Some("E_0078"));
    }

    // ── The 30.09.2026 cut ──────────────────────────────────────────────────

    #[test]
    fn only_the_taegliche_aauez_expires() {
        for f in ZP_FAMILIEN {
            let expected = f.serie == ZpSerie::TaeglicheAauez;
            assert_eq!(
                f.serie.endet_am().is_some(),
                expected,
                "{}",
                f.serie.label()
            );
        }
        let ende = TAEGLICHE_AAUEZ_ENDE;
        assert!(ZpSerie::TaeglicheAauez.gilt_am(ende));
        assert!(!ZpSerie::TaeglicheAauez.gilt_am(ende.next_day().unwrap()));
        // Everything else is unaffected by the Kap.-17 repeal.
        assert!(ZpSerie::LfAaszr.gilt_am(ende.next_day().unwrap()));
    }

    // ── Behaviour ───────────────────────────────────────────────────────────

    #[test]
    fn a_family_without_an_antwort_is_terminal_on_arrival() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(ZpSerie::Zuordnungsermaechtigung, ZpVorgang::Aktivierung),
        )
        .expect("accepted");
        let state = fold(&out.events);
        assert_eq!(state.label(), "Erfasst");
        assert!(out.outbox.is_empty(), "record-only family must not emit");

        let err = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendAntwort {
                bestaetigt: true,
                grund: None,
            },
        )
        .expect_err("must reject");
        assert!(format!("{err}").contains("Antwort"), "got: {err}");
    }

    #[test]
    fn the_same_pid_answers_or_does_not_depending_on_the_series() {
        // Both arrive as 55062. One owes a 55064, the other is terminal — the
        // single fact a PID-keyed table cannot represent.
        let owes = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(
                ZpSerie::Bilanzierungsgebietssummenzeitreihe,
                ZpVorgang::Aktivierung,
            ),
        )
        .expect("accepted");
        assert_eq!(fold(&owes.events).label(), "AnfrageErhalten");

        let terminal = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(ZpSerie::TaeglicheBkSzr, ZpVorgang::Aktivierung),
        )
        .expect("accepted");
        assert_eq!(fold(&terminal.events).label(), "Erfasst");
    }

    #[test]
    fn the_antwort_carries_the_tree_it_was_read_against() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(ZpSerie::Deltazeitreihenuebertrag, ZpVorgang::Deaktivierung),
        )
        .expect("accepted");
        let state = fold(&out.events);
        let antwort = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendAntwort {
                bestaetigt: true,
                grund: None,
            },
        )
        .expect("answered");
        assert_eq!(antwort.outbox[0].payload["pid"], 55064);
        assert_eq!(antwort.outbox[0].payload["antwort_codeliste"], "E_0028");
    }

    #[test]
    fn anfrage_antwort_weiterleitung_happy_path() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung),
        )
        .expect("accepted");
        let state = fold(&out.events);
        assert_eq!(state.label(), "AnfrageErhalten");

        let antwort = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendAntwort {
                bestaetigt: true,
                grund: None,
            },
        )
        .expect("pruefung");
        assert_eq!(antwort.outbox.len(), 1);
        assert_eq!(antwort.outbox[0].payload["pid"], 55204);
        assert_eq!(antwort.outbox[0].payload["antwort_codeliste"], "E_0071");
        assert_eq!(
            antwort.outbox[0].recipient.as_ref(),
            "9900123456789",
            "the Antwort goes back to the requesting party"
        );

        let state = antwort
            .events
            .iter()
            .fold(state, MabisZpLifecycleWorkflow::apply);
        assert_eq!(state.label(), "Bestaetigt");

        let out = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendWeiterleitung {
                empfaenger: mp("9900555555555"),
            },
        )
        .expect("weiterleitung");
        assert_eq!(out.outbox[0].payload["pid"], 55205);
    }

    // ── Requester side ──────────────────────────────────────────────────────

    #[test]
    fn sending_an_anfrage_emits_the_familys_pid_and_one_utilmd() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            send(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung),
        )
        .expect("accepted");

        assert_eq!(out.outbox.len(), 1);
        assert_eq!(out.outbox[0].payload["pid"], 55203);
        assert_eq!(out.outbox[0].payload["mabis_zaehlpunkt"], ZP);
        assert_eq!(out.outbox[0].payload["bilanzierungsbeginn"], "20260701");
        assert_eq!(out.outbox[0].recipient.as_ref(), "9900123456789");

        let state = fold(&out.events);
        assert_eq!(state.label(), "AnfrageGesendet");
        assert_eq!(state.data().expect("carries data").mabis_zp_id, ZP);
    }

    /// A Deaktivierung states `SG4 DTM+159` Bilanzierungsende, never a
    /// Bilanzierungsbeginn (UTILMD AHB Strom 2.2 Kap. 13.3).
    #[test]
    fn a_sent_deaktivierung_states_the_bilanzierungsende() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            send(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Deaktivierung),
        )
        .expect("accepted");
        assert_eq!(out.outbox[0].payload["pid"], 55206);
        assert_eq!(out.outbox[0].payload["bilanzierungsende"], "20260701");
        assert!(out.outbox[0].payload.get("bilanzierungsbeginn").is_none());
    }

    /// The end-date rule binds on the side that *sends*, too: activating a
    /// repealed series is refused inside the submission window rather than
    /// discovered when the Abrechnung never arrives.
    #[test]
    fn a_repealed_series_cannot_be_sent_for_a_period_after_its_end() {
        let mut cmd = send(ZpSerie::TaeglicheAauez, ZpVorgang::Aktivierung);
        if let ZpLifecycleCommand::SendAnfrage {
            ref mut billing_period,
            ..
        } = cmd
        {
            *billing_period = BillingPeriod::new("202610");
        }
        let err = MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd)
            .expect_err("the series is repealed with the end of 30.09.2026");
        assert!(format!("{err}").contains("2026-09-30"), "got: {err}");
    }

    #[test]
    fn a_confirming_antwort_closes_the_process_the_anfrage_opened() {
        let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
        let out = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
            .expect("the BIKO confirmed");
        assert!(out.outbox.is_empty(), "an answer is not answered");

        let state = out
            .events
            .iter()
            .fold(state, MabisZpLifecycleWorkflow::apply);
        assert_eq!(state.label(), "AntwortBestaetigt");
    }

    /// The requester must not be able to run Prozessschritt 4: „Der BIKO leitet
    /// nur den nicht abgelehnten MaBiS-ZP an den BKV … weiter" — the
    /// Weiterleitung is the answering party's step.
    #[test]
    fn a_requester_cannot_forward_what_it_asked_for() {
        let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
        let out = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
            .expect("confirmed");
        let state = out
            .events
            .iter()
            .fold(state, MabisZpLifecycleWorkflow::apply);

        let err = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendWeiterleitung {
                empfaenger: mp("9900555555555"),
            },
        )
        .expect_err("only the answering party forwards");
        assert!(format!("{err}").contains("Bestaetigt"), "got: {err}");
    }

    #[test]
    fn a_rejecting_antwort_carries_its_begruendung_into_the_state() {
        let state = gesendet(ZpSerie::MonatlicheAauezBkvAnfNb, ZpVorgang::Aktivierung);
        let out = MabisZpLifecycleWorkflow::handle(
            &state,
            antwort(55210, false, Some("Bilanzierungsgebiet nicht gültig")),
        )
        .expect("rejections are applied");
        let state = out
            .events
            .iter()
            .fold(state, MabisZpLifecycleWorkflow::apply);
        assert_eq!(state.label(), "Abgelehnt");
        let ZpLifecycleState::Abgelehnt { grund } = state else {
            panic!("expected Abgelehnt");
        };
        assert_eq!(grund, "Bilanzierungsgebiet nicht gültig");
    }

    /// „Im Falle einer Ablehnung … erfolgt diese mit einer Begründung"
    /// (BK6-24-174 Anlage 3 SD Nr. 2, Hinweis). A bare refusal is an incomplete
    /// answer, and accepting it drops the only lead the NB gets for the manual
    /// Fehlerklärung of Prozessschritt 3.
    #[test]
    fn an_inbound_rejection_without_a_begruendung_is_refused() {
        let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
        for grund in [None, Some("   ")] {
            let err = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, false, grund))
                .expect_err("must refuse");
            assert!(format!("{err}").contains("reason"), "got: {err}");
        }
    }

    /// A record-only family has no Prozessschritt 2, so there is no answer to
    /// apply — accepting one would close a process on an obligation the
    /// Festlegung never created.
    #[test]
    fn a_record_only_family_takes_no_antwort() {
        let state = gesendet(ZpSerie::LfAaszr, ZpVorgang::Aktivierung);
        let err = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
            .expect_err("55199 owes no answer");
        let msg = format!("{err}");
        assert!(msg.contains("definiert keine Antwort"), "got: {msg}");
        assert!(msg.contains("55199"), "the error names the Anfrage: {msg}");
    }

    /// An answer code from another family is a routing error, not a variant.
    #[test]
    fn an_antwort_pid_that_contradicts_the_family_is_refused() {
        let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
        let err = MabisZpLifecycleWorkflow::handle(&state, antwort(55210, true, None))
            .expect_err("55210 answers the anfNB family");
        assert!(format!("{err}").contains("55204"), "got: {err}");
    }

    #[test]
    fn an_antwort_without_a_question_is_refused_and_a_redelivered_one_is_a_no_op() {
        // Nothing was sent, so there is no Anfrage this answers.
        let err =
            MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, antwort(55204, true, None))
                .expect_err("an orphan answer");
        assert!(format!("{err}").contains("AnfrageGesendet"), "got: {err}");

        // Delivered twice, applied once.
        let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
        let out = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
            .expect("confirmed");
        let state = out
            .events
            .iter()
            .fold(state, MabisZpLifecycleWorkflow::apply);
        let again = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
            .expect("idempotent");
        assert!(again.events.is_empty());
    }

    /// The two directions are separate processes over one family table: the
    /// answering side never reaches `AnfrageGesendet` and the requesting side
    /// never reaches `Bestaetigt`.
    #[test]
    fn the_two_directions_do_not_share_a_positive_state() {
        let answering = {
            let out = MabisZpLifecycleWorkflow::handle(
                &ZpLifecycleState::New,
                receive(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung),
            )
            .expect("accepted");
            let state = fold(&out.events);
            let out = MabisZpLifecycleWorkflow::handle(
                &state,
                ZpLifecycleCommand::SendAntwort {
                    bestaetigt: true,
                    grund: None,
                },
            )
            .expect("answered");
            out.events
                .iter()
                .fold(state, MabisZpLifecycleWorkflow::apply)
        };
        assert_eq!(answering.label(), "Bestaetigt");

        let requesting = {
            let state = gesendet(ZpSerie::MonatlicheAauezBkvLf, ZpVorgang::Aktivierung);
            let out = MabisZpLifecycleWorkflow::handle(&state, antwort(55204, true, None))
                .expect("confirmed");
            out.events
                .iter()
                .fold(state, MabisZpLifecycleWorkflow::apply)
        };
        assert_eq!(requesting.label(), "AntwortBestaetigt");
    }

    /// The PID-space questions the ingest dispatcher asks, in the order it must
    /// ask them: for the eleven generic series Prozessschritt 4 re-uses the
    /// request code, so 55062 is both.
    #[test]
    fn the_generic_request_codes_are_also_weiterleitung_codes() {
        for pid in [55062_u32, 55063] {
            assert!(!serien_fuer_pid(pid).is_empty(), "{pid} is an Anfrage");
            assert!(ist_weiterleitung_pid(pid), "{pid} is also a Weiterleitung");
            assert!(!ist_antwort_pid(pid), "{pid} is never an Antwort");
        }
        for pid in [55064_u32, 55204, 55207, 55210, 55213, 55237] {
            assert!(ist_antwort_pid(pid), "{pid} is an Antwort");
            assert!(serien_fuer_pid(pid).is_empty(), "{pid} is no Anfrage");
            assert!(!ist_weiterleitung_pid(pid), "{pid} is no Weiterleitung");
        }
        for pid in [55205_u32, 55208, 55211, 55214] {
            assert!(ist_weiterleitung_pid(pid), "{pid} is a Weiterleitung");
            assert!(!ist_antwort_pid(pid), "{pid} is no Antwort");
            assert!(serien_fuer_pid(pid).is_empty(), "{pid} is no Anfrage");
        }
    }

    /// The Cluster comes from the **pair**, never from the code alone.
    ///
    /// `A12` is the Zustimmung of `E_0020` and an Ablehnung („MaBiS-ZP bereits
    /// aktiviert") in `E_0071`. A resolver keyed on the code would answer
    /// „aktiviert" to a refusal, and the missing Summenzeitreihe would be the
    /// only symptom. A code the tree does not publish resolves to `None` rather
    /// than defaulting in either direction.
    #[test]
    fn the_antwort_cluster_needs_both_the_tree_and_the_code() {
        for ebd in ["E_0020", "E_0071", "E_0072", "E_0078", "E_0079"] {
            let zustimmung = mako_pruefung::mabis::codes::zustimmung(ebd)
                .unwrap_or_else(|| panic!("{ebd} publishes a Zustimmung"));
            assert_eq!(
                antwort_ist_zustimmung(ebd, zustimmung.code),
                Some(true),
                "{ebd} {}",
                zustimmung.code
            );
        }

        // The same code, opposite meanings.
        assert_eq!(antwort_ist_zustimmung("E_0020", "A12"), Some(true));
        assert_eq!(antwort_ist_zustimmung("E_0071", "A12"), Some(false));

        // Neither an unknown tree nor an unpublished code is guessed.
        assert_eq!(antwort_ist_zustimmung("E_0020", "ZZZ"), None);
        assert_eq!(
            antwort_ist_zustimmung("E_0072", "A13"),
            None,
            "A13 is the Aktivierung trees' Zustimmung; E_0072 stops at A07"
        );
        assert_eq!(antwort_ist_zustimmung("E_9999", "A01"), None);
    }

    #[test]
    fn a_rejecting_antwort_requires_a_reason() {
        let out = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive(ZpSerie::NetzzeitreiheBiko, ZpVorgang::Aktivierung),
        )
        .expect("accepted");
        let state = fold(&out.events);
        let err = MabisZpLifecycleWorkflow::handle(
            &state,
            ZpLifecycleCommand::SendAntwort {
                bestaetigt: false,
                grund: None,
            },
        )
        .expect_err("must reject");
        assert!(format!("{err}").contains("reason"), "got: {err}");
    }

    #[test]
    fn a_pid_that_contradicts_the_series_is_rejected() {
        // 55197 is the tägliche AAÜZ; filing it against the Netzzeitreihe is a
        // routing error, not a variant.
        let err = MabisZpLifecycleWorkflow::handle(
            &ZpLifecycleState::New,
            receive_with_pid(ZpSerie::NetzzeitreiheBiko, ZpVorgang::Aktivierung, 55197),
        )
        .expect_err("must reject");
        assert!(format!("{err}").contains("55062"), "got: {err}");
    }

    #[test]
    fn validation_failure_is_terminal_and_emits_nothing() {
        let cmd = match receive(ZpSerie::NetzzeitreiheBiko, ZpVorgang::Aktivierung) {
            ZpLifecycleCommand::ReceiveAnfrage {
                pid,
                serie,
                vorgang,
                mabis_zp_id,
                sender,
                receiver,
                billing_period,
                document_date,
                message_ref,
                ..
            } => ZpLifecycleCommand::ReceiveAnfrage {
                pid,
                serie,
                vorgang,
                mabis_zp_id,
                sender,
                receiver,
                billing_period,
                document_date,
                message_ref,
                validation_passed: false,
                validation_errors: vec!["SG6 LOC missing".to_owned()],
            },
            other => other,
        };
        let out = MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd).expect("accepted");
        assert!(out.outbox.is_empty());
        assert_eq!(fold(&out.events).label(), "ValidationFailed");
    }

    #[test]
    fn a_redelivered_anfrage_is_a_no_op() {
        let cmd = receive(ZpSerie::NetzzeitreiheBiko, ZpVorgang::Aktivierung);
        let out = MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd.clone())
            .expect("accepted");
        let state = fold(&out.events);
        let again = MabisZpLifecycleWorkflow::handle(&state, cmd).expect("idempotent");
        assert!(again.events.is_empty());
        assert!(again.outbox.is_empty());
    }

    /// BK6-23-241 Tenorziffer 5 repeals MaBiS Anlage 1 Kap. 17.2 with the end of
    /// 30.09.2026, so a MaBiS-ZP cannot be activated for a Bilanzierungsmonat
    /// that starts after it. Accepting one books a Zählpunkt into a
    /// Summenzeitreihe that never settles, and nothing downstream says why.
    #[test]
    fn a_repealed_series_cannot_be_activated_after_its_end() {
        let cmd = receive_for_period(ZpSerie::TaeglicheAauez, ZpVorgang::Aktivierung, "202610");
        let out = MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd);
        let err = out.expect_err("an activation past the repeal is refused");
        assert!(
            format!("{err}").contains("endet am 2026-09-30"),
            "the refusal names the date: {err}"
        );
    }

    /// The last month the series exists still activates.
    #[test]
    fn the_final_month_of_a_repealed_series_still_activates() {
        let cmd = receive_for_period(ZpSerie::TaeglicheAauez, ZpVorgang::Aktivierung, "202609");
        assert!(MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd).is_ok());
    }

    /// A Deaktivierung is how a repealed series is wound down, so the guard
    /// must not refuse one.
    #[test]
    fn a_deaktivierung_is_not_bound_by_the_end_date() {
        let cmd = receive_for_period(ZpSerie::TaeglicheAauez, ZpVorgang::Deaktivierung, "202610");
        assert!(MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd).is_ok());
    }

    /// Every other series is open-ended and unaffected.
    #[test]
    fn a_series_with_no_end_date_activates_in_any_period() {
        let cmd = receive_for_period(ZpSerie::TaeglicheBkSzr, ZpVorgang::Aktivierung, "209912");
        assert!(MabisZpLifecycleWorkflow::handle(&ZpLifecycleState::New, cmd).is_ok());
    }

    /// A period whose shape the AHB version changed is not evidence of a period
    /// out of range, so the guard stands down rather than inventing a refusal.
    #[test]
    fn an_unreadable_abrechnungszeitraum_does_not_refuse() {
        let okt = time::Date::from_calendar_date(2026, time::Month::October, 1).unwrap();
        for shape in ["202610", "2026-10", "20261001-20261031"] {
            assert_eq!(
                super::abrechnungszeitraum_beginn(shape),
                Some(okt),
                "{shape}"
            );
        }
        for bad in ["2026", "", "202613"] {
            assert_eq!(super::abrechnungszeitraum_beginn(bad), None, "{bad:?}");
        }
    }
}

#[cfg(test)]
mod wire_tests {
    use super::*;
    use crate::zeitreihen::{
        Aggregationsebene, Familie, Kategorie, Rolle, Zeitreihe, cav_aus_zeitreihe, cci_aus_rolle,
    };

    #[test]
    fn the_wire_codes_resolve_the_series_a_shared_pid_cannot() {
        /// One row: the Tabelle-1 identity, its Aggregationsebene where it has
        /// one, the responsible role, and the family it must resolve to.
        type Fall = (
            Familie,
            Option<Kategorie>,
            Option<Aggregationsebene>,
            Rolle,
            ZpSerie,
        );
        let cases: &[Fall] = &[
            (
                Familie::BgSzr,
                Some(Kategorie::B),
                None,
                Rolle::Uenb,
                ZpSerie::Bilanzierungsgebietssummenzeitreihe,
            ),
            (
                Familie::BgSzr,
                Some(Kategorie::C),
                None,
                Rolle::Uenb,
                ZpSerie::TaeglicheBgSzr,
            ),
            (
                Familie::BkSzr,
                Some(Kategorie::A),
                None,
                Rolle::Nb,
                ZpSerie::BilanzkreissummenzeitreiheNb,
            ),
            (
                Familie::BkSzr,
                Some(Kategorie::B),
                Some(Aggregationsebene::Bilanzierungsgebiet),
                Rolle::Uenb,
                ZpSerie::BilanzkreissummenzeitreiheUenb,
            ),
            (
                Familie::BkSzr,
                Some(Kategorie::C),
                None,
                Rolle::Uenb,
                ZpSerie::TaeglicheBkSzr,
            ),
            (
                Familie::LfSzr,
                Some(Kategorie::A),
                None,
                Rolle::Nb,
                ZpSerie::LieferantensummenzeitreiheNb,
            ),
            (
                Familie::LfSzr,
                Some(Kategorie::B),
                Some(Aggregationsebene::Bilanzierungsgebiet),
                Rolle::Uenb,
                ZpSerie::LieferantensummenzeitreiheUenb,
            ),
            (
                Familie::Dzue,
                None,
                None,
                Rolle::Uenb,
                ZpSerie::Deltazeitreihenuebertrag,
            ),
            (
                Familie::Nzr,
                None,
                None,
                Rolle::Nb,
                ZpSerie::NetzzeitreiheBiko,
            ),
            (
                Familie::Abrechnungssummenzeitreihe,
                None,
                None,
                Rolle::Biko,
                ZpSerie::Abrechnungssummenzeitreihe,
            ),
        ];
        for &(familie, kategorie, ebene, rolle, expected) in cases {
            let z = Zeitreihe::new(familie, kategorie).expect("Tabelle-1 row");
            let cav = cav_aus_zeitreihe(z, ebene).expect("has a CAV code");
            let cci = cci_aus_rolle(rolle).expect("has a CCI code");
            assert_eq!(
                ZpSerie::from_wire(cav, cci),
                Some(expected),
                "CAV {cav} / CCI {cci}"
            );
        }
    }

    #[test]
    fn every_resolved_series_has_a_family_row() {
        for cav in [
            "Z95", "Z96", "Z97", "Z99", "ZA0", "ZA1", "ZA3", "ZA4", "ZA5", "ZA6",
        ] {
            for cci in ["ZA8", "ZA9", "ZB7"] {
                if let Some(serie) = ZpSerie::from_wire(cav, cci) {
                    for vorgang in [ZpVorgang::Aktivierung, ZpVorgang::Deaktivierung] {
                        assert!(
                            familie_for(serie, vorgang).is_some(),
                            "{cav}/{cci} → {serie:?} / {vorgang:?} has no family row"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn an_unknown_code_resolves_to_nothing_rather_than_a_neighbour() {
        assert_eq!(
            ZpSerie::from_wire("ZG7", "ZA9"),
            None,
            "eMob is not MaBiS Tabelle 1"
        );
        assert_eq!(ZpSerie::from_wire("ZZZ", "ZA9"), None);
        assert_eq!(ZpSerie::from_wire("Z95", "ZZZ"), None);
    }

    #[test]
    fn the_series_with_their_own_pids_are_not_reachable_from_the_generic_codes() {
        // The Zuordnungsermächtigung, the AAÜZ families and the LF-AASZR are
        // activated with 55071/55072 and 55197–55214, not with 55062/55063, so
        // no CAV code names them.
        let unreachable = [
            ZpSerie::Zuordnungsermaechtigung,
            ZpSerie::TaeglicheAauez,
            ZpSerie::LfAaszr,
            ZpSerie::MonatlicheAauezBkvLf,
            ZpSerie::MonatlicheAauezBkvAnfNb,
        ];
        for cav in [
            "Z95", "Z96", "Z97", "Z98", "Z99", "ZA0", "ZA1", "ZA2", "ZA3", "ZA4", "ZA5", "ZA6",
        ] {
            for cci in ["ZA8", "ZA9", "ZB7"] {
                if let Some(s) = ZpSerie::from_wire(cav, cci) {
                    assert!(!unreachable.contains(&s), "{cav}/{cci} → {s:?}");
                }
            }
        }
    }
}