bsv-sdk 0.2.82

Pure Rust implementation of the BSV Blockchain SDK
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
//! RemittanceManager — core orchestrator for the remittance protocol.
//!
//! This file is gated behind `#[cfg(feature = "network")]` via the module
//! declaration in `mod.rs`. All types, the manager struct, and all methods
//! require the serde + tokio async runtime.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, Notify};

use crate::remittance::comms_layer::CommsLayer;
use crate::remittance::error::RemittanceError;
use crate::remittance::identity_layer::IdentityLayer;
use crate::remittance::remittance_module::ErasedRemittanceModule;
use crate::remittance::types::{
    Amount, IdentityVerificationAcknowledgment, IdentityVerificationRequest,
    IdentityVerificationResponse, InstrumentBase, Invoice, LineItem, LoggerLike, ModuleContext,
    PeerMessage, Receipt, RemittanceCertificate, RemittanceEnvelope, RemittanceKind,
    RemittanceThreadState, Settlement, Termination, ThreadId, UnixMillis,
};
use crate::wallet::interfaces::{GetPublicKeyArgs, WalletInterface};

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Returns true if `state` is a terminal state (no further transitions expected).
fn is_terminal_state(state: &RemittanceThreadState) -> bool {
    matches!(
        state,
        RemittanceThreadState::Receipted
            | RemittanceThreadState::Terminated
            | RemittanceThreadState::Errored
    )
}

// ---------------------------------------------------------------------------
// Supporting enums
// ---------------------------------------------------------------------------

/// Role of this node in a remittance thread.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThreadRole {
    Maker,
    Taker,
}

/// Result of waiting for a receipt, allowing for graceful termination handling.
pub enum WaitReceiptResult {
    /// The thread reached Receipted state and a receipt was available.
    Receipt(Receipt),
    /// The counterparty terminated the thread before a receipt was issued.
    Terminated(Termination),
}

/// Result of waiting for a settlement, allowing for graceful termination handling.
pub enum WaitSettlementResult {
    /// The thread reached Settled state and a settlement was available.
    Settlement(Settlement),
    /// The counterparty terminated the thread before settlement occurred.
    Terminated(Termination),
}

/// Direction of a protocol log entry relative to this node.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum MessageDirection {
    #[serde(rename = "in")]
    In,
    #[serde(rename = "out")]
    Out,
}

/// When identity verification should occur within a thread.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IdentityPhase {
    Never,
    BeforeInvoicing,
    BeforeSettlement,
}

// ---------------------------------------------------------------------------
// Supporting structs
// ---------------------------------------------------------------------------

/// Identity-exchange status for one side of a thread.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ThreadIdentity {
    pub certs_sent: Vec<RemittanceCertificate>,
    pub certs_received: Vec<RemittanceCertificate>,
    pub request_sent: bool,
    pub response_sent: bool,
    pub acknowledgment_sent: bool,
    pub acknowledgment_received: bool,
}

/// Boolean flags summarizing the lifecycle progress of a thread.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ThreadFlags {
    pub has_identified: bool,
    pub has_invoiced: bool,
    pub has_paid: bool,
    pub has_receipted: bool,
    pub error: bool,
}

/// One entry in the state transition history of a thread.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateLogEntry {
    pub at: UnixMillis,
    pub from: RemittanceThreadState,
    pub to: RemittanceThreadState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// One entry in the protocol message history of a thread.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProtocolLogEntry {
    pub direction: MessageDirection,
    pub envelope: RemittanceEnvelope,
    pub transport_message_id: String,
}

/// An error that occurred on a thread, captured for later inspection.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadError {
    pub message: String,
    pub at: UnixMillis,
}

/// Full state of one remittance thread.
///
/// Serializes to camelCase JSON to match the TypeScript wire format.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Thread {
    pub thread_id: ThreadId,
    pub counterparty: String,
    pub my_role: ThreadRole,
    pub their_role: ThreadRole,
    pub created_at: UnixMillis,
    pub updated_at: UnixMillis,
    pub state: RemittanceThreadState,
    pub state_log: Vec<StateLogEntry>,
    pub processed_message_ids: Vec<String>,
    pub protocol_log: Vec<ProtocolLogEntry>,
    pub identity: ThreadIdentity,
    pub flags: ThreadFlags,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invoice: Option<Invoice>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub settlement: Option<Settlement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub receipt: Option<Receipt>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub termination: Option<Termination>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error: Option<ThreadError>,
}

/// Per-counterparty identity-phase configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentityRuntimeOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maker_request_identity: Option<IdentityPhase>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub taker_request_identity: Option<IdentityPhase>,
}

/// Runtime tuning options for the manager.
///
/// All fields have sensible defaults matching the TypeScript SDK.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemittanceManagerRuntimeOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identity_options: Option<IdentityRuntimeOptions>,
    /// Whether the peer has indicated it will provide a receipt.
    pub receipt_provided: bool,
    /// Automatically issue a receipt after accepting settlement.
    pub auto_issue_receipt: bool,
    /// Seconds until a sent invoice expires.
    pub invoice_expiry_seconds: u64,
    /// Milliseconds to wait for an identity response before timing out.
    pub identity_timeout_ms: u64,
    /// Milliseconds between identity-polling attempts (TS compat; Rust uses Notify).
    pub identity_poll_interval_ms: u64,
}

impl Default for RemittanceManagerRuntimeOptions {
    fn default() -> Self {
        Self {
            identity_options: None,
            // TS SDK defaults receipt_provided=true — peer is expected to send one.
            receipt_provided: true,
            auto_issue_receipt: true,
            invoice_expiry_seconds: 3600,
            identity_timeout_ms: 30_000,
            // TS SDK uses 500ms poll interval.
            identity_poll_interval_ms: 500,
        }
    }
}

/// Input for composing an invoice message.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComposeInvoiceInput {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    pub line_items: Vec<LineItem>,
    pub total: Amount,
    pub invoice_number: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arbitrary: Option<HashMap<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
}

/// Serializable state snapshot for persistence.
///
/// The `v` field (always 1) is the schema version sentinel for future migrations.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RemittanceManagerState {
    pub v: u8,
    pub threads: Vec<Thread>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_payment_option_id: Option<String>,
}

// ---------------------------------------------------------------------------
// Event enum
// ---------------------------------------------------------------------------

/// All events emitted by the RemittanceManager.
///
/// Derived `Clone` + `Debug` only — not serialized. Deliver to all registered
/// `on_event` listeners.
#[derive(Clone, Debug)]
pub enum RemittanceEvent {
    ThreadCreated {
        thread_id: ThreadId,
        thread: Thread,
    },
    StateChanged {
        thread_id: ThreadId,
        previous: RemittanceThreadState,
        next: RemittanceThreadState,
        reason: Option<String>,
    },
    EnvelopeSent {
        thread_id: ThreadId,
        envelope: RemittanceEnvelope,
        transport_message_id: String,
    },
    EnvelopeReceived {
        thread_id: ThreadId,
        envelope: RemittanceEnvelope,
        transport_message_id: String,
    },
    IdentityRequested {
        thread_id: ThreadId,
        direction: MessageDirection,
        request: IdentityVerificationRequest,
    },
    IdentityResponded {
        thread_id: ThreadId,
        direction: MessageDirection,
        response: IdentityVerificationResponse,
    },
    IdentityAcknowledged {
        thread_id: ThreadId,
        direction: MessageDirection,
        acknowledgment: IdentityVerificationAcknowledgment,
    },
    InvoiceSent {
        thread_id: ThreadId,
        invoice: Invoice,
    },
    InvoiceReceived {
        thread_id: ThreadId,
        invoice: Invoice,
    },
    SettlementSent {
        thread_id: ThreadId,
        settlement: Settlement,
    },
    SettlementReceived {
        thread_id: ThreadId,
        settlement: Settlement,
    },
    ReceiptSent {
        thread_id: ThreadId,
        receipt: Receipt,
    },
    ReceiptReceived {
        thread_id: ThreadId,
        receipt: Receipt,
    },
    TerminationSent {
        thread_id: ThreadId,
        termination: Termination,
    },
    TerminationReceived {
        thread_id: ThreadId,
        termination: Termination,
    },
    Error {
        thread_id: ThreadId,
        error: String,
    },
}

// ---------------------------------------------------------------------------
// Config (not Serialize/Deserialize — contains closures)
// ---------------------------------------------------------------------------

/// Construction-time configuration for RemittanceManager.
///
/// Closures must be `Send + Sync` because the manager is used across async tasks.
/// This struct intentionally does not derive Serialize/Deserialize.
pub struct RemittanceManagerConfig {
    /// Message box name for inbound messages.
    pub message_box: Option<String>,
    /// Originator string passed through to wallet calls.
    pub originator: Option<String>,
    /// Pluggable logger.
    pub logger: Option<Arc<dyn LoggerLike>>,
    /// Runtime tuning options (defaults apply when None).
    pub options: Option<RemittanceManagerRuntimeOptions>,
    /// Called for every event emitted by the manager.
    pub on_event: Option<Box<dyn Fn(RemittanceEvent) + Send + Sync>>,
    /// Called after every state change to persist the serialized state.
    pub state_saver: Option<Box<dyn Fn(RemittanceManagerState) + Send + Sync>>,
    /// Called during `init()` to restore previously persisted state.
    pub state_loader: Option<Box<dyn Fn() -> Option<RemittanceManagerState> + Send + Sync>>,
    /// Override for the current-time provider (useful in tests).
    pub now: Option<Box<dyn Fn() -> UnixMillis + Send + Sync>>,
    /// Override for thread-ID generation (useful in tests).
    pub thread_id_factory: Option<Box<dyn Fn() -> ThreadId + Send + Sync>>,
}

// ---------------------------------------------------------------------------
// Inner state
// ---------------------------------------------------------------------------

/// Mutable state owned by the manager.
///
/// Lives behind `Arc<Mutex<ManagerInner>>` so multiple clones of `RemittanceManager`
/// (e.g. passed into async tasks) share the same state safely.
struct ManagerInner {
    threads: HashMap<ThreadId, Thread>,
    default_payment_option_id: Option<String>,
    my_identity_key: Option<String>,
    event_listeners: Vec<(usize, Arc<dyn Fn(RemittanceEvent) + Send + Sync>)>,
    next_listener_id: usize,
}

// ---------------------------------------------------------------------------
// RemittanceManager
// ---------------------------------------------------------------------------

/// Core orchestrator for peer-to-peer remittance protocol exchanges.
///
/// Cheaply cloneable — all mutable state is behind `Arc<Mutex<ManagerInner>>`.
/// All async methods require the tokio runtime (gated via `network` feature).
#[derive(Clone)]
pub struct RemittanceManager {
    inner: Arc<Mutex<ManagerInner>>,
    pub(crate) config: Arc<RemittanceManagerConfig>,
    wallet: Arc<dyn WalletInterface>,
    pub(crate) comms: Arc<dyn CommsLayer>,
    pub(crate) identity: Option<Arc<dyn IdentityLayer>>,
    /// Module registry keyed by module ID. Arc (not Mutex) — modules are immutable after construction.
    pub(crate) modules: Arc<HashMap<String, Box<dyn ErasedRemittanceModule>>>,
    /// Per-thread notify handles for `waitFor*` callers.
    pub(crate) notifiers: Arc<Mutex<HashMap<ThreadId, Arc<Notify>>>>,
    pub(crate) options: RemittanceManagerRuntimeOptions,
}

impl RemittanceManager {
    /// Construct a new manager with the given config and service dependencies.
    ///
    /// Modules are registered at construction time and never mutated afterwards,
    /// so they live behind `Arc<HashMap>` (no lock required on every pay/accept call).
    pub fn new(
        config: RemittanceManagerConfig,
        wallet: Arc<dyn WalletInterface>,
        comms: Arc<dyn CommsLayer>,
        identity: Option<Arc<dyn IdentityLayer>>,
        modules: Vec<Box<dyn ErasedRemittanceModule>>,
    ) -> Self {
        let options = config.options.clone().unwrap_or_default();

        let module_map: HashMap<String, Box<dyn ErasedRemittanceModule>> = modules
            .into_iter()
            .map(|m| (m.id().to_string(), m))
            .collect();

        let inner = ManagerInner {
            threads: HashMap::new(),
            default_payment_option_id: None,
            my_identity_key: None,
            event_listeners: Vec::new(),
            next_listener_id: 0,
        };

        let config_arc = Arc::new(config);

        let manager = Self {
            inner: Arc::new(Mutex::new(inner)),
            config: config_arc,
            wallet,
            comms,
            identity,
            modules: Arc::new(module_map),
            notifiers: Arc::new(Mutex::new(HashMap::new())),
            options,
        };

        // Register the on_event closure from config as a listener, via a forwarding Arc.
        // We do this synchronously since new() is not async.
        if manager.config.on_event.is_some() {
            let cfg = Arc::clone(&manager.config);
            let listener: Arc<dyn Fn(RemittanceEvent) + Send + Sync> =
                Arc::new(move |event: RemittanceEvent| {
                    if let Some(ref handler) = cfg.on_event {
                        handler(event);
                    }
                });
            // SAFETY: new() is called before any other async access; we can block_on or use
            // try_lock here. Since no tasks are running yet, try_lock always succeeds.
            if let Ok(mut guard) = manager.inner.try_lock() {
                let id = guard.next_listener_id;
                guard.next_listener_id += 1;
                guard.event_listeners.push((id, listener));
            }
        }

        manager
    }

    // -----------------------------------------------------------------------
    // Initialisation
    // -----------------------------------------------------------------------

    /// Load persisted state and refresh the identity key from the wallet.
    ///
    /// Must be called after construction and before any protocol operations.
    pub async fn init(&self) -> Result<(), RemittanceError> {
        // Restore state from persistence, if a loader was provided.
        if let Some(ref loader) = self.config.state_loader {
            if let Some(state) = loader() {
                self.load_state(state).await;
            }
        }

        // Refresh the node's own identity public key from the wallet.
        self.refresh_my_identity_key().await?;

        Ok(())
    }

    /// Fetch this node's identity public key from the wallet and cache it.
    pub(crate) async fn refresh_my_identity_key(&self) -> Result<(), RemittanceError> {
        let args = GetPublicKeyArgs {
            identity_key: true,
            protocol_id: None,
            key_id: None,
            counterparty: None,
            privileged: false,
            privileged_reason: None,
            for_self: None,
            seek_permission: None,
        };
        let originator = self.config.originator.as_deref();
        let result = self.wallet.get_public_key(args, originator).await?;
        let key_hex = result.public_key.to_der_hex();

        let mut guard = self.inner.lock().await;
        guard.my_identity_key = Some(key_hex);
        Ok(())
    }

    // -----------------------------------------------------------------------
    // State persistence
    // -----------------------------------------------------------------------

    /// Snapshot the current state as a serializable envelope.
    pub async fn save_state(&self) -> RemittanceManagerState {
        let guard = self.inner.lock().await;
        RemittanceManagerState {
            v: 1,
            threads: guard.threads.values().cloned().collect(),
            default_payment_option_id: guard.default_payment_option_id.clone(),
        }
    }

    /// Snapshot and call `state_saver` if one was configured.
    pub async fn persist_state(&self) {
        let state = self.save_state().await;
        if let Some(ref saver) = self.config.state_saver {
            saver(state);
        }
    }

    /// Replace inner thread map and options from a serialized state envelope.
    pub async fn load_state(&self, state: RemittanceManagerState) {
        let mut guard = self.inner.lock().await;
        guard.threads = state
            .threads
            .into_iter()
            .map(|t| (t.thread_id.clone(), t))
            .collect();
        guard.default_payment_option_id = state.default_payment_option_id;
    }

    // -----------------------------------------------------------------------
    // State machine
    // -----------------------------------------------------------------------

    /// Attempt to transition `thread_id` from its current state to `to`.
    ///
    /// Validates the transition, appends a `StateLogEntry`, emits `StateChanged`,
    /// notifies any `waitForState` callers, and persists the new state.
    /// Returns `RemittanceError::InvalidStateTransition` on invalid transitions.
    pub async fn transition_thread_state(
        &self,
        thread_id: &str,
        to: RemittanceThreadState,
        reason: Option<String>,
    ) -> Result<(), RemittanceError> {
        // Collect data under lock, then drop guard before calling async methods.
        let (previous, notify) = {
            let mut guard = self.inner.lock().await;
            let thread = guard.threads.get_mut(thread_id).ok_or_else(|| {
                RemittanceError::Protocol(format!("thread not found: {}", thread_id))
            })?;

            let current = thread.state.clone();

            if !crate::remittance::types::is_valid_transition(&current, &to) {
                return Err(RemittanceError::InvalidStateTransition {
                    from: current.to_string(),
                    to: to.to_string(),
                });
            }

            let now = self.now_internal();
            thread.state_log.push(StateLogEntry {
                at: now,
                from: current.clone(),
                to: to.clone(),
                reason: reason.clone(),
            });
            thread.state = to.clone();
            thread.updated_at = now;

            // Grab or create the Notify for this thread (outside the inner lock to avoid nesting).
            // We'll look it up from notifiers after releasing inner.
            (current, thread_id.to_string())
        };

        // Emit event (does not hold inner guard).
        let event = RemittanceEvent::StateChanged {
            thread_id: notify.clone(),
            previous,
            next: to,
            reason,
        };
        self.emit_event(event).await;

        // Wake any tokio::sync::Notify waiters for this thread.
        let notifier = {
            let mut nmap = self.notifiers.lock().await;
            nmap.entry(notify.clone())
                .or_insert_with(|| Arc::new(Notify::new()))
                .clone()
        };
        notifier.notify_waiters();

        // Persist after notifying waiters so callers see the new state.
        self.persist_state().await;

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Event system
    // -----------------------------------------------------------------------

    /// Register a listener that receives every future event.
    ///
    /// Returns a listener ID that can be passed to [`remove_event_listener`] to
    /// unsubscribe — mirroring the TS SDK's `onEvent` which returns an
    /// unsubscribe function.
    pub async fn on_event(&self, listener: Arc<dyn Fn(RemittanceEvent) + Send + Sync>) -> usize {
        let mut guard = self.inner.lock().await;
        let id = guard.next_listener_id;
        guard.next_listener_id += 1;
        guard.event_listeners.push((id, listener));
        id
    }

    /// Remove a previously registered event listener by its ID.
    ///
    /// Returns `true` if a listener with the given ID was found and removed.
    pub async fn remove_event_listener(&self, listener_id: usize) -> bool {
        let mut guard = self.inner.lock().await;
        let len_before = guard.event_listeners.len();
        guard.event_listeners.retain(|(id, _)| *id != listener_id);
        guard.event_listeners.len() < len_before
    }

    /// Deliver `event` to all registered listeners.
    ///
    /// Public so that downstream code and integration tests can synthesise events.
    pub async fn emit_event(&self, event: RemittanceEvent) {
        // Clone the listener list so we can call outside the lock.
        let listeners: Vec<(usize, Arc<dyn Fn(RemittanceEvent) + Send + Sync>)> = {
            let guard = self.inner.lock().await;
            guard.event_listeners.clone()
        };
        for (_id, listener) in listeners {
            listener(event.clone());
        }
    }

    // -----------------------------------------------------------------------
    // Thread accessors
    // -----------------------------------------------------------------------

    /// Returns a clone of the thread if it exists, or `None`.
    pub async fn get_thread(&self, thread_id: &str) -> Option<Thread> {
        let guard = self.inner.lock().await;
        guard.threads.get(thread_id).cloned()
    }

    /// Returns a clone of the thread, or `RemittanceError::Protocol` if not found.
    pub async fn get_thread_or_throw(&self, thread_id: &str) -> Result<Thread, RemittanceError> {
        self.get_thread(thread_id)
            .await
            .ok_or_else(|| RemittanceError::Protocol(format!("thread not found: {}", thread_id)))
    }

    /// Returns a `ThreadHandle` for ergonomic chained access.
    pub async fn get_thread_handle(
        &self,
        thread_id: &str,
    ) -> Result<ThreadHandle, RemittanceError> {
        // Verify the thread exists before issuing a handle.
        let _ = self.get_thread_or_throw(thread_id).await?;
        Ok(ThreadHandle {
            manager: self.clone(),
            thread_id: thread_id.to_string(),
        })
    }

    /// Insert a thread into the inner map directly (used by invoice/create flows and tests).
    pub async fn insert_thread(&self, thread: Thread) {
        let mut guard = self.inner.lock().await;
        guard.threads.insert(thread.thread_id.clone(), thread);
    }

    /// Update a thread in place using a mutable closure.
    pub(crate) async fn update_thread<F>(
        &self,
        thread_id: &str,
        f: F,
    ) -> Result<(), RemittanceError>
    where
        F: FnOnce(&mut Thread),
    {
        let mut guard = self.inner.lock().await;
        let thread = guard
            .threads
            .get_mut(thread_id)
            .ok_or_else(|| RemittanceError::Protocol(format!("thread not found: {}", thread_id)))?;
        f(thread);
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Payment option helpers
    // -----------------------------------------------------------------------

    /// Set the default payment option ID used when none is specified (takes Option<String>).
    ///
    /// Use `preselect_payment_option_id` for the `&str` public API variant.
    pub async fn preselect_payment_option(&self, option_id: Option<String>) {
        let mut guard = self.inner.lock().await;
        guard.default_payment_option_id = option_id;
        drop(guard);
        self.persist_state().await;
    }

    /// Set the default payment option ID from a string slice and persist state.
    ///
    /// This is the primary public API — corresponds to the TypeScript
    /// `preselectPaymentOption(optionId: string)` method.
    pub async fn preselect_payment_option_id(&self, option_id: &str) {
        {
            let mut guard = self.inner.lock().await;
            guard.default_payment_option_id = Some(option_id.to_string());
        }
        self.persist_state().await;
    }

    /// Get the current default payment option ID.
    pub async fn get_default_payment_option_id(&self) -> Option<String> {
        let guard = self.inner.lock().await;
        guard.default_payment_option_id.clone()
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    /// Returns current Unix time in milliseconds, using override if configured.
    pub(crate) fn now_internal(&self) -> UnixMillis {
        if let Some(ref f) = self.config.now {
            return f();
        }
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }

    /// Returns the current time (public alias for external callers).
    pub fn now(&self) -> UnixMillis {
        self.now_internal()
    }

    /// Generates a fresh thread ID using the configured factory or getrandom.
    pub fn generate_thread_id(&self) -> ThreadId {
        if let Some(ref f) = self.config.thread_id_factory {
            return f();
        }
        let mut bytes = [0u8; 16];
        getrandom::getrandom(&mut bytes).expect("getrandom failed");
        bytes.iter().fold(String::with_capacity(32), |mut acc, b| {
            use std::fmt::Write;
            let _ = write!(acc, "{:02x}", b);
            acc
        })
    }

    /// Expose the wallet reference for use by sub-flows.
    pub(crate) fn wallet(&self) -> &Arc<dyn WalletInterface> {
        &self.wallet
    }

    /// Expose inner my_identity_key.
    pub(crate) async fn my_identity_key(&self) -> Option<String> {
        let guard = self.inner.lock().await;
        guard.my_identity_key.clone()
    }

    // -----------------------------------------------------------------------
    // ModuleContext factory
    // -----------------------------------------------------------------------

    /// Build a ModuleContext that shares the manager's clock and wallet.
    ///
    /// If `config.now` is set (e.g. for tests), modules see the same overridden
    /// clock as the manager itself.
    fn make_module_context(&self) -> ModuleContext {
        let now_fn: Arc<dyn Fn() -> u64 + Send + Sync> = match &self.config.now {
            Some(f) => {
                // Wrap the config closure in an Arc so ModuleContext can clone it.
                let cfg = Arc::clone(&self.config);
                Arc::new(move || (cfg.now.as_ref().unwrap())())
            }
            None => Arc::new(|| {
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis() as u64
            }),
        };
        ModuleContext {
            wallet: Arc::clone(&self.wallet),
            originator: self.config.originator.clone(),
            now: now_fn,
            logger: self.config.logger.clone(),
        }
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    /// Create a RemittanceEnvelope from its parts.
    fn make_envelope(
        kind: RemittanceKind,
        thread_id: &str,
        payload: serde_json::Value,
        now: UnixMillis,
    ) -> RemittanceEnvelope {
        // Generate a random ID for the envelope using getrandom.
        let mut bytes = [0u8; 16];
        getrandom::getrandom(&mut bytes).expect("getrandom failed");
        let id = bytes.iter().fold(String::with_capacity(32), |mut acc, b| {
            use std::fmt::Write;
            let _ = write!(acc, "{:02x}", b);
            acc
        });
        RemittanceEnvelope {
            v: 1,
            id,
            kind,
            thread_id: thread_id.to_string(),
            created_at: now,
            payload,
        }
    }

    /// Serialize and send an envelope to a recipient.
    ///
    /// Tries `send_live_message` first; falls back to `send_message` on error.
    /// After sending, appends to the thread's protocol log and emits `EnvelopeSent`.
    async fn send_envelope(
        &self,
        recipient: &str,
        env: &RemittanceEnvelope,
        host_override: Option<&str>,
    ) -> Result<String, RemittanceError> {
        let body = serde_json::to_string(env)?;
        let message_box = self.config.message_box.as_deref().unwrap_or("remittance");

        // Try live first; fall back to queued.
        let transport_message_id = match self
            .comms
            .send_live_message(recipient, message_box, &body, host_override)
            .await
        {
            Ok(id) => id,
            Err(_) => {
                self.comms
                    .send_message(recipient, message_box, &body, host_override)
                    .await?
            }
        };

        // Append to protocol log (under lock) without holding lock across await.
        let log_entry = ProtocolLogEntry {
            direction: MessageDirection::Out,
            envelope: env.clone(),
            transport_message_id: transport_message_id.clone(),
        };
        {
            let mut guard = self.inner.lock().await;
            if let Some(thread) = guard.threads.get_mut(&env.thread_id) {
                thread.protocol_log.push(log_entry);
            }
        }

        // Emit event (no lock held).
        self.emit_event(RemittanceEvent::EnvelopeSent {
            thread_id: env.thread_id.clone(),
            envelope: env.clone(),
            transport_message_id: transport_message_id.clone(),
        })
        .await;

        Ok(transport_message_id)
    }

    /// Compose an Invoice from ComposeInvoiceInput and module-generated options.
    ///
    /// Calls `create_option_erased` on each registered module that supports it,
    /// collecting option terms keyed by module ID.
    async fn compose_invoice(
        &self,
        thread: &Thread,
        input: &ComposeInvoiceInput,
    ) -> Result<Invoice, RemittanceError> {
        let now = self.now_internal();
        let my_key = {
            let guard = self.inner.lock().await;
            guard.my_identity_key.clone().unwrap_or_default()
        };

        let base = InstrumentBase {
            thread_id: thread.thread_id.clone(),
            payee: my_key,
            payer: thread.counterparty.clone(),
            note: input.note.clone(),
            line_items: input.line_items.clone(),
            total: input.total.clone(),
            invoice_number: input.invoice_number.clone(),
            created_at: now,
            arbitrary: input.arbitrary.clone(),
        };

        let expires_at = input
            .expires_at
            .or_else(|| Some(now + self.options.invoice_expiry_seconds * 1_000));

        // Draft invoice (without options yet) for passing to create_option_erased.
        let draft = Invoice {
            kind: RemittanceKind::Invoice,
            expires_at,
            options: HashMap::new(),
            base: base.clone(),
        };

        let ctx = self.make_module_context();
        let mut options: HashMap<String, serde_json::Value> = HashMap::new();

        // Collect options from all modules that support create_option.
        // modules is Arc<HashMap> — no lock needed.
        for (module_id, module) in self.modules.as_ref() {
            if module.supports_create_option() {
                let option_value = module
                    .create_option_erased(&thread.thread_id, &draft, &ctx)
                    .await?;
                options.insert(module_id.clone(), option_value);
            }
        }

        Ok(Invoice {
            kind: RemittanceKind::Invoice,
            expires_at,
            options,
            base,
        })
    }

    /// Perform identity exchange with the counterparty if required.
    ///
    /// Checks runtime options to decide whether identity is needed.
    /// If an identity layer is configured and the phase is not Never,
    /// sends an IdentityVerificationRequest envelope.
    async fn ensure_identity_exchange(
        &self,
        thread_id: &str,
        counterparty: &str,
    ) -> Result<(), RemittanceError> {
        let identity_layer = match &self.identity {
            Some(il) => il.clone(),
            None => return Ok(()),
        };

        // Determine whether identity is needed based on role and options.
        let should_request = match &self.options.identity_options {
            None => false,
            Some(id_opts) => {
                // Maker initiates — check maker_request_identity phase.
                let phase = id_opts.maker_request_identity.as_ref();
                matches!(
                    phase,
                    Some(IdentityPhase::BeforeInvoicing) | Some(IdentityPhase::BeforeSettlement)
                )
            }
        };

        if !should_request {
            return Ok(());
        }

        let ctx = self.make_module_context();
        let request = identity_layer
            .determine_certificates_to_request(counterparty, thread_id, &ctx)
            .await?;

        let payload = serde_json::to_value(&request)?;
        let env = Self::make_envelope(
            RemittanceKind::IdentityVerificationRequest,
            thread_id,
            payload,
            self.now_internal(),
        );

        self.send_envelope(counterparty, &env, None).await?;

        // Transition to IdentityRequested.
        self.transition_thread_state(
            thread_id,
            RemittanceThreadState::IdentityRequested,
            Some("identity exchange initiated".to_string()),
        )
        .await?;

        self.emit_event(RemittanceEvent::IdentityRequested {
            thread_id: thread_id.to_string(),
            direction: MessageDirection::Out,
            request,
        })
        .await;

        Ok(())
    }

    /// Create a new thread with the given counterparty and role.
    async fn create_thread(
        &self,
        counterparty: &str,
        my_role: ThreadRole,
    ) -> Result<Thread, RemittanceError> {
        let thread_id = self.generate_thread_id();
        let now = self.now_internal();
        let their_role = match my_role {
            ThreadRole::Maker => ThreadRole::Taker,
            ThreadRole::Taker => ThreadRole::Maker,
        };

        let thread = Thread {
            thread_id: thread_id.clone(),
            counterparty: counterparty.to_string(),
            my_role,
            their_role,
            created_at: now,
            updated_at: now,
            state: RemittanceThreadState::New,
            state_log: Vec::new(),
            processed_message_ids: Vec::new(),
            protocol_log: Vec::new(),
            identity: ThreadIdentity::default(),
            flags: ThreadFlags::default(),
            invoice: None,
            settlement: None,
            receipt: None,
            termination: None,
            last_error: None,
        };

        {
            let mut guard = self.inner.lock().await;
            guard.threads.insert(thread_id.clone(), thread.clone());
        }

        self.emit_event(RemittanceEvent::ThreadCreated {
            thread_id: thread_id.clone(),
            thread: thread.clone(),
        })
        .await;

        Ok(thread)
    }

    // -----------------------------------------------------------------------
    // Public payment flow API
    // -----------------------------------------------------------------------

    /// Create a new thread (maker), optionally run identity exchange, compose
    /// an invoice with module options, send it, and transition to Invoiced.
    pub async fn send_invoice(
        &self,
        counterparty: &str,
        input: ComposeInvoiceInput,
        host_override: Option<&str>,
    ) -> Result<InvoiceHandle, RemittanceError> {
        let thread = self.create_thread(counterparty, ThreadRole::Maker).await?;
        let thread_id = thread.thread_id.clone();

        // Identity exchange (if configured).
        self.ensure_identity_exchange(&thread_id, counterparty)
            .await?;

        // Re-fetch thread after possible identity transition.
        let thread = self.get_thread_or_throw(&thread_id).await?;
        let invoice = self.compose_invoice(&thread, &input).await?;

        let payload = serde_json::to_value(&invoice)?;
        let env = Self::make_envelope(
            RemittanceKind::Invoice,
            &thread_id,
            payload,
            self.now_internal(),
        );

        self.send_envelope(counterparty, &env, host_override)
            .await?;

        // Store invoice on thread and transition to Invoiced (lock-free across await).
        {
            let mut guard = self.inner.lock().await;
            if let Some(t) = guard.threads.get_mut(&thread_id) {
                t.invoice = Some(invoice.clone());
                t.flags.has_invoiced = true;
            }
        }

        self.transition_thread_state(
            &thread_id,
            RemittanceThreadState::Invoiced,
            Some("invoice sent".to_string()),
        )
        .await?;

        self.emit_event(RemittanceEvent::InvoiceSent {
            thread_id: thread_id.clone(),
            invoice,
        })
        .await;

        Ok(InvoiceHandle {
            handle: ThreadHandle {
                manager: self.clone(),
                thread_id,
            },
        })
    }

    /// Send an invoice on an existing thread.
    pub async fn send_invoice_for_thread(
        &self,
        thread_id: &str,
        input: ComposeInvoiceInput,
        host_override: Option<&str>,
    ) -> Result<InvoiceHandle, RemittanceError> {
        let thread = self.get_thread_or_throw(thread_id).await?;
        let counterparty = thread.counterparty.clone();

        let invoice = self.compose_invoice(&thread, &input).await?;

        let payload = serde_json::to_value(&invoice)?;
        let env = Self::make_envelope(
            RemittanceKind::Invoice,
            thread_id,
            payload,
            self.now_internal(),
        );

        self.send_envelope(&counterparty, &env, host_override)
            .await?;

        {
            let mut guard = self.inner.lock().await;
            if let Some(t) = guard.threads.get_mut(thread_id) {
                t.invoice = Some(invoice.clone());
                t.flags.has_invoiced = true;
            }
        }

        self.transition_thread_state(
            thread_id,
            RemittanceThreadState::Invoiced,
            Some("invoice sent on existing thread".to_string()),
        )
        .await?;

        self.emit_event(RemittanceEvent::InvoiceSent {
            thread_id: thread_id.to_string(),
            invoice,
        })
        .await;

        Ok(InvoiceHandle {
            handle: ThreadHandle {
                manager: self.clone(),
                thread_id: thread_id.to_string(),
            },
        })
    }

    /// Return all threads where this node is the taker and the state is Invoiced.
    ///
    /// If `counterparty` is Some, only threads with that counterparty are returned.
    pub async fn find_invoices_payable(&self, counterparty: Option<&str>) -> Vec<InvoiceHandle> {
        let guard = self.inner.lock().await;
        guard
            .threads
            .values()
            .filter(|t| {
                matches!(t.my_role, ThreadRole::Taker)
                    && t.state == RemittanceThreadState::Invoiced
                    && counterparty.map_or(true, |c| t.counterparty == c)
            })
            .map(|t| InvoiceHandle {
                handle: ThreadHandle {
                    manager: self.clone(),
                    thread_id: t.thread_id.clone(),
                },
            })
            .collect()
    }

    /// Return all threads where this node is the maker and the state is Invoiced.
    ///
    /// If `counterparty` is Some, only threads with that counterparty are returned.
    pub async fn find_receivable_invoices(&self, counterparty: Option<&str>) -> Vec<InvoiceHandle> {
        let guard = self.inner.lock().await;
        guard
            .threads
            .values()
            .filter(|t| {
                matches!(t.my_role, ThreadRole::Maker)
                    && t.state == RemittanceThreadState::Invoiced
                    && counterparty.map_or(true, |c| t.counterparty == c)
            })
            .map(|t| InvoiceHandle {
                handle: ThreadHandle {
                    manager: self.clone(),
                    thread_id: t.thread_id.clone(),
                },
            })
            .collect()
    }

    /// Pay an invoice on a thread.
    ///
    /// Selects the payment module by `option_id`, the default option ID, or the
    /// first available option in the invoice. Calls `build_settlement_erased`,
    /// sends a Settlement envelope, transitions to Settled.
    pub async fn pay(
        &self,
        thread_id: &str,
        option_id: Option<&str>,
        host_override: Option<&str>,
    ) -> Result<ThreadHandle, RemittanceError> {
        let thread = self.get_thread_or_throw(thread_id).await?;

        if thread.state != RemittanceThreadState::Invoiced {
            return Err(RemittanceError::Protocol(format!(
                "thread {} is not in Invoiced state (current: {})",
                thread_id, thread.state
            )));
        }

        let invoice = thread.invoice.as_ref().ok_or_else(|| {
            RemittanceError::Protocol(format!("thread {} has no invoice", thread_id))
        })?;

        // Reject expired invoices.
        if let Some(expires_at) = invoice.expires_at {
            if self.now_internal() > expires_at {
                return Err(RemittanceError::Protocol(format!(
                    "invoice on thread {} has expired",
                    thread_id
                )));
            }
        }

        // Determine option_id to use.
        let default_option_id = {
            let guard = self.inner.lock().await;
            guard.default_payment_option_id.clone()
        };

        let selected_option_id = option_id
            .map(|s| s.to_string())
            .or(default_option_id)
            .or_else(|| invoice.options.keys().next().cloned())
            .ok_or_else(|| {
                RemittanceError::Protocol(format!(
                    "no payment option available for thread {}",
                    thread_id
                ))
            })?;

        let option_value = invoice
            .options
            .get(&selected_option_id)
            .cloned()
            .unwrap_or(serde_json::Value::Null);

        let module = self.modules.get(&selected_option_id).ok_or_else(|| {
            RemittanceError::Protocol(format!("module not found: {}", selected_option_id))
        })?;

        let note = invoice.base.note.as_deref();
        let ctx = self.make_module_context();

        let result = module
            .build_settlement_erased(thread_id, Some(invoice), &option_value, note, &ctx)
            .await?;

        let counterparty = thread.counterparty.clone();
        let my_key = {
            let guard = self.inner.lock().await;
            guard.my_identity_key.clone().unwrap_or_default()
        };
        let now = self.now_internal();

        match result.action {
            "settle" => {
                let artifact = result.artifact.unwrap_or(serde_json::Value::Null);
                let settlement = Settlement {
                    kind: RemittanceKind::Settlement,
                    thread_id: thread_id.to_string(),
                    module_id: selected_option_id.clone(),
                    option_id: selected_option_id.clone(),
                    sender: my_key,
                    created_at: now,
                    artifact,
                    note: None,
                };

                let payload = serde_json::to_value(&settlement)?;
                let env = Self::make_envelope(RemittanceKind::Settlement, thread_id, payload, now);

                self.send_envelope(&counterparty, &env, host_override)
                    .await?;

                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.settlement = Some(settlement.clone());
                        t.flags.has_paid = true;
                    }
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::Settled,
                    Some("settlement sent".to_string()),
                )
                .await?;

                self.emit_event(RemittanceEvent::SettlementSent {
                    thread_id: thread_id.to_string(),
                    settlement,
                })
                .await;
            }
            "terminate" => {
                let termination = result.termination.unwrap_or_else(|| Termination {
                    code: "module_terminated".to_string(),
                    message: "module requested termination".to_string(),
                    details: None,
                });

                let payload = serde_json::to_value(&termination)?;
                let env = Self::make_envelope(RemittanceKind::Termination, thread_id, payload, now);

                self.send_envelope(&counterparty, &env, host_override)
                    .await?;

                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.termination = Some(termination.clone());
                    }
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::Terminated,
                    Some("module requested termination".to_string()),
                )
                .await?;

                self.emit_event(RemittanceEvent::TerminationSent {
                    thread_id: thread_id.to_string(),
                    termination,
                })
                .await;
            }
            other => {
                return Err(RemittanceError::Protocol(format!(
                    "unexpected build_settlement action: {}",
                    other
                )));
            }
        }

        Ok(ThreadHandle {
            manager: self.clone(),
            thread_id: thread_id.to_string(),
        })
    }

    // -----------------------------------------------------------------------
    // Inbound message pipeline
    // -----------------------------------------------------------------------

    /// Parse an inbound PeerMessage, deduplicate, and dispatch to the correct handler.
    pub(crate) async fn handle_inbound_message(
        &self,
        msg: PeerMessage,
    ) -> Result<(), RemittanceError> {
        // Parse envelope from message body.
        let envelope: RemittanceEnvelope = serde_json::from_str(&msg.body)
            .map_err(|e| RemittanceError::Protocol(format!("invalid envelope: {}", e)))?;

        // Get or create thread for this inbound message.
        let thread_id = self
            .get_or_create_thread_from_inbound(&envelope, &msg.sender)
            .await?;

        // Deduplication: skip if already processed.
        {
            let guard = self.inner.lock().await;
            if let Some(thread) = guard.threads.get(&thread_id) {
                if thread.processed_message_ids.contains(&msg.message_id) {
                    // Already processed — acknowledge and return.
                    drop(guard);
                    let _ = self.comms.acknowledge_message(&[msg.message_id]).await;
                    return Ok(());
                }
            }
        }

        // Dispatch to kind-specific handler.
        self.apply_inbound_envelope(&thread_id, envelope.clone())
            .await?;

        // Record message ID and log entry under lock.
        let log_entry = ProtocolLogEntry {
            direction: MessageDirection::In,
            envelope: envelope.clone(),
            transport_message_id: msg.message_id.clone(),
        };
        {
            let mut guard = self.inner.lock().await;
            if let Some(thread) = guard.threads.get_mut(&thread_id) {
                thread.processed_message_ids.push(msg.message_id.clone());
                thread.protocol_log.push(log_entry);
            }
        }

        // Emit EnvelopeReceived event.
        self.emit_event(RemittanceEvent::EnvelopeReceived {
            thread_id: thread_id.clone(),
            envelope,
            transport_message_id: msg.message_id.clone(),
        })
        .await;

        // Acknowledge message transport.
        let _ = self.comms.acknowledge_message(&[msg.message_id]).await;

        // Persist updated state.
        self.persist_state().await;

        Ok(())
    }

    /// Determine the thread_id for an inbound message, creating a new thread if needed.
    async fn get_or_create_thread_from_inbound(
        &self,
        env: &RemittanceEnvelope,
        sender: &str,
    ) -> Result<ThreadId, RemittanceError> {
        // Check if thread already exists.
        {
            let guard = self.inner.lock().await;
            if guard.threads.contains_key(&env.thread_id) {
                return Ok(env.thread_id.clone());
            }
        }

        // Determine our role based on message kind.
        // Invoice → I am taker (maker is initiating).
        // Settlement (unsolicited) → I am maker (paying party sends without invoice).
        // Receipt/Termination on new thread → I am taker (default — we did not create this).
        // Identity messages → infer from config which party is the requester, then derive role.
        let my_role = match &env.kind {
            RemittanceKind::Invoice => ThreadRole::Taker,
            RemittanceKind::Settlement => ThreadRole::Maker,
            RemittanceKind::Receipt | RemittanceKind::Termination => ThreadRole::Taker,
            RemittanceKind::IdentityVerificationRequest
            | RemittanceKind::IdentityVerificationResponse
            | RemittanceKind::IdentityVerificationAcknowledgment => {
                // Determine which role is the requester per config. When only the maker is
                // configured to request, the requester_role is Maker; when only the taker is
                // configured, requester_role is Taker; otherwise default to Maker.
                let identity_opts = self.options.identity_options.as_ref();
                let maker_requests = identity_opts
                    .and_then(|o| o.maker_request_identity.as_ref())
                    .map(|p| !matches!(p, IdentityPhase::Never))
                    .unwrap_or(false);
                let taker_requests = identity_opts
                    .and_then(|o| o.taker_request_identity.as_ref())
                    .map(|p| !matches!(p, IdentityPhase::Never))
                    .unwrap_or(false);

                let requester_role = if maker_requests && !taker_requests {
                    ThreadRole::Maker
                } else if taker_requests && !maker_requests {
                    ThreadRole::Taker
                } else {
                    // Both or neither — default to Maker as requester.
                    ThreadRole::Maker
                };

                // For a Response: the requester is receiving the response (I am the requester).
                // For a Request or Acknowledgment: the other party is acting, so I am the opposite.
                match &env.kind {
                    RemittanceKind::IdentityVerificationResponse => requester_role,
                    _ => match requester_role {
                        ThreadRole::Maker => ThreadRole::Taker,
                        ThreadRole::Taker => ThreadRole::Maker,
                    },
                }
            }
        };

        let thread = self
            .create_thread_with_id(sender, my_role, &env.thread_id)
            .await?;
        Ok(thread.thread_id)
    }

    /// Create a new thread with a specific thread_id (for inbound message flows).
    async fn create_thread_with_id(
        &self,
        counterparty: &str,
        my_role: ThreadRole,
        thread_id: &str,
    ) -> Result<Thread, RemittanceError> {
        let now = self.now_internal();
        let their_role = match my_role {
            ThreadRole::Maker => ThreadRole::Taker,
            ThreadRole::Taker => ThreadRole::Maker,
        };

        let thread = Thread {
            thread_id: thread_id.to_string(),
            counterparty: counterparty.to_string(),
            my_role,
            their_role,
            created_at: now,
            updated_at: now,
            state: RemittanceThreadState::New,
            state_log: Vec::new(),
            processed_message_ids: Vec::new(),
            protocol_log: Vec::new(),
            identity: ThreadIdentity::default(),
            flags: ThreadFlags::default(),
            invoice: None,
            settlement: None,
            receipt: None,
            termination: None,
            last_error: None,
        };

        {
            let mut guard = self.inner.lock().await;
            guard.threads.insert(thread_id.to_string(), thread.clone());
        }

        self.emit_event(RemittanceEvent::ThreadCreated {
            thread_id: thread_id.to_string(),
            thread: thread.clone(),
        })
        .await;

        Ok(thread)
    }

    /// Dispatch an inbound envelope to the appropriate protocol handler by kind.
    async fn apply_inbound_envelope(
        &self,
        thread_id: &str,
        env: RemittanceEnvelope,
    ) -> Result<(), RemittanceError> {
        // Extract sender from thread (counterparty field).
        let (sender, invoice_opt, settlement_opt, my_role, has_identified) = {
            let guard = self.inner.lock().await;
            let thread = guard.threads.get(thread_id).ok_or_else(|| {
                RemittanceError::Protocol(format!("thread not found: {}", thread_id))
            })?;
            (
                thread.counterparty.clone(),
                thread.invoice.clone(),
                thread.settlement.clone(),
                thread.my_role.clone(),
                thread.flags.has_identified,
            )
        };

        match env.kind {
            RemittanceKind::IdentityVerificationRequest => {
                let request: IdentityVerificationRequest =
                    serde_json::from_value(env.payload.clone()).map_err(|e| {
                        RemittanceError::Protocol(format!("bad IdentityVerificationRequest: {}", e))
                    })?;

                let identity = match &self.identity {
                    Some(il) => il.clone(),
                    None => {
                        // No identity layer — send termination.
                        let termination = Termination {
                            code: "no_identity_layer".to_string(),
                            message: "no identity layer configured".to_string(),
                            details: None,
                        };
                        let payload = serde_json::to_value(&termination)?;
                        let term_env = Self::make_envelope(
                            RemittanceKind::Termination,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &term_env, None).await?;
                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::Terminated,
                            Some("no identity layer".to_string()),
                        )
                        .await?;
                        return Ok(());
                    }
                };

                let ctx = self.make_module_context();
                let result = identity
                    .respond_to_request(&sender, thread_id, &request, &ctx)
                    .await?;

                match result {
                    crate::remittance::identity_layer::RespondToRequestResult::Respond {
                        response,
                    } => {
                        let certs = response.certificates.clone();
                        let payload = serde_json::to_value(&response)?;
                        let resp_env = Self::make_envelope(
                            RemittanceKind::IdentityVerificationResponse,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &resp_env, None).await?;

                        {
                            let mut guard = self.inner.lock().await;
                            if let Some(t) = guard.threads.get_mut(thread_id) {
                                t.identity.response_sent = true;
                                t.identity.certs_sent = certs;
                            }
                        }

                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::IdentityResponded,
                            Some("identity response sent".to_string()),
                        )
                        .await?;

                        self.emit_event(RemittanceEvent::IdentityRequested {
                            thread_id: thread_id.to_string(),
                            direction: MessageDirection::In,
                            request,
                        })
                        .await;
                    }
                    crate::remittance::identity_layer::RespondToRequestResult::Terminate {
                        termination,
                    } => {
                        let payload = serde_json::to_value(&termination)?;
                        let term_env = Self::make_envelope(
                            RemittanceKind::Termination,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &term_env, None).await?;
                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::Terminated,
                            Some("identity terminated".to_string()),
                        )
                        .await?;
                    }
                }
            }

            RemittanceKind::IdentityVerificationResponse => {
                let response: IdentityVerificationResponse =
                    serde_json::from_value(env.payload.clone()).map_err(|e| {
                        RemittanceError::Protocol(format!(
                            "bad IdentityVerificationResponse: {}",
                            e
                        ))
                    })?;

                let identity = match &self.identity {
                    Some(il) => il.clone(),
                    None => {
                        return Err(RemittanceError::Protocol(
                            "received IdentityVerificationResponse with no identity layer"
                                .to_string(),
                        ));
                    }
                };

                let result = identity
                    .assess_received_certificate_sufficiency(&sender, &response, thread_id)
                    .await?;

                match result {
                    crate::remittance::identity_layer::AssessIdentityResult::Acknowledge(ack) => {
                        let certs_received = response.certificates.clone();
                        let payload = serde_json::to_value(&ack)?;
                        let ack_env = Self::make_envelope(
                            RemittanceKind::IdentityVerificationAcknowledgment,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &ack_env, None).await?;

                        {
                            let mut guard = self.inner.lock().await;
                            if let Some(t) = guard.threads.get_mut(thread_id) {
                                t.identity.certs_received = certs_received;
                                t.identity.acknowledgment_sent = true;
                                t.flags.has_identified = true;
                            }
                        }

                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::IdentityAcknowledged,
                            Some("identity acknowledged".to_string()),
                        )
                        .await?;

                        self.emit_event(RemittanceEvent::IdentityResponded {
                            thread_id: thread_id.to_string(),
                            direction: MessageDirection::In,
                            response,
                        })
                        .await;
                    }
                    crate::remittance::identity_layer::AssessIdentityResult::Terminate(
                        termination,
                    ) => {
                        let payload = serde_json::to_value(&termination)?;
                        let term_env = Self::make_envelope(
                            RemittanceKind::Termination,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &term_env, None).await?;
                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::Terminated,
                            Some("identity assessment terminated".to_string()),
                        )
                        .await?;
                    }
                }
            }

            RemittanceKind::IdentityVerificationAcknowledgment => {
                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.identity.acknowledgment_received = true;
                        t.flags.has_identified = true;
                    }
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::IdentityAcknowledged,
                    Some("identity acknowledgment received".to_string()),
                )
                .await?;

                let ack: IdentityVerificationAcknowledgment =
                    serde_json::from_value(env.payload.clone()).unwrap_or_else(|_| {
                        IdentityVerificationAcknowledgment {
                            kind: RemittanceKind::IdentityVerificationAcknowledgment,
                            thread_id: thread_id.to_string(),
                        }
                    });
                self.emit_event(RemittanceEvent::IdentityAcknowledged {
                    thread_id: thread_id.to_string(),
                    direction: MessageDirection::In,
                    acknowledgment: ack,
                })
                .await;
            }

            RemittanceKind::Invoice => {
                let invoice: Invoice = serde_json::from_value(env.payload.clone())
                    .map_err(|e| RemittanceError::Protocol(format!("bad Invoice: {}", e)))?;

                let invoice_clone = invoice.clone();
                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.invoice = Some(invoice.clone());
                        t.flags.has_invoiced = true;
                    }
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::Invoiced,
                    Some("invoice received".to_string()),
                )
                .await?;

                self.emit_event(RemittanceEvent::InvoiceReceived {
                    thread_id: thread_id.to_string(),
                    invoice: invoice_clone,
                })
                .await;
            }

            RemittanceKind::Settlement => {
                // PARITY-06 / PARITY-12: If the maker required identity before settlement and
                // identity has not been completed, reject the settlement with a termination.
                // Only applies when I am the Maker — the party that issued the requirement.
                let should_require_identity = matches!(my_role, ThreadRole::Maker)
                    && matches!(
                        self.options
                            .identity_options
                            .as_ref()
                            .and_then(|o| o.maker_request_identity.as_ref()),
                        Some(IdentityPhase::BeforeSettlement)
                    )
                    && !has_identified;

                if should_require_identity {
                    let termination = Termination {
                        code: "identity.required".to_string(),
                        message: "Identity verification is required before settlement".to_string(),
                        details: None,
                    };
                    let payload = serde_json::to_value(&termination)?;
                    let term_env = Self::make_envelope(
                        RemittanceKind::Termination,
                        thread_id,
                        payload,
                        self.now_internal(),
                    );
                    self.send_envelope(&sender, &term_env, None).await?;
                    self.transition_thread_state(
                        thread_id,
                        RemittanceThreadState::Terminated,
                        Some("identity required before settlement".to_string()),
                    )
                    .await?;
                    return Ok(());
                }

                let settlement: Settlement = serde_json::from_value(env.payload.clone())
                    .map_err(|e| RemittanceError::Protocol(format!("bad Settlement: {}", e)))?;

                let module_id = settlement.module_id.clone();
                let module = match self.modules.get(&module_id) {
                    Some(m) => m,
                    None => {
                        return Err(RemittanceError::Protocol(format!(
                            "no module registered for module_id: {}",
                            module_id
                        )));
                    }
                };

                let ctx = self.make_module_context();
                let result = module
                    .accept_settlement_erased(
                        thread_id,
                        invoice_opt.as_ref(),
                        &settlement.artifact,
                        &sender,
                        &ctx,
                    )
                    .await?;

                let settlement_clone = settlement.clone();
                match result.action {
                    "accept" => {
                        // Store settlement on thread.
                        {
                            let mut guard = self.inner.lock().await;
                            if let Some(t) = guard.threads.get_mut(thread_id) {
                                t.settlement = Some(settlement.clone());
                                t.flags.has_paid = true;
                            }
                        }

                        if self.options.auto_issue_receipt {
                            let receipt_data =
                                result.receipt_data.unwrap_or(serde_json::Value::Null);
                            // Build payee/payer from invoice if available, else use thread info.
                            let (payee, payer) = if let Some(ref inv) = invoice_opt {
                                (inv.base.payee.clone(), inv.base.payer.clone())
                            } else {
                                // Maker receives settlement, so maker is payee.
                                let guard = self.inner.lock().await;
                                let thread = guard.threads.get(thread_id);
                                let key = guard.my_identity_key.clone().unwrap_or_default();
                                let cp = thread.map(|t| t.counterparty.clone()).unwrap_or_default();
                                drop(guard);
                                (key, cp)
                            };
                            let receipt = Receipt {
                                kind: RemittanceKind::Receipt,
                                thread_id: thread_id.to_string(),
                                module_id: settlement.module_id.clone(),
                                option_id: settlement.option_id.clone(),
                                payee,
                                payer,
                                receipt_data,
                                created_at: self.now_internal(),
                            };
                            let receipt_clone = receipt.clone();
                            let payload = serde_json::to_value(&receipt)?;
                            let receipt_env = Self::make_envelope(
                                RemittanceKind::Receipt,
                                thread_id,
                                payload,
                                self.now_internal(),
                            );
                            self.send_envelope(&sender, &receipt_env, None).await?;

                            {
                                let mut guard = self.inner.lock().await;
                                if let Some(t) = guard.threads.get_mut(thread_id) {
                                    t.receipt = Some(receipt.clone());
                                    t.flags.has_receipted = true;
                                }
                            }

                            self.transition_thread_state(
                                thread_id,
                                RemittanceThreadState::Settled,
                                Some("settlement accepted".to_string()),
                            )
                            .await?;

                            self.transition_thread_state(
                                thread_id,
                                RemittanceThreadState::Receipted,
                                Some("receipt auto-issued".to_string()),
                            )
                            .await?;

                            self.emit_event(RemittanceEvent::ReceiptSent {
                                thread_id: thread_id.to_string(),
                                receipt: receipt_clone,
                            })
                            .await;
                        } else {
                            self.transition_thread_state(
                                thread_id,
                                RemittanceThreadState::Settled,
                                Some("settlement accepted".to_string()),
                            )
                            .await?;
                        }

                        self.emit_event(RemittanceEvent::SettlementReceived {
                            thread_id: thread_id.to_string(),
                            settlement: settlement_clone,
                        })
                        .await;
                    }
                    "terminate" => {
                        let termination = result.termination.unwrap_or_else(|| Termination {
                            code: "module_terminated".to_string(),
                            message: "module rejected settlement".to_string(),
                            details: None,
                        });
                        let payload = serde_json::to_value(&termination)?;
                        let term_env = Self::make_envelope(
                            RemittanceKind::Termination,
                            thread_id,
                            payload,
                            self.now_internal(),
                        );
                        self.send_envelope(&sender, &term_env, None).await?;
                        self.transition_thread_state(
                            thread_id,
                            RemittanceThreadState::Terminated,
                            Some("module rejected settlement".to_string()),
                        )
                        .await?;

                        self.emit_event(RemittanceEvent::SettlementReceived {
                            thread_id: thread_id.to_string(),
                            settlement: settlement_clone,
                        })
                        .await;
                    }
                    other => {
                        return Err(RemittanceError::Protocol(format!(
                            "unexpected accept_settlement action: {}",
                            other
                        )));
                    }
                }
            }

            RemittanceKind::Receipt => {
                let receipt: Receipt = serde_json::from_value(env.payload.clone())
                    .map_err(|e| RemittanceError::Protocol(format!("bad Receipt: {}", e)))?;

                let receipt_clone = receipt.clone();
                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.receipt = Some(receipt.clone());
                        t.flags.has_receipted = true;
                    }
                }

                // Call module's process_receipt_erased if available (swallow errors).
                // Use settlement's module_id (most reliable) or the receipt's module_id.
                let module_id_for_receipt = settlement_opt
                    .as_ref()
                    .map(|s| s.module_id.as_str())
                    .unwrap_or(&receipt.module_id);
                if let Some(module) = self.modules.get(module_id_for_receipt) {
                    let ctx = self.make_module_context();
                    let _ = module
                        .process_receipt_erased(
                            thread_id,
                            invoice_opt.as_ref(),
                            &receipt.receipt_data,
                            &sender,
                            &ctx,
                        )
                        .await;
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::Receipted,
                    Some("receipt received".to_string()),
                )
                .await?;

                self.emit_event(RemittanceEvent::ReceiptReceived {
                    thread_id: thread_id.to_string(),
                    receipt: receipt_clone,
                })
                .await;
            }

            RemittanceKind::Termination => {
                let termination: Termination = serde_json::from_value(env.payload.clone())
                    .map_err(|e| RemittanceError::Protocol(format!("bad Termination: {}", e)))?;

                let termination_clone = termination.clone();
                {
                    let mut guard = self.inner.lock().await;
                    if let Some(t) = guard.threads.get_mut(thread_id) {
                        t.termination = Some(termination.clone());
                        t.flags.error = true;
                    }
                }

                // Call module's process_termination_erased if available (swallow errors).
                // Use settlement's module_id if available, else try the first registered module.
                let module_for_term = if let Some(s) = settlement_opt.as_ref() {
                    self.modules.get(&s.module_id)
                } else {
                    self.modules.values().next()
                };
                if let Some(module) = module_for_term {
                    let ctx = self.make_module_context();
                    let _ = module
                        .process_termination_erased(
                            thread_id,
                            invoice_opt.as_ref(),
                            settlement_opt.as_ref(),
                            &termination,
                            &sender,
                            &ctx,
                        )
                        .await;
                }

                self.transition_thread_state(
                    thread_id,
                    RemittanceThreadState::Terminated,
                    Some(format!("termination received: {}", termination_clone.code)),
                )
                .await?;

                self.emit_event(RemittanceEvent::TerminationReceived {
                    thread_id: thread_id.to_string(),
                    termination: termination_clone,
                })
                .await;
            }
        }

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Comms integration
    // -----------------------------------------------------------------------

    /// Fetch all pending messages from the CommsLayer and process each one.
    pub async fn sync_threads(&self, host_override: Option<&str>) -> Result<(), RemittanceError> {
        let message_box = self.config.message_box.as_deref().unwrap_or("remittance");
        let messages = self.comms.list_messages(message_box, host_override).await?;
        for msg in messages {
            // Errors on individual messages are logged, not fatal.
            if let Err(e) = self.handle_inbound_message(msg).await {
                if let Some(logger) = &self.config.logger {
                    logger.error(&[&"sync_threads: error processing message", &e.to_string()]);
                }
            }
        }
        Ok(())
    }

    /// Register a live message callback with the CommsLayer.
    ///
    /// The callback spawns a tokio task for each inbound message, so this
    /// method returns immediately after registration.
    pub async fn start_listening(
        &self,
        host_override: Option<&str>,
    ) -> Result<(), RemittanceError> {
        let message_box = self.config.message_box.as_deref().unwrap_or("remittance");
        let manager_clone = self.clone();
        let callback: Arc<dyn Fn(PeerMessage) + Send + Sync> = Arc::new(move |msg: PeerMessage| {
            let mgr = manager_clone.clone();
            tokio::spawn(async move {
                let _ = mgr.handle_inbound_message(msg).await;
            });
        });
        self.comms
            .listen_for_live_messages(message_box, host_override, callback)
            .await?;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Notify-based waiters
    // -----------------------------------------------------------------------

    /// Wait until a thread reaches `target` state (or a terminal state).
    ///
    /// Uses `tokio::sync::Notify` to avoid busy-polling. The lost-wakeup
    /// prevention pattern registers the `notified()` future before re-checking
    /// state under lock. If `timeout_ms` is Some, returns `RemittanceError::Timeout`
    /// if the target state is not reached within the given duration.
    pub async fn wait_for_state(
        &self,
        thread_id: &str,
        target: RemittanceThreadState,
        timeout_ms: Option<u64>,
    ) -> Result<Thread, RemittanceError> {
        let fut = async {
            loop {
                // Register notify handle under lock, then check state.
                let notify = {
                    let mut nmap = self.notifiers.lock().await;
                    nmap.entry(thread_id.to_string())
                        .or_insert_with(|| Arc::new(Notify::new()))
                        .clone()
                };

                // CRITICAL: Create notified future before releasing any lock that
                // guards state, to prevent lost wakeups.
                let notified = notify.notified();

                // Re-check state under inner lock.
                {
                    let inner = self.inner.lock().await;
                    if let Some(thread) = inner.threads.get(thread_id) {
                        if thread.state == target || is_terminal_state(&thread.state) {
                            return Ok(thread.clone());
                        }
                    } else {
                        return Err(RemittanceError::Protocol(format!(
                            "thread not found: {}",
                            thread_id
                        )));
                    }
                }

                notified.await;
            }
        };

        if let Some(ms) = timeout_ms {
            tokio::time::timeout(std::time::Duration::from_millis(ms), fut)
                .await
                .map_err(|_| {
                    RemittanceError::Timeout(format!(
                        "wait_for_state timed out after {}ms waiting for thread {} to reach {:?}",
                        ms, thread_id, target
                    ))
                })?
        } else {
            fut.await
        }
    }

    /// Wait until a thread reaches `Receipted` state and return the receipt.
    ///
    /// If the thread reaches `Terminated` state first, returns `WaitReceiptResult::Terminated`.
    /// If the thread reaches `Errored` state, returns the error from `last_error`.
    /// If `timeout_ms` is Some, returns `RemittanceError::Timeout` on expiry.
    pub async fn wait_for_receipt(
        &self,
        thread_id: &str,
        timeout_ms: Option<u64>,
    ) -> Result<WaitReceiptResult, RemittanceError> {
        let thread = self
            .wait_for_state(thread_id, RemittanceThreadState::Receipted, timeout_ms)
            .await?;
        if thread.state == RemittanceThreadState::Terminated {
            return Ok(WaitReceiptResult::Terminated(thread.termination.unwrap_or(
                Termination {
                    code: "terminated".into(),
                    message: "counterparty terminated".into(),
                    details: None,
                },
            )));
        }
        if thread.state == RemittanceThreadState::Errored {
            let msg = thread
                .last_error
                .map(|e| e.message)
                .unwrap_or_else(|| "unknown error".into());
            return Err(RemittanceError::Protocol(format!(
                "thread {} entered Errored state: {}",
                thread_id, msg
            )));
        }
        thread
            .receipt
            .map(WaitReceiptResult::Receipt)
            .ok_or_else(|| {
                RemittanceError::Protocol(format!(
                    "thread {} reached Receipted state but has no receipt",
                    thread_id
                ))
            })
    }

    /// Wait until the thread has completed identity exchange.
    pub async fn wait_for_identity(
        &self,
        thread_id: &str,
        timeout_ms: Option<u64>,
    ) -> Result<Thread, RemittanceError> {
        self.wait_for_state(
            thread_id,
            RemittanceThreadState::IdentityAcknowledged,
            timeout_ms,
        )
        .await
    }

    /// Wait until a thread reaches `Settled` state and return the settlement.
    ///
    /// If the thread reaches `Terminated` state first, returns `WaitSettlementResult::Terminated`.
    /// If the thread reaches `Errored` state, returns the error from `last_error`.
    /// If `timeout_ms` is Some, returns `RemittanceError::Timeout` on expiry.
    pub async fn wait_for_settlement(
        &self,
        thread_id: &str,
        timeout_ms: Option<u64>,
    ) -> Result<WaitSettlementResult, RemittanceError> {
        let thread = self
            .wait_for_state(thread_id, RemittanceThreadState::Settled, timeout_ms)
            .await?;
        if thread.state == RemittanceThreadState::Terminated {
            return Ok(WaitSettlementResult::Terminated(
                thread.termination.unwrap_or(Termination {
                    code: "terminated".into(),
                    message: "counterparty terminated".into(),
                    details: None,
                }),
            ));
        }
        if thread.state == RemittanceThreadState::Errored {
            let msg = thread
                .last_error
                .map(|e| e.message)
                .unwrap_or_else(|| "unknown error".into());
            return Err(RemittanceError::Protocol(format!(
                "thread {} entered Errored state: {}",
                thread_id, msg
            )));
        }
        thread
            .settlement
            .map(WaitSettlementResult::Settlement)
            .ok_or_else(|| {
                RemittanceError::Protocol(format!(
                    "thread {} reached Settled state but has no settlement",
                    thread_id
                ))
            })
    }

    /// Send a settlement without a prior invoice (unsolicited).
    ///
    /// Creates a new taker thread, verifies the module allows unsolicited
    /// settlements, calls `build_settlement_erased` with no invoice, and sends.
    ///
    /// `option` is the module-specific option data (e.g. payment terms) passed
    /// through to `build_settlement`. `note` is an optional human-readable note.
    pub async fn send_unsolicited_settlement(
        &self,
        counterparty: &str,
        module_id: &str,
        option_id: &str,
        option: serde_json::Value,
        note: Option<&str>,
        host_override: Option<&str>,
    ) -> Result<ThreadHandle, RemittanceError> {
        let thread = self.create_thread(counterparty, ThreadRole::Taker).await?;
        let thread_id = thread.thread_id.clone();

        let module = self
            .modules
            .get(module_id)
            .ok_or_else(|| RemittanceError::Protocol(format!("module not found: {}", module_id)))?;

        if !module.allow_unsolicited_settlements() {
            return Err(RemittanceError::Protocol(format!(
                "module {} does not allow unsolicited settlements",
                module_id
            )));
        }

        let ctx = self.make_module_context();
        let result = module
            .build_settlement_erased(&thread_id, None, &option, note, &ctx)
            .await?;

        let my_key = {
            let guard = self.inner.lock().await;
            guard.my_identity_key.clone().unwrap_or_default()
        };
        let now = self.now_internal();

        let artifact = result.artifact.unwrap_or(serde_json::Value::Null);
        let settlement = Settlement {
            kind: RemittanceKind::Settlement,
            thread_id: thread_id.clone(),
            module_id: module_id.to_string(),
            option_id: option_id.to_string(),
            sender: my_key,
            created_at: now,
            artifact,
            note: note.map(|s| s.to_string()),
        };

        let payload = serde_json::to_value(&settlement)?;
        let env = Self::make_envelope(RemittanceKind::Settlement, &thread_id, payload, now);
        self.send_envelope(counterparty, &env, host_override)
            .await?;

        {
            let mut guard = self.inner.lock().await;
            if let Some(t) = guard.threads.get_mut(&thread_id) {
                t.settlement = Some(settlement.clone());
                t.flags.has_paid = true;
            }
        }

        self.transition_thread_state(
            &thread_id,
            RemittanceThreadState::Settled,
            Some("unsolicited settlement sent".to_string()),
        )
        .await?;

        self.emit_event(RemittanceEvent::SettlementSent {
            thread_id: thread_id.clone(),
            settlement,
        })
        .await;

        Ok(ThreadHandle {
            manager: self.clone(),
            thread_id,
        })
    }
}

// ---------------------------------------------------------------------------
// ThreadHandle / InvoiceHandle
// ---------------------------------------------------------------------------

/// Ergonomic handle to a thread with shorthand accessor methods.
pub struct ThreadHandle {
    pub manager: RemittanceManager,
    pub thread_id: ThreadId,
}

impl ThreadHandle {
    /// Returns the thread ID string.
    pub fn thread_id(&self) -> &str {
        &self.thread_id
    }

    /// Returns the current thread state, or an error if the thread has been removed.
    pub async fn get_thread(&self) -> Result<Thread, RemittanceError> {
        self.manager.get_thread_or_throw(&self.thread_id).await
    }

    /// Wait until the thread reaches `state` (or a terminal state).
    pub async fn wait_for_state(
        &self,
        state: RemittanceThreadState,
        timeout_ms: Option<u64>,
    ) -> Result<Thread, RemittanceError> {
        self.manager
            .wait_for_state(&self.thread_id, state, timeout_ms)
            .await
    }

    /// Wait until the thread has completed identity exchange.
    pub async fn wait_for_identity(
        &self,
        timeout_ms: Option<u64>,
    ) -> Result<Thread, RemittanceError> {
        self.manager
            .wait_for_identity(&self.thread_id, timeout_ms)
            .await
    }

    /// Wait until the thread has a confirmed settlement.
    pub async fn wait_for_settlement(
        &self,
        timeout_ms: Option<u64>,
    ) -> Result<WaitSettlementResult, RemittanceError> {
        self.manager
            .wait_for_settlement(&self.thread_id, timeout_ms)
            .await
    }

    /// Wait until the thread has been receipted.
    pub async fn wait_for_receipt(
        &self,
        timeout_ms: Option<u64>,
    ) -> Result<WaitReceiptResult, RemittanceError> {
        self.manager
            .wait_for_receipt(&self.thread_id, timeout_ms)
            .await
    }
}

/// Handle wrapping a `ThreadHandle` for invoice-specific operations.
pub struct InvoiceHandle {
    pub handle: ThreadHandle,
}

impl InvoiceHandle {
    /// Returns the invoice stored on the thread, or an error if not present.
    pub async fn invoice(&self) -> Result<Invoice, RemittanceError> {
        let thread = self.handle.get_thread().await?;
        thread.invoice.ok_or_else(|| {
            RemittanceError::Protocol(format!("thread {} has no invoice", self.handle.thread_id))
        })
    }

    /// Pay the invoice using the given option_id (or the default/first available).
    pub async fn pay(
        &self,
        option_id: Option<&str>,
        host_override: Option<&str>,
    ) -> Result<ThreadHandle, RemittanceError> {
        self.handle
            .manager
            .pay(&self.handle.thread_id, option_id, host_override)
            .await
    }
}