vector-core 0.13.1

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
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
//! Message sending — NIP-17 gift-wrapped DMs (text and file attachments).
//!
//! This is the core send pipeline used by all Vector interfaces (GUI, CLI, SDK).
//! Clients provide a `SendCallback` for status notifications (pending/sent/failed/progress)
//! and a `SendConfig` for retry/cancel behavior.

use crate::event_ext::FinalizeUnsignedWithId;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use nostr_sdk::prelude::*;

/// NIP-59's gift-wrap backdating window (0 to 2 days).
///
/// nostr 0.45 made its own copy of this private, but the wrap timestamps we mint
/// must stay inside the window readers expect, so it's pinned here rather than
/// re-guessed per call site.
pub const NIP59_RANDOM_TIMESTAMP_TWEAK: Range<u64> = 0..172_800;

/// `crate::clock::timestamp()` backdated by a random offset inside the NIP-59 window.
///
/// 0.45.0 removed `Timestamp::tweaked`; this mirrors what nip59 does internally.
pub fn tweaked_timestamp() -> Timestamp {
    use ::rand::Rng;
    let secs: u64 = ::rand::thread_rng().gen_range(NIP59_RANDOM_TIMESTAMP_TWEAK);
    Timestamp::from_secs(crate::clock::timestamp().as_secs().saturating_sub(secs))
}

use crate::state::{nostr_client, my_public_key, STATE};
use crate::types::{Message, Attachment};
use crate::crypto;

// ============================================================================
// SendCallback — Client notification trait
// ============================================================================

/// Callbacks invoked during the DM send pipeline.
///
/// Each method has a default no-op so simple callers (CLI, bots, tests)
/// implement only what they need. Methods are synchronous and non-fallible
/// by design — they should never block the send pipeline.
///
/// Exception: `on_upload_progress` returns `Result` — return `Err` to cancel.
pub trait SendCallback: Send + Sync {
    /// Message created and added to STATE as pending.
    fn on_pending(&self, _chat_id: &str, _msg: &Message) {}

    /// The flag a cancel flips for this pending message, if the client keeps one.
    /// The uploader polls it between progress ticks, so a cancel lands at once
    /// even while nothing is moving.
    fn cancel_token(&self, _pending_id: &str) -> Option<Arc<AtomicBool>> {
        None
    }

    /// File upload progress. Return Err("...") to cancel the upload.
    fn on_upload_progress(
        &self,
        _pending_id: &str,
        _percentage: u8,
        _bytes_sent: u64,
    ) -> Result<(), String> {
        Ok(())
    }

    /// Upload complete, attachment URL now available.
    fn on_upload_complete(&self, _chat_id: &str, _pending_id: &str, _attachment_id: &str, _url: &str) {}
    /// What an upload is doing before its bytes move: sealing (`"encrypting"`, with its
    /// percentage when it is streamed) or getting underway (`"starting"`).
    fn on_upload_stage(&self, _pending_id: &str, _stage: &str, _pct: Option<u8>) {}

    /// Message successfully delivered to at least one relay.
    /// `old_id` is the pending ID, `msg` has the real event ID.
    fn on_sent(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}

    /// Message delivery failed after all retry attempts.
    fn on_failed(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}

    /// The network in use refuses every relay the recipient reads (I2P-Only and clearnet inbox
    /// relays, say): the send fails at once, before `on_failed`, with this one-line reason.
    fn on_refused(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}

    /// Why the send failed, in one line the user can act on: called right before `on_failed`.
    fn on_failed_reason(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}

    /// Persist message to database. Default is no-op.
    /// Tauri implements this to call save_message + save_slim_chat.
    fn on_persist(&self, _chat_id: &str, _msg: &Message) {}
}

/// No-op callback for headless/CLI/test use.
pub struct NoOpSendCallback;
impl SendCallback for NoOpSendCallback {}

// ============================================================================
// SendConfig — Per-call configuration
// ============================================================================

/// Configuration for a send operation.
pub struct SendConfig {
    /// Max gift-wrap send attempts (default: 1).
    pub max_send_attempts: u32,
    /// Delay between send retries (default: 5 seconds).
    pub retry_delay: std::time::Duration,
    /// Send copy to own inbox for recovery/sync (default: false).
    pub self_send: bool,
    /// Cancel token for file uploads — set to true to abort.
    pub cancel_token: Option<Arc<AtomicBool>>,
    /// Max Blossom upload retries per server (default: 3).
    pub upload_retries: u32,
    /// Delay between upload retries (default: 2 seconds).
    pub upload_retry_delay: std::time::Duration,
    /// NIP-40 self-destruct expiry (unix secs) to stamp on the outgoing rumor
    /// and mirror onto the outer wrap. None = permanent. Resolved per-chat by
    /// the caller (the "Self-Destruct Timer" setting).
    pub expiration: Option<u64>,
    /// A self-destruct LIFESPAN (secs) resolved at publish instead: a file send
    /// stamps `now + lifespan` once its upload is done, so a slow upload does not
    /// eat into the message's life. Takes precedence over `expiration` there.
    pub self_destruct_secs: Option<u64>,
}

impl Default for SendConfig {
    fn default() -> Self {
        Self {
            max_send_attempts: 1,
            retry_delay: std::time::Duration::from_secs(5),
            self_send: false,
            cancel_token: None,
            upload_retries: 3,
            upload_retry_delay: std::time::Duration::from_secs(2),
            expiration: None,
            self_destruct_secs: None,
        }
    }
}

impl SendConfig {
    /// Preset for GUI clients (12 retries, self-send enabled).
    pub fn gui() -> Self {
        Self {
            max_send_attempts: 12,
            self_send: true,
            ..Default::default()
        }
    }

    /// Preset for headless/background mode (3 retries, self-send enabled).
    pub fn headless() -> Self {
        Self {
            max_send_attempts: 3,
            self_send: true,
            ..Default::default()
        }
    }
}

// ============================================================================
// SendResult
// ============================================================================

/// Result of sending a message.
#[derive(serde::Serialize, Clone, Debug)]
pub struct SendResult {
    /// The pending ID used while sending
    pub pending_id: String,
    /// The real event ID after successful send (None if failed)
    pub event_id: Option<String>,
    /// The chat ID (receiver npub for DMs)
    pub chat_id: String,
}

// ============================================================================
// Late-OK confirmation registry
// ============================================================================
//
// A relay's OK can outlive the per-attempt wait: slow links push the
// round-trip past nostr-sdk's OK timeout, and mobile handovers drop the
// socket after the EVENT frame was already delivered. The wrap is then
// on the relay while the sender believes it failed — the user re-sends
// and the recipient sees a double-post.
//
// Every wrap publish registers here before its first attempt. Hosts feed
// relay OKs back via `note_relay_ok` from their notification loop; an
// accepted OK counts as delivery no matter how late it arrives — it wakes
// the in-flight retry loop early, or rescues a message already marked
// Failed back to Sent.

struct WrapConfirm {
    wrap_id: EventId,
    chat_id: String,
    pending_id: String,
    /// Inner rumor id — the message's final id after finalization.
    rumor_event_id: String,
    rumor: UnsignedEvent,
    callback: Arc<dyn SendCallback>,
    self_send: bool,
    confirmed: AtomicBool,
    /// Claimed by whichever path (retry loop or note_relay_ok) performs
    /// the failed→sent rescue, so it happens exactly once.
    rescued: AtomicBool,
    /// Set once the retry loop has exited after marking the message
    /// failed — from then on `note_relay_ok` performs the rescue itself.
    loop_exited: AtomicBool,
    notify: tokio::sync::Notify,
    /// Weak: the entry lives in this session's own scoped map, so a strong
    /// reference would keep a swapped-out account alive forever.
    session: std::sync::Weak<crate::db::Session>,
    registered_at: web_time::Instant,
}

/// Entries carry this account's chat and message ids, so a late OK must only
/// ever rescue a message in the account that sent it.
struct WrapConfirms;

fn wrap_confirms() -> Arc<std::sync::Mutex<std::collections::HashMap<EventId, Arc<WrapConfirm>>>> {
    crate::db::current_session().scoped::<WrapConfirms, _>()
}

/// An OK this long after the last publish attempt is a ghost — drop the
/// entry rather than resurrect a message the user has moved past.
const WRAP_CONFIRM_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);

fn register_wrap_confirm(entry: Arc<WrapConfirm>) {
    let owner = wrap_confirms();
    let mut map = owner.lock().unwrap();
    map.retain(|_, e| e.registered_at.elapsed() < WRAP_CONFIRM_TTL);
    map.insert(entry.wrap_id, entry);
}

fn remove_wrap_confirm(wrap_id: &EventId) {
    wrap_confirms().lock().unwrap().remove(wrap_id);
}

/// Feed a relay `OK` for an outbound event back into the send pipeline.
///
/// Hosts call this from their notification loop for every
/// `RelayMessage::Ok`. Ids that aren't in-flight wraps miss the registry
/// and return immediately.
pub fn note_relay_ok(event_id: &EventId, accepted: bool) {
    if !accepted {
        return;
    }
    let entry = {
        let owner = wrap_confirms();
        let map = owner.lock().unwrap();
        map.get(event_id).cloned()
    };
    let Some(entry) = entry else { return };
    entry.confirmed.store(true, Ordering::SeqCst);
    entry.notify.notify_one();
    if !entry.loop_exited.load(Ordering::SeqCst)
        || entry.rescued.swap(true, Ordering::SeqCst)
    {
        return;
    }
    if !entry.session.upgrade().is_some_and(|s| s.is_live()) {
        remove_wrap_confirm(&entry.wrap_id);
        return;
    }
    crate::db::spawn_bound(async move {
        rescue_failed_as_sent(&entry).await;
        remove_wrap_confirm(&entry.wrap_id);
    });
}

/// Flip an already-failed message back to Sent — a late relay OK proved
/// the wrap was delivered.
async fn rescue_failed_as_sent(entry: &WrapConfirm) {
    let finalized = {
        let mut state = STATE.lock().await;
        state.update_message(&entry.pending_id, |msg| {
            msg.set_failed(false);
        });
        state.finalize_pending_message(&entry.chat_id, &entry.pending_id, &entry.rumor_event_id)
    };
    let Some((_old_id, ref msg)) = finalized else { return };
    crate::log_info!(
        "[Send] late relay OK confirmed wrap {} — message {} rescued to sent",
        entry.wrap_id,
        entry.rumor_event_id,
    );
    entry.callback.on_sent(&entry.chat_id, &entry.pending_id, msg);
    entry.callback.on_persist(&entry.chat_id, msg);
    // A late OK proved delivery — drop the retained resend body.
    if let Some(rid) = entry.rumor.id {
        let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
    }
    if entry.self_send {
        if let (Some(client), Some(my_pk)) = (nostr_client(), my_public_key()) {
            spawn_self_send(client, my_pk, entry.rumor.clone());
        }
    }
    crate::push::after_delivery(&entry.chat_id, &entry.rumor);
}

/// Fire-and-forget the self-send recovery copy + persist its wrap key.
fn spawn_self_send(client: Client, my_pk: PublicKey, rumor: UnsignedEvent) {
    let rid_for_self = rumor.id;
    crate::db::spawn_bound(async move {
        match crate::inbox_relays::send_gift_wrap_retained(
            &client, &my_pk, rumor, [],
        ).await {
            Ok(self_outcome) if !self_outcome.output.success.is_empty() => {
                if let Some(rid) = rid_for_self {
                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
                        &self_outcome.wrap_event_id,
                        &rid,
                        &my_pk,
                        crate::db::nip17_keys::WrapRole::SelfSend,
                        &self_outcome.wrap_secret,
                        &self_outcome.targeted_relays,
                    ) {
                        eprintln!("[NIP-17] failed to persist self-wrap key: {}", e);
                    }
                }
            }
            _ => {}
        }
    });
}

// ============================================================================
// Internal: retry gift-wrap send
// ============================================================================

/// Shared tail of send_dm / send_file_dm / send_rumor_dm:
/// gift-wrap → retry loop → finalize/fail → self-send.
///
/// The wrap is built ONCE and the identical event republished on every
/// attempt: a relay that already stored it answers the resend with
/// OK-true "duplicate", so a lost OK becomes a delivery confirmation on
/// the next attempt instead of an unconfirmed extra copy. The wrap's
/// ephemeral key is persisted via `db::nip17_keys::store_wrap_key`
/// BEFORE the first publish — a wrap can land without us ever seeing
/// the OK, and the user must still be able to NIP-09 it later.
#[allow(clippy::too_many_arguments)]
async fn retry_send_gift_wrap(
    client: &Client,
    receiver: &PublicKey,
    receiver_npub: &str,
    pending_id: &str,
    rumor: UnsignedEvent,
    event_id: &str,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
    // Manual retry injects the retained wrap so the EXACT same event
    // republishes (relay dedups the duplicate). `None` = a fresh send that
    // builds + retains the wrap in-loop.
    prebuilt: Option<crate::inbox_relays::BuiltGiftWrap>,
) -> Result<SendResult, String> {
    let my_pk = my_public_key().ok_or("Public key not set")?;
    let inner_rumor_id = rumor.id;

    // A resend already holds a persisted wrap key + retained body — don't
    // re-store either (that would reset the row's clock and re-stash bytes).
    let is_resend = prebuilt.is_some();
    // Built lazily in-loop so transient signer failures (NIP-46 bunker
    // round-trips) still get the full retry schedule; a resend seeds it.
    let mut built: Option<crate::inbox_relays::BuiltGiftWrap> = prebuilt;
    // Targets resolve once (again only after a lookup the network kept blind); transient
    // inbox connections live across the whole retry window rather than reconnecting per attempt.
    let mut targets: Option<crate::inbox_relays::GiftWrapTargets> = None;
    let mut confirm: Option<Arc<WrapConfirm>> = None;
    let mut last_error: Option<String> = None;
    // Why the last attempt had nowhere to publish: the lookup couldn't reach their relays.
    let mut unknown: Option<String> = None;
    let mut keys_stored = is_resend;
    // A cached inbox list is checked again at most once per send, after its relays all refused.
    let mut rechecked = false;

    let max_attempts = config.max_send_attempts.max(1);

    // Too large is final: no retry makes a relay take it.
    if let Err(why) = crate::event_size::check_rumor(&rumor) {
        fail_pending(&callback, receiver_npub, pending_id, &why).await;
        return Err(why);
    }

    // A network still starting is waited for once (as long as the retries would have taken, at
    // least its ready budget), so the inbox lookup can reach the relays that list it; one that
    // stays down fails the send with its reason.
    if crate::transport::blocked_reason().is_some() {
        let retries = config.retry_delay.saturating_mul(max_attempts.saturating_sub(1));
        let budget = crate::transport::budget(crate::transport::Op::ReadyWait, std::time::Duration::ZERO).max(retries);
        if let Err(why) = crate::transport::wait_ready(budget).await {
            fail_pending(&callback, receiver_npub, pending_id, &why).await;
            return Err(why);
        }
    }

    for attempt in 0..max_attempts {
        if built.is_none() {
            // Mirror any NIP-40 expiry from the rumor onto the outer wrap so
            // relays drop the gift-wrap on schedule (the inner tag is encrypted).
            let wrap_extra: Vec<Tag> = rumor.tags.iter()
                .find(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
                .cloned()
                .into_iter()
                .collect();
            match crate::inbox_relays::build_gift_wrap_retained(
                client, receiver, rumor.clone(), wrap_extra,
            ).await {
                Ok(b) => built = Some(b),
                Err(e) => {
                    crate::log_warn!(
                        "[Send] attempt {}/{} — building gift-wrap failed: {}",
                        attempt + 1, max_attempts, e,
                    );
                    last_error = Some(e);
                    if attempt + 1 < max_attempts {
                        crate::rt::time::sleep(config.retry_delay).await;
                    }
                    continue;
                }
            }
        }
        let wrap = built.as_ref().unwrap();

        if confirm.is_none() {
            let entry = Arc::new(WrapConfirm {
                wrap_id: wrap.event.id,
                chat_id: receiver_npub.to_string(),
                pending_id: pending_id.to_string(),
                rumor_event_id: event_id.to_string(),
                rumor: rumor.clone(),
                callback: callback.clone(),
                self_send: config.self_send,
                confirmed: AtomicBool::new(false),
                rescued: AtomicBool::new(false),
                loop_exited: AtomicBool::new(false),
                notify: tokio::sync::Notify::new(),
                session: std::sync::Arc::downgrade(&crate::db::current_session()),
                registered_at: web_time::Instant::now(),
            });
            register_wrap_confirm(entry.clone());
            confirm = Some(entry);
        }
        let confirm_ref = confirm.as_ref().unwrap();

        if let Some(t) = targets.as_ref().filter(|t| t.unknown.is_none()) {
            crate::inbox_relays::reconnect_gift_wrap_targets(t).await;
        } else {
            let t = crate::inbox_relays::resolve_gift_wrap_targets(client, receiver).await;
            // A cached list the network refuses may be out of date: ask once before failing.
            if t.refused.is_some() && t.from_cache && !rechecked {
                rechecked = true;
                if crate::inbox_relays::recheck_after_failure(client, receiver, &t.inbox_tried).await {
                    continue;
                }
            }
            // No retry changes a policy refusal: fail now, and say why.
            if let Some(why) = t.refused.clone() {
                remove_wrap_confirm(&confirm_ref.wrap_id);
                callback.on_refused(receiver_npub, pending_id, &why);
                fail_pending(&callback, receiver_npub, pending_id, &why).await;
                return Err(why);
            }
            // Unknown is not absent: nothing is published this attempt, and the next looks again
            // rather than landing on our own relays.
            if let Some(why) = t.unknown.clone() {
                crate::log_warn!("[Send] attempt {}/{} — inbox lookup out of reach: {}", attempt + 1, max_attempts, why);
                unknown = Some(why);
                targets = None;
                if attempt + 1 < max_attempts {
                    crate::rt::time::sleep(config.retry_delay).await;
                }
                continue;
            }
            unknown = None;
            // First send only: persist the wrap key (NIP-09 delete) AND retain
            // the exact wrap event + rumor (byte-identical resend on manual
            // retry). A resend already holds both.
            if !keys_stored {
                keys_stored = true;
                if let Some(rid) = inner_rumor_id {
                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
                        &wrap.event.id,
                        &rid,
                        receiver,
                        crate::db::nip17_keys::WrapRole::Recipient,
                        &wrap.secret,
                        &t.targeted_relays,
                    ) {
                        eprintln!("[NIP-17] failed to persist wrap key: {}", e);
                    }
                    if let Err(e) = crate::db::nip17_keys::stash_resend_payload(
                        &wrap.event.id, pending_id, &wrap.event, &rumor,
                    ) {
                        eprintln!("[NIP-17] failed to retain resend payload: {}", e);
                    }
                }
            }
            // A resend, or targets swapped after a re-check: a later delete must reach these too.
            if keys_stored && (is_resend || rechecked) {
                if let Err(e) = crate::db::nip17_keys::add_wrap_relays(&wrap.event.id, &t.targeted_relays) {
                    eprintln!("[NIP-17] failed to note the new wrap relays: {}", e);
                }
            }
            targets = Some(t);
        }
        let targets_ref = targets.as_ref().unwrap();
        let from_cache = targets_ref.from_cache;
        let inbox_tried = targets_ref.inbox_tried.clone();

        match crate::inbox_relays::publish_gift_wrap_to_targets(
            client, targets_ref, &wrap.event,
        ).await {
            Ok(output) if !output.success.is_empty() => {
                return Ok(finalize_gift_wrap_sent(
                    client, my_pk, receiver_npub, pending_id, event_id,
                    &rumor, config, &callback, confirm_ref, targets_ref,
                ).await);
            }
            Ok(output) => {
                // The publish round-trip ran but no targeted relay confirmed
                // (auth required, kind filter, rate-limit, timed-out OK,
                // etc.). Surface the per-relay failure reasons so the user
                // can see WHY their DMs aren't being accepted.
                let failures: Vec<String> = output.failed.iter()
                    .map(|(url, err)| format!("{}: {}", url, err))
                    .collect();
                crate::log_warn!(
                    "[Send] attempt {}/{} — 0 of {} relays accepted (targeted: {}). Per-relay errors: {}",
                    attempt + 1,
                    max_attempts,
                    targets_ref.targeted_relays.len(),
                    targets_ref.targeted_relays.join(", "),
                    if failures.is_empty() {
                        "(none reported — likely all timed out before responding)".to_string()
                    } else {
                        failures.join(" | ")
                    },
                );
                last_error = None;
            }
            Err(e) => {
                crate::log_warn!(
                    "[Send] attempt {}/{} — publish errored: {}",
                    attempt + 1, max_attempts, e,
                );
                last_error = Some(e);
            }
        }

        // A late OK for an earlier attempt may have arrived while this one
        // was publishing.
        if confirm_ref.confirmed.load(Ordering::SeqCst) {
            return Ok(finalize_gift_wrap_sent(
                client, my_pk, receiver_npub, pending_id, event_id,
                &rumor, config, &callback, confirm_ref, targets_ref,
            ).await);
        }

        // Every relay refused a list the cache served, which may be out of date: ask again, and
        // if it changed, the next attempt goes to the new one at once.
        if from_cache && !rechecked && attempt + 1 < max_attempts {
            rechecked = true;
            if crate::inbox_relays::recheck_after_failure(client, receiver, &inbox_tried).await {
                crate::log_info!("[Send] {}'s inbox relays changed; sending to the new ones", receiver_npub);
                if let Some(old) = targets.take() {
                    crate::inbox_relays::teardown_gift_wrap_targets(client, &old).await;
                }
                continue;
            }
        }

        if attempt + 1 < max_attempts {
            // Sleep out the retry delay, waking instantly on a late OK
            // (notify_one stores a permit, so an OK landing before this
            // line still wakes us).
            let _ = crate::rt::time::timeout(
                config.retry_delay,
                confirm_ref.notify.notified(),
            ).await;
            if confirm_ref.confirmed.load(Ordering::SeqCst) {
                return Ok(finalize_gift_wrap_sent(
                    client, my_pk, receiver_npub, pending_id, event_id,
                    &rumor, config, &callback, confirm_ref, targets_ref,
                ).await);
            }
        }
    }

    // No OK is no proof it didn't land: a relay seen holding the wrap is proof it did.
    if let (Some(wrap), Some(t), Some(entry)) = (built.as_ref(), targets.as_ref(), confirm.as_ref()) {
        if wrap_on_relays(client, &wrap.event, receiver, t).await {
            return Ok(finalize_gift_wrap_sent(
                client, my_pk, receiver_npub, pending_id, event_id,
                &rumor, config, &callback, entry, t,
            ).await);
        }
    }

    // Exhausted every attempt with no OK observed. Mark failed, but leave
    // the confirmation entry armed: a straggler OK can still rescue this
    // message to Sent (see note_relay_ok).
    if let Some(t) = targets.as_ref() {
        crate::inbox_relays::teardown_gift_wrap_targets(client, t).await;
    }
    let why = crate::transport::blocked_reason()
        .or_else(|| unknown.clone())
        .or_else(|| built.is_none().then(|| last_error.clone()).flatten())
        .unwrap_or_else(|| "No relay accepted the message.".to_string());
    fail_pending(&callback, receiver_npub, pending_id, &why).await;
    if let Some(entry) = confirm.as_ref() {
        entry.loop_exited.store(true, Ordering::SeqCst);
        // An OK that landed between the last attempt and loop_exited going
        // up would see loop_exited=false and skip its rescue — catch it here.
        if entry.confirmed.load(Ordering::SeqCst)
            && !entry.rescued.swap(true, Ordering::SeqCst)
        {
            rescue_failed_as_sent(entry).await;
            remove_wrap_confirm(&entry.wrap_id);
            return Ok(SendResult {
                pending_id: pending_id.to_string(),
                event_id: Some(event_id.to_string()),
                chat_id: receiver_npub.to_string(),
            });
        }
    }
    match last_error {
        Some(e) => Err(format!("Failed to send DM after {} attempts: {}", max_attempts, e)),
        None => Err(format!(
            "Failed to send DM after {} attempts (no relays accepted the gift-wrap)",
            max_attempts
        )),
    }
}

/// Whether any targeted relay holds `wrap`. One that serves gift wraps only to their
/// recipient can't say, so silence here is no verdict.
async fn wrap_on_relays(
    client: &Client,
    wrap: &Event,
    receiver: &PublicKey,
    targets: &crate::inbox_relays::GiftWrapTargets,
) -> bool {
    use futures_util::stream::{FuturesUnordered, StreamExt};
    let filter = Filter::new().id(wrap.id).kind(Kind::GiftWrap).pubkey(*receiver);
    let budget = crate::relay_request_timeout(std::time::Duration::from_secs(8));
    let mut checks: FuturesUnordered<_> = targets
        .resolved
        .iter()
        .map(|(url, _)| crate::community::transport::fetch_relay_eose_filters(client, url.as_str(), vec![filter.clone()], budget))
        .collect();
    while let Some(found) = checks.next().await {
        if found.is_ok_and(|events| events.iter().any(|e| e.id == wrap.id)) {
            return true;
        }
    }
    false
}

/// Success epilogue shared by every confirmed path in the retry loop:
/// finalize the pending message, notify, persist, fire the self-send.
#[allow(clippy::too_many_arguments)]
async fn finalize_gift_wrap_sent(
    client: &Client,
    my_pk: PublicKey,
    receiver_npub: &str,
    pending_id: &str,
    event_id: &str,
    rumor: &UnsignedEvent,
    config: &SendConfig,
    callback: &Arc<dyn SendCallback>,
    confirm: &Arc<WrapConfirm>,
    targets: &crate::inbox_relays::GiftWrapTargets,
) -> SendResult {
    remove_wrap_confirm(&confirm.wrap_id);
    crate::inbox_relays::teardown_gift_wrap_targets(client, targets).await;

    let finalized = {
        let mut state = STATE.lock().await;
        state.finalize_pending_message(receiver_npub, pending_id, event_id)
    };
    if let Some((_old_id, ref finalized_msg)) = finalized {
        callback.on_sent(receiver_npub, pending_id, finalized_msg);
        callback.on_persist(receiver_npub, finalized_msg);
    }

    // Delivery confirmed — drop the retained resend body (the key row stays for
    // NIP-09). Steady-state, only genuinely-unsent messages carry a body.
    if let Some(rid) = rumor.id {
        let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
    }

    if config.self_send {
        spawn_self_send(client.clone(), my_pk, rumor.clone());
    }
    crate::push::after_delivery(receiver_npub, rumor);

    SendResult {
        pending_id: pending_id.to_string(),
        event_id: Some(event_id.to_string()),
        chat_id: receiver_npub.to_string(),
    }
}

// ============================================================================
// send_dm — Text DMs
// ============================================================================

/// Send a NIP-17 gift-wrapped text DM.
///
/// Flow: pending msg → callback.on_pending → build Kind 14 rumor →
/// gift-wrap with retry → finalize → callback.on_sent → optional self-send.
/// Our pending message into its chat. A send answers a DM request, so the pictures and
/// wallpaper held while it waited come down now.
async fn add_pending(receiver_npub: &str, msg: &Message) {
    let answered = {
        let mut state = STATE.lock().await;
        let unanswered = crate::requests::shielded() && state.dm_unanswered(receiver_npub);
        state.add_message_to_participant(receiver_npub, msg);
        unanswered
    };
    if answered {
        let npub = receiver_npub.to_string();
        crate::db::spawn_bound(async move { crate::wallpaper::release_held(&npub).await });
        crate::profile::sync::queue_profile_sync(receiver_npub.to_string(), crate::profile::sync::SyncPriority::Critical, true);
    }
}

pub async fn send_dm(
    receiver_npub: &str,
    content: &str,
    reply_to: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;
    let my_pk = my_public_key().ok_or("Public key not set")?;

    // device-clock: a local id, never compared with a time.
    let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
    // Stamped by the corrected clock, so a fast device never dates a message ahead of everyone.
    let now = std::time::Duration::from_millis(crate::clock::now_ms());

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    let (plain, text_spans) = crate::text_spans::extract_own(content);
    let content = plain.as_str();

    // NIP-30: resolve any `:shortcode:` in the outbound text against the
    // user's subscribed packs so the rumor carries `["emoji", ...]` tags.
    // Recipients without the pack subscribed still render correctly, and
    // our own-view echo populates `emoji_tags` for the renderer.
    let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(content);

    // Build pending message and add to state
    let mut msg = Message {
        id: pending_id.clone(),
        content: content.to_string(),
        replied_to: reply_to.unwrap_or("").to_string(),
        at: now.as_millis() as u64,
        pending: true,
        mine: true,
        npub: my_pk.to_bech32().ok(),
        emoji_tags: emoji_tags.clone(),
        text_spans: text_spans.clone(),
        expiration: config.expiration,
        ..Default::default()
    };
    // The quote rides the message itself: the parent may be nowhere in the UI's memory.
    let _ = crate::db::events::populate_reply_context(&mut msg).await;

    add_pending(receiver_npub, &msg).await;

    callback.on_pending(receiver_npub, &msg);

    // Build the rumor
    let milliseconds = now.as_millis() % 1000;
    // NIP-17 rumor: kind 14 + recipient p-tag (upstream's `make_rumor` is private).
    let mut rumor = EventBuilder::new(Kind::PrivateDirectMessage, content)
        .custom_created_at(Timestamp::from_secs(now.as_secs()))
        .tag(Tag::public_key(receiver));

    if let Some(reply_id) = reply_to {
        if !reply_id.is_empty() {
            rumor = rumor.tag(Tag::custom(
                "e",
                [reply_id.to_string(), String::new(), "reply".to_string()],
            ));
        }
    }

    let mut rumor = rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
    for et in &emoji_tags {
        rumor = rumor.tag(Tag::custom(
            "emoji",
            [et.shortcode.clone(), et.url.clone()],
        ));
    }
    rumor = rumor.tags(crate::text_spans::to_nostr_tags(&text_spans));
    // NIP-40 self-destruct: stamp the rumor so compliant receivers honor the
    // expiry; retry_send_gift_wrap mirrors it onto the outer wrap for relays.
    if let Some(exp) = config.expiration {
        rumor = rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
    }
    let built_rumor = rumor.finalize_unsigned_with_id(my_pk);
    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();

    // Send via gift-wrap with retry
    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, &pending_id,
        built_rumor, &event_id, config, callback, None,
    ).await
}

// ============================================================================
// send_rumor_dm — Pre-built rumor (custom events)
// ============================================================================

/// Send a pre-built rumor via NIP-17 gift-wrap.
///
/// Used when the caller has already built the rumor. Skips encryption/upload.
pub async fn send_rumor_dm(
    receiver_npub: &str,
    pending_id: &str,
    rumor: UnsignedEvent,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    let event_id = rumor.id.ok_or("Rumor has no id")?.to_hex();

    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, pending_id,
        rumor, &event_id, config, callback, None,
    ).await
}

/// Manually retry a failed DM by republishing the EXACT retained recipient
/// wrap. Same outer event id → relays no-op the duplicate, so a first send
/// that silently landed can never double-post, regardless of the recipient's
/// client.
///
/// `Ok(true)`  — a retained wrap was found and the resend went through the
///               normal retry loop (message ends sent, or red again ready to
///               retry). The caller must NOT fall back.
/// `Ok(false)` — nothing retained (old/pruned message, or the first send
///               failed before a wrap was ever built, e.g. an upload error).
///               The caller falls back to a fresh send — safe, since no wrap
///               reached a relay in that case.
pub async fn resend_failed_dm(
    receiver_npub: &str,
    failed_msg_id: &str,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<bool, String> {
    // Guard the read→flip→republish against a mid-tap account swap: the payload
    // is this account's; a swap before the STATE flip must abort (returning
    // "handled" so the caller never falls back to a fresh send in the WRONG
    // account). retry_send_gift_wrap re-guards its own STATE/DB writes.
    let payload = match crate::db::nip17_keys::get_resend_payload_by_pending(failed_msg_id)? {
        Some(p) => p,
        None => return Ok(false),
    };
    let client = nostr_client().ok_or("Not logged in")?;
    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    // Flip the red row back to "sending"; the retry loop's own fail/finalize
    // path returns it to red or promotes it to sent.
    let repending = {
        let mut state = STATE.lock().await;
        state.update_message(failed_msg_id, |msg| {
            msg.set_failed(false);
            msg.set_pending(true);
        })
    };
    if let Some((_chat_id, ref msg)) = repending {
        callback.on_pending(receiver_npub, msg);
    }

    let event_id = payload.rumor.id.ok_or("Retained rumor has no id")?.to_hex();
    let built = crate::inbox_relays::BuiltGiftWrap {
        event: payload.wrap_event,
        secret: payload.secret,
    };
    // Inject the retained wrap: the loop republishes these exact bytes.
    if let Err(e) = retry_send_gift_wrap(
        &client, &receiver, receiver_npub, failed_msg_id,
        payload.rumor, &event_id, config, callback, Some(built),
    )
    .await
    {
        // The resend was attempted — the loop already marked the row red again.
        // Still "handled": the caller must not fall back to a fresh wrap, or the
        // retained wrap that may yet be sitting on a relay would double-post.
        crate::log_warn!("[Send] idempotent resend of {} did not land: {}", failed_msg_id, e);
    }
    Ok(true)
}

// ============================================================================
// send_file_dm — File Attachment DMs
// ============================================================================

/// Send a NIP-17 gift-wrapped file attachment DM.
///
/// Flow: hash → save locally → pending → encrypt → upload → build Kind 15 rumor → gift-wrap + send.
#[allow(clippy::too_many_arguments)]
pub async fn send_file_dm(
    receiver_npub: &str,
    file_bytes: Arc<Vec<u8>>,
    filename: &str,
    extension: &str,
    content: Option<&str>,
    reply_to: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    send_file_dm_with_meta(receiver_npub, file_bytes, filename, extension, None, content, reply_to, config, callback).await
}

/// [`send_file_dm`] for a caller that already holds the image's preview metadata,
/// sparing a second full decode before the bubble can appear. `None` derives it.
#[allow(clippy::too_many_arguments)]
pub async fn send_file_dm_with_meta(
    receiver_npub: &str,
    file_bytes: Arc<Vec<u8>>,
    filename: &str,
    extension: &str,
    img_meta: Option<crate::types::ImageMetadata>,
    content: Option<&str>,
    reply_to: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    send_file_dm_from(receiver_npub, FileSource::Bytes(file_bytes), filename, extension, img_meta, content, reply_to, config, callback).await
}

/// Where an outgoing file's bytes come from.
pub enum FileSource {
    /// In memory: images the caller has already processed, pasted bytes.
    Bytes(Arc<Vec<u8>>),
    /// On disk, read a chunk at a time: a file of any size costs one chunk of memory.
    /// Its preview metadata is the caller's to give; nothing here decodes it.
    Path(std::path::PathBuf),
    /// A copy this app already saved in the download folder (a failed send's, retried):
    /// sent from where it is, since copying it again would only leave a duplicate.
    Saved(std::path::PathBuf),
    /// Our own ciphertext of an upload that failed, kept to go again as it is: the same blob,
    /// under the key and nonce it was sealed with.
    Sealed { path: std::path::PathBuf, hash: String, key: String, nonce: String, blob_sha256: String },
}

/// Removes a file when dropped: the ciphertext of an upload that ended either way.
pub struct TempFile(std::path::PathBuf);

impl Drop for TempFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

impl TempFile {
    /// Keep the file after all: a failed upload's ciphertext, for its retry.
    pub fn keep(self) -> std::path::PathBuf {
        let path = self.0.clone();
        std::mem::forget(self);
        path
    }
}

/// Where a send's ciphertext waits for its upload, and a failed one for its retry.
#[cfg(not(target_arch = "wasm32"))]
fn outgoing_dir() -> std::path::PathBuf {
    crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_else(|_| std::env::temp_dir())
}

/// A failed upload's ciphertext, kept for its retry: written out when it was sealed in memory.
#[cfg(not(target_arch = "wasm32"))]
pub fn keep_for_retry(body: &crate::blossom::UploadBody, guard: Option<TempFile>, hash: &str, key: &str, nonce: &str, pending_id: &str, mime: &str) {
    let path = match (body, guard) {
        (crate::blossom::UploadBody::File { .. }, Some(guard)) => guard.keep(),
        (crate::blossom::UploadBody::Memory(data), _) => {
            let dir = outgoing_dir();
            let _ = std::fs::create_dir_all(&dir);
            let path = dir.join(format!("{hash}-{pending_id}.enc"));
            if std::fs::write(&path, &***data).is_err() {
                return;
            }
            path
        }
        _ => return,
    };
    crate::media::pending::sealed(crate::simd::hex::hex_to_bytes_32(hash), path, key, nonce, mime);
}

/// What a failed send of `att` can go again from, best first: the sender's own file, the
/// bytes this account still holds, or the ciphertext its failed upload kept.
#[cfg(not(target_arch = "wasm32"))]
pub fn retry_source(att: &Attachment) -> Option<FileSource> {
    let hash = crate::simd::hex::hex_to_bytes_32_checked(&att.id)?;
    if let Some(path) = crate::media::pending::plain_path(&hash) {
        return Some(FileSource::Path(path));
    }
    if crate::media::ram::cache().contains(&hash) || crate::media::store::holds(&hash) {
        let src = crate::media::open(&hash)?;
        return crate::media::read_all(&*src).ok().map(|bytes| FileSource::Bytes(Arc::new(bytes)));
    }
    let prefix = format!("{}-", att.id);
    let kept = std::fs::read_dir(outgoing_dir())
        .ok()?
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix) && e.file_name().to_string_lossy().ends_with(".enc"))
        .max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())?;
    let (blob_sha256, _) = crypto::stream::hash_file(&kept.path()).ok()?;
    Some(FileSource::Sealed { path: kept.path(), hash: att.id.clone(), key: att.key.clone(), nonce: att.nonce.clone(), blob_sha256 })
}

/// Give up on a failed send for good. Its uploads leave the media servers only once nothing
/// signed can still be read with them: no message was ever built, or its take-back is on a
/// relay. A message that failed here may have landed, or may land yet, and would point at them.
pub async fn abandon_failed_send(chat_id: &str, message_id: &str, attachments: &[Attachment]) {
    let in_community = matches!(crate::db::community::community_id_for_channel(chat_id), Ok(Some(_)));
    let unread = if in_community {
        crate::community::v2::service::discard_unconfirmed(chat_id, message_id).await
    } else {
        match crate::db::nip17_keys::get_resend_payload_by_pending(message_id) {
            Ok(None) => true,
            Ok(Some(wrapped)) => match (wrapped.rumor.id, PublicKey::from_bech32(chat_id)) {
                (Some(rumor_id), Ok(recipient)) => crate::deletion::take_back_failed_dm(&rumor_id, &recipient).await,
                _ => false,
            },
            Err(_) => false,
        }
    };
    if !unread {
        return;
    }
    let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
    let urls = crate::db::attachments::urls_unreferenced_elsewhere(&urls, message_id).unwrap_or_default();
    if urls.is_empty() {
        return;
    }
    if let Ok(signer) = crate::signer::active_signer() {
        crate::blossom::delete_blobs_best_effort(signer, urls);
    }
}

/// Forget what a failed send of `att` kept to go again: its sealed copies and its bubble's source.
#[cfg(not(target_arch = "wasm32"))]
pub fn discard_retry_copy(att: &Attachment) {
    let Some(hash) = crate::simd::hex::hex_to_bytes_32_checked(&att.id) else { return };
    crate::media::pending::forget(&hash);
    let prefix = format!("{}-", att.id);
    if let Ok(entries) = std::fs::read_dir(outgoing_dir()) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with(&prefix) && name.ends_with(".enc") {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
}

/// Ciphertext of uploads that never went again, once it's two weeks old, and plaintext working
/// copies a send left behind, once they're a day old.
#[cfg(not(target_arch = "wasm32"))]
pub fn sweep_outgoing() {
    let dir = outgoing_dir();
    sweep_older_than(&dir, std::time::Duration::from_secs(14 * 24 * 3600));
    sweep_older_than(&dir.join("work"), std::time::Duration::from_secs(24 * 3600));
}

#[cfg(not(target_arch = "wasm32"))]
fn sweep_older_than(dir: &std::path::Path, max_age: std::time::Duration) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    for entry in entries.flatten() {
        let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
        if old {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// An outgoing attachment, ready for the upload.
pub enum Sealed {
    /// A live blob of these bytes already exists: the message just names it.
    Reused(crate::db::attachments::ReusableUpload),
    /// Freshly sealed. A disk body's ciphertext goes when the guard drops.
    Body(crate::blossom::UploadBody, Option<TempFile>),
}

/// Reuse a live blob of the plaintext `hash`, or seal `plain` under `key`/`nonce`,
/// reporting each stage against `pending_id`. A file seals file to file, costing no memory.
pub async fn seal_or_reuse(
    plain: FileSource,
    hash: &str,
    key: &str,
    nonce: &str,
    pending_id: &str,
    callback: Arc<dyn SendCallback>,
    cancel: Option<Arc<AtomicBool>>,
) -> Result<Sealed, String> {
    // Every verified send or download of these bytes left url+key+nonce behind. Liveness
    // is proven, never assumed: a dead or unreachable blob falls through to a fresh upload.
    if let Ok(Some(r)) = crate::db::attachments::find_reusable_by_hash(hash) {
        if crate::blossom::blob_is_served(&r.url, std::time::Duration::from_secs(5)).await {
            crate::log_info!("[SmartForward] {} reused ({}, {} KB) — no upload", &hash[..8.min(hash.len())], if r.mine { "own blob" } else { "foreign blob, mirroring in background" }, r.size / 1024);
            return Ok(Sealed::Reused(r));
        }
    }

    let (key, nonce) = (key.to_string(), nonce.to_string());
    // Resolved here, on the task that carries the account, not on a blocking thread.
    #[cfg(not(target_arch = "wasm32"))]
    let outgoing = outgoing_dir();
    // The web never seals from a file; wasm has no temp dir to fall back on.
    #[cfg(target_arch = "wasm32")]
    let outgoing = crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_default();
    // Only a streamed seal can count its progress; bytes in hand are sealed in one go.
    callback.on_upload_stage(pending_id, "encrypting", matches!(plain, FileSource::Path(_) | FileSource::Saved(_)).then_some(0));
    let sealed = match plain {
        FileSource::Bytes(bytes) => {
            let sealed = crate::rt::spawn_blocking(move || {
                crypto::encrypt_data(&bytes, &crypto::EncryptionParams { key, nonce })
            })
            .await
            .map_err(|e| format!("Encryption failed: {}", e))??;
            Sealed::Body(crate::blossom::UploadBody::Memory(Arc::new(sealed)), None)
        }
        FileSource::Sealed { path, blob_sha256, .. } => {
            let len = std::fs::metadata(&path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
            Sealed::Body(crate::blossom::UploadBody::file(path.clone(), len, &blob_sha256)?, Some(TempFile(path)))
        }
        FileSource::Path(path) | FileSource::Saved(path) => {
            let _ = std::fs::create_dir_all(&outgoing);
            let out = outgoing.join(format!("{}-{}.enc", hash, pending_id));
            let guard = TempFile(out.clone());
            let target = out.clone();
            let (stage_cb, pid, plain_hash) = (callback.clone(), pending_id.to_string(), hash.to_string());
            // Sealed from the sender's own file, so it must still be the bytes that were hashed.
            let (sealed_hash, len) = crate::rt::spawn_blocking(move || {
                crypto::stream::encrypt_file_matching(&path, &target, &key, &nonce, &plain_hash, &mut |pct| {
                    stage_cb.on_upload_stage(&pid, "encrypting", Some(pct));
                    // A cancel lands here, not after the whole file is sealed.
                    !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed))
                })
            })
            .await
            .map_err(|e| format!("Encryption failed: {}", e))??;
            Sealed::Body(crate::blossom::UploadBody::file(out, len, &sealed_hash)?, Some(guard))
        }
    };
    callback.on_upload_stage(pending_id, "starting", None);
    Ok(sealed)
}

/// Mark a pending message failed (in state, in the UI, on disk), saying why.
async fn fail_pending(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, why: &str) {
    let failed_msg = {
        let mut state = STATE.lock().await;
        state.update_message(pending_id, |msg| {
            msg.set_failed(true);
            msg.set_pending(false);
        })
    };
    if let Some((_chat_id, ref msg)) = failed_msg {
        callback.on_failed_reason(receiver_npub, pending_id, why);
        callback.on_failed(receiver_npub, pending_id, msg);
        callback.on_persist(receiver_npub, msg);
    }
}

/// The first line of a failure, as a row can show it: a list of per-server reasons is
/// summed up by its heading.
pub fn failure_line(err: &str) -> String {
    let line = err.trim().trim_start_matches("Upload failed:").trim().lines().next().unwrap_or_default().trim();
    match line.strip_suffix(':') {
        Some(head) => format!("{head}."),
        None => line.to_string(),
    }
}

/// Mark a pending file message failed (in state, in the UI, on disk) and hand back `err`.
/// Keep a sent blob in the store: the file moves in, bytes in hand are written there.
#[cfg(not(target_arch = "wasm32"))]
pub fn keep_sent(body: &crate::blossom::UploadBody, hash: &str, key: &str, nonce: &str, pt_len: u64, mime: &str) -> bool {
    use crate::media::store::{keep_bytes, keep_file, Keep};
    let keep = |blob_sha256: String| Keep {
        hash: crate::simd::hex::hex_to_bytes_32(hash), key: key.to_string(), nonce: nonce.to_string(),
        blob_sha256, pt_len, mime: mime.to_string(), origin: crate::db::media_store::Origin::Sent,
    };
    let kept = match body {
        crate::blossom::UploadBody::Memory(data) => keep_bytes(data, keep(crypto::sha256_hex(data))),
        crate::blossom::UploadBody::File { path, sha256, .. } => keep_file(path, keep(sha256.to_string())),
    };
    kept.inspect_err(|e| crate::log_warn!("[Send] sent, but couldn't keep it: {e}")).is_ok()
}

async fn mark_send_failed(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, err: String) -> String {
    fail_pending(callback, receiver_npub, pending_id, &failure_line(&err)).await;
    err
}

/// [`send_file_dm_with_meta`] from either source.
#[allow(clippy::too_many_arguments)]
pub async fn send_file_dm_from(
    receiver_npub: &str,
    source: FileSource,
    filename: &str,
    extension: &str,
    img_meta: Option<crate::types::ImageMetadata>,
    content: Option<&str>,
    reply_to: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;
    let my_pk = my_public_key().ok_or("Public key not set")?;
    let reply_to = reply_to.filter(|r| !r.is_empty());
    // Sign the Blossom auth event via the active client signer so bunker
    // accounts route through NostrConnect (the user's identity key lives on
    // the remote signer; MY_SECRET_KEY only holds the NIP-46 client key).
    let signer = crate::signer::active_signer()
        .map_err(|e| format!("Signer unavailable: {}", e))?;

    // device-clock: a local id, never compared with a time.
    let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
    let now = std::time::Duration::from_millis(crate::clock::now_ms());
    let milliseconds = now.as_millis() % 1000;

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    let mime_type = crypto::mime_from_extension(extension);

    // The web sends from memory only, and its bubble shows the bytes in hand.
    #[cfg(target_arch = "wasm32")]
    let (file_hash, local_path_str, img_meta, plain_len) = {
        let FileSource::Bytes(bytes) = &source else {
            return Err("Vector Web sends files from memory".into());
        };
        let file_hash = crypto::sha256_hex(bytes);
        let _ = crate::media::ram::insert(crate::simd::hex::hex_to_bytes_32(&file_hash), bytes.to_vec(), mime_type);
        let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(bytes));
        (file_hash, String::new(), img_meta, bytes.len() as u64)
    };
    // Hash and (if not given) read the preview metadata off the runtime: each is a full
    // pass over the bytes, and a runtime worker parked on one stalls every task queued
    // behind it. Nothing is copied: the bubble reads the sender's own bytes.
    #[cfg(not(target_arch = "wasm32"))]
    let (file_hash, local_path_str, img_meta, plain_len) = {
        let (file_hash, img_meta, plain_len) = match &source {
            FileSource::Bytes(bytes) => {
                let bytes = Arc::clone(bytes);
                crate::rt::spawn_blocking(move || {
                    let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(&bytes));
                    (crypto::sha256_hex(&bytes), img_meta, bytes.len() as u64)
                })
                .await
                .map_err(|e| format!("Attachment prep failed: {}", e))?
            }
            FileSource::Path(path) | FileSource::Saved(path) => {
                let path = path.clone();
                let (hash, len) = crate::rt::spawn_blocking(move || crypto::stream::hash_file(&path))
                    .await
                    .map_err(|e| format!("Attachment prep failed: {}", e))??;
                (hash, img_meta, len)
            }
            FileSource::Sealed { path, hash, .. } => {
                let len = std::fs::metadata(path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
                (hash.clone(), img_meta, len.saturating_sub(16))
            }
        };
        let hash = crate::simd::hex::hex_to_bytes_32(&file_hash);
        match &source {
            FileSource::Bytes(bytes) => {
                let _ = crate::media::ram::insert(hash, bytes.to_vec(), mime_type);
            }
            FileSource::Path(path) | FileSource::Saved(path) => crate::media::pending::plain(hash, path.clone(), mime_type),
            FileSource::Sealed { path, key, nonce, .. } => crate::media::pending::sealed(hash, path.clone(), key, nonce, mime_type),
        }
        (file_hash, String::new(), img_meta, plain_len)
    };

    // WebXDC Mini Apps: mint the realtime-channel topic at send time and carry
    // it on the rumor — locally-derived topics are asymmetric in DMs (each
    // side's chat_id is the other party's npub), splitting players onto
    // disjoint gossip topics.
    let webxdc_topic = (extension.eq_ignore_ascii_case("xdc"))
        .then(|| crate::webxdc::mint_topic_id(&file_hash, &my_pk.to_hex()));

    // The bubble goes up now, on fresh encryption parameters (a kept seal brings its own);
    // a reused blob swaps in its own below. AES-GCM appends a 16-byte tag, so the size is
    // known unencrypted.
    let params = match &source {
        FileSource::Sealed { key, nonce, .. } => crypto::EncryptionParams { key: key.clone(), nonce: nonce.clone() },
        _ => crypto::generate_encryption_params(),
    };
    let attachment = Attachment {
        id: file_hash.clone(), key: params.key.clone(), nonce: params.nonce.clone(),
        extension: extension.to_string(), name: filename.to_string(),
        url: String::new(), path: local_path_str.clone(), size: plain_len + 16,
        // No copy of its own: the bubble reads the sender's bytes until the send ends.
        img_meta: img_meta.clone(), downloading: false, downloaded: false, verified: true,
        resident: crate::media::resident(&crate::simd::hex::hex_to_bytes_32(&file_hash)),
        webxdc_topic: webxdc_topic.clone(),
        ..Default::default()
    };
    let mut msg = Message {
        id: pending_id.clone(), content: content.unwrap_or("").to_string(),
        replied_to: reply_to.unwrap_or("").to_string(),
        at: now.as_millis() as u64, pending: true, mine: true,
        npub: my_pk.to_bech32().ok(), attachments: vec![attachment.clone()],
        // A lifespan is stamped after the upload; the bubble shows no clock until then.
        expiration: if config.self_destruct_secs.is_some() { None } else { config.expiration },
        ..Default::default()
    };
    let _ = crate::db::events::populate_reply_context(&mut msg).await;
    add_pending(receiver_npub, &msg).await;
    callback.on_pending(receiver_npub, &msg);
    let cancel = config.cancel_token.clone().or_else(|| callback.cancel_token(&pending_id));

    // Encrypt and upload, or reference a live blob of the same bytes and skip both.
    let plain = source;
    let sealed = match seal_or_reuse(plain, &file_hash, &params.key, &params.nonce, &pending_id, callback.clone(), cancel.clone()).await {
        Ok(sealed) => sealed,
        // The bubble is up: a seal that fails (or is cancelled) must say so, not stay pending.
        Err(e) => return Err(mark_send_failed(&callback, receiver_npub, &pending_id, e).await),
    };
    // Held to the end of the send, so the ciphertext goes however it ends, unless a failed
    // upload keeps it for the retry.
    #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
    let (reused, encrypted, ciphertext_file) = match sealed {
        Sealed::Reused(r) => (Some(r), None, None),
        Sealed::Body(body, guard) => (None, Some(body), guard),
    };
    let (att_key, att_nonce, att_url, encrypted_size) = match (&reused, &encrypted) {
        (Some(r), _) => {
            let adopted = crate::compact::CompactAttachment::from_attachment(&Attachment {
                key: r.key.clone(), nonce: r.nonce.clone(), url: r.url.clone(), size: r.size,
                ..attachment.clone()
            });
            let mut state = STATE.lock().await;
            state.update_message(&pending_id, |msg| {
                if let Some(att) = msg.attachments.last_mut() {
                    *att = adopted.clone();
                }
            });
            (r.key.clone(), r.nonce.clone(), r.url.clone(), r.size)
        }
        (None, body) => (params.key.clone(), params.nonce.clone(), String::new(), body.as_ref().map_or(0, |b| b.len())),
    };

    // Upload to Blossom — bridge SendCallback.on_upload_progress to Blossom ProgressCallback
    let servers = crate::state::get_blossom_servers();
    let cb_for_progress = callback.clone();
    let pid_for_progress = pending_id.clone();
    let progress_cb: crate::blossom::ProgressCallback = Arc::new(move |percentage, bytes| {
        cb_for_progress.on_upload_progress(
            &pid_for_progress,
            percentage.unwrap_or(0),
            bytes.unwrap_or(0),
        )
    });

    // Send the original MIME even though bytes are ciphertext: many
    // Blossom servers reject `application/octet-stream` but accept the
    // same bytes under their original type.
    let (upload_url, mirror_urls) = match encrypted {
        // Reuse: the attachment already points at a live blob. No upload, no
        // fan-out — the send is just the message.
        None => {
            callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &att_url);
            // A FOREIGN blob's lifetime belongs to its uploader; mirror it to
            // our servers in the background as availability insurance. Never
            // blocks or delays the send — best-effort by design.
            if reused.as_ref().is_some_and(|r| !r.mine) {
                let signer_bg = signer.clone();
                let url_bg = att_url.clone();
                crate::db::spawn_bound(async move {
                    let _ = crate::blossom::mirror_blob_to_servers(
                        signer_bg, &url_bg, crate::state::get_blossom_servers(),
                        1, std::time::Duration::from_secs(8), &[],
                    ).await;
                });
            }
            (att_url.clone(), Vec::new())
        }
        Some(encrypted) => {
            #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
            let body = encrypted.clone();
            let accepted = match crate::blossom::upload_body_with_progress_and_failover(
                signer.clone(), servers, encrypted, Some(mime_type),
                /* is_encrypted */ true,
                progress_cb, Some(config.upload_retries), Some(config.upload_retry_delay),
                cancel.clone(),
            ).await {
                Ok(accepted) => accepted,
                Err(e) => {
                    #[cfg(not(target_arch = "wasm32"))]
                    if !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
                        keep_for_retry(&body, ciphertext_file, &file_hash, &att_key, &att_nonce, &pending_id, mime_type);
                    }
                    return Err(mark_send_failed(&callback, receiver_npub, &pending_id, format!("Upload failed: {}", e)).await);
                }
            };
            // The account keeps media: the blob just uploaded is the copy it keeps.
            #[cfg(not(target_arch = "wasm32"))]
            if crate::media::keep_media() && keep_sent(&body, &file_hash, &att_key, &att_nonce, plain_len, mime_type) {
                let mut state = STATE.lock().await;
                state.update_message(&pending_id, |msg| {
                    if let Some(att) = msg.attachments.last_mut() {
                        att.set_downloaded(true);
                    }
                });
            }

            let upload_url = accepted.url.clone();
            {
                let mut state = STATE.lock().await;
                state.update_message(&pending_id, |msg| {
                    if let Some(att) = msg.attachments.last_mut() {
                        att.url = upload_url.clone().into_boxed_str();
                    }
                });
            }
            callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &upload_url);

            // BUD-04 mirror fan-out: bounded, best-effort. Verified mirrors ride the
            // rumor as NIP-17 `fallback` tags so the message survives its primary
            // host dying later; zero mirrors never delays or fails the send.
            let mirror_urls = crate::blossom::mirror_blob_to_servers(
                signer.clone(),
                &upload_url,
                crate::state::get_blossom_servers(),
                2,
                std::time::Duration::from_secs(5),
                std::slice::from_ref(&accepted.server),
            ).await;
            if !mirror_urls.is_empty() {
                let mut state = STATE.lock().await;
                state.update_message(&pending_id, |msg| {
                    if let Some(att) = msg.attachments.last_mut() {
                        att.set_fallback_urls(mirror_urls.iter().map(|s| s.as_str().into()));
                    }
                });
            }
            (upload_url, mirror_urls)
        }
    };

    // A cancel during the mirror fan-out or the publish must not deliver: the
    // bubble is already gone on the sender's side.
    if cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
        return Err("Upload cancelled".to_string());
    }

    // Build Kind 15
    let mut file_rumor = EventBuilder::new(Kind::from_u16(15), &upload_url)
        .custom_created_at(Timestamp::from_secs(now.as_secs()))
        .tag(Tag::public_key(receiver))
        .tag(Tag::custom("file-type", [mime_type]))
        .tag(Tag::custom("size", [encrypted_size.to_string()]))
        .tag(Tag::custom("encryption-algorithm", ["aes-gcm"]))
        .tag(Tag::custom("decryption-key", [att_key.as_str()]))
        .tag(Tag::custom("decryption-nonce", [att_nonce.as_str()]))
        .tag(Tag::custom("ox", [file_hash.clone()]));
    if let Some(reply_id) = reply_to {
        file_rumor = file_rumor.tag(Tag::custom(
            "e",
            [reply_id.to_string(), String::new(), "reply".to_string()],
        ));
    }
    for fb in &mirror_urls {
        file_rumor = file_rumor.tag(Tag::custom("fallback", [fb.as_str()]));
    }
    if !filename.is_empty() {
        file_rumor = file_rumor.tag(Tag::custom("name", [filename]));
    }
    if let Some(ref topic) = webxdc_topic {
        file_rumor = file_rumor.tag(Tag::custom("webxdc-topic", [topic.as_str()]));
    }
    // Include image preview metadata for compatible rendering across all clients
    if let Some(ref meta) = img_meta {
        if !meta.thumbhash.is_empty() {
            // `thumbhash` names the value accurately; receivers read `thumb` too
            // (legacy), so this stays backward-compatible in both directions.
            file_rumor = file_rumor.tag(Tag::custom("thumbhash", [meta.thumbhash.as_str()]));
        }
        file_rumor = file_rumor.tag(Tag::custom("dim", [format!("{}x{}", meta.width, meta.height)]));
    }
    file_rumor = file_rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
    // The self-destruct clock starts at publish: resolve the lifespan now that the
    // upload is done, and put the same stamp on the sender's own bubble.
    let expiration = config
        .self_destruct_secs
        .and_then(crate::self_destruct::expiry_after)
        .or(config.expiration);
    if let Some(exp) = expiration {
        file_rumor = file_rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
        let mut state = STATE.lock().await;
        state.update_message(&pending_id, |msg| { msg.expiration_secs = exp as u32; });
    }

    let built_rumor = file_rumor.finalize_unsigned_with_id(my_pk);
    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();

    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, &pending_id,
        built_rumor, &event_id, config, callback, None,
    ).await
}

// ============================================================================
// Tests
// ============================================================================

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

    #[derive(Debug, Clone, PartialEq)]
    enum CbEvent {
        Pending(String),
        UploadProgress(String, u8, u64),
        UploadComplete(String, String),
        Sent(String, String),
        Failed(String, String),
        Persist(String),
    }

    struct MockCallback {
        events: Mutex<Vec<CbEvent>>,
        cancel_at: Option<u8>,
    }

    impl MockCallback {
        fn new() -> Self { Self { events: Mutex::new(vec![]), cancel_at: None } }
        fn with_cancel(pct: u8) -> Self { Self { events: Mutex::new(vec![]), cancel_at: Some(pct) } }
        fn events(&self) -> Vec<CbEvent> { self.events.lock().unwrap().clone() }
    }

    impl SendCallback for MockCallback {
        fn on_pending(&self, cid: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Pending(cid.into()));
        }
        fn on_upload_progress(&self, pid: &str, pct: u8, bytes: u64) -> Result<(), String> {
            self.events.lock().unwrap().push(CbEvent::UploadProgress(pid.into(), pct, bytes));
            if self.cancel_at.map_or(false, |c| pct >= c) { return Err("Cancelled".into()); }
            Ok(())
        }
        fn on_upload_complete(&self, cid: &str, _: &str, _: &str, url: &str) {
            self.events.lock().unwrap().push(CbEvent::UploadComplete(cid.into(), url.into()));
        }
        fn on_sent(&self, cid: &str, old: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Sent(cid.into(), old.into()));
        }
        fn on_failed(&self, cid: &str, old: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Failed(cid.into(), old.into()));
        }
        fn on_persist(&self, cid: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Persist(cid.into()));
        }
    }

    #[test]
    fn config_default() {
        let c = SendConfig::default();
        assert_eq!(c.max_send_attempts, 1);
        assert!(!c.self_send);
        assert!(c.cancel_token.is_none());
        assert_eq!(c.upload_retries, 3);
    }

    #[test]
    fn config_gui() {
        let c = SendConfig::gui();
        assert_eq!(c.max_send_attempts, 12);
        assert!(c.self_send);
    }

    #[test]
    fn config_headless() {
        let c = SendConfig::headless();
        assert_eq!(c.max_send_attempts, 3);
        assert!(c.self_send);
    }

    #[test]
    fn config_custom_override() {
        let c = SendConfig { max_send_attempts: 5, ..SendConfig::gui() };
        assert_eq!(c.max_send_attempts, 5);
        assert!(c.self_send);
    }

    #[test]
    fn noop_callback_all_methods() {
        let cb = NoOpSendCallback;
        let msg = Message::default();
        cb.on_pending("c", &msg);

        assert!(cb.on_upload_progress("p", 50, 1024).is_ok());
        cb.on_upload_complete("c", "p", "a", "url");
        cb.on_sent("c", "o", &msg);
        cb.on_failed("c", "o", &msg);
        cb.on_persist("c", &msg);
    }

    #[test]
    fn text_dm_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);
        cb.on_sent("r", "p-1", &msg);
        cb.on_persist("r", &msg);
        assert_eq!(cb.events(), vec![
            CbEvent::Pending("r".into()),
            CbEvent::Sent("r".into(), "p-1".into()),
            CbEvent::Persist("r".into()),
        ]);
    }

    #[test]
    fn file_dm_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 50, 5000).ok();
        cb.on_upload_progress("p", 100, 10000).ok();
        cb.on_upload_complete("r", "p", "h", "https://blossom/h");
        cb.on_sent("r", "p", &msg);
        cb.on_persist("r", &msg);
        let e = cb.events();
        assert_eq!(e.len(), 7);
        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.contains("blossom")));
    }

    #[test]
    fn failed_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);
        cb.on_failed("r", "p", &msg);
        cb.on_persist("r", &msg);
        assert_eq!(cb.events(), vec![
            CbEvent::Pending("r".into()),
            CbEvent::Failed("r".into(), "p".into()),
            CbEvent::Persist("r".into()),
        ]);
    }

    #[test]
    fn cancel_upload_at_threshold() {
        let cb = MockCallback::with_cancel(50);
        assert!(cb.on_upload_progress("p", 25, 512).is_ok());
        assert!(cb.on_upload_progress("p", 50, 1024).is_err());
        assert_eq!(cb.events().len(), 2);
    }

    #[test]
    fn cancel_triggers_failed() {
        let cb = MockCallback::with_cancel(30);
        let msg = Message::default();
        cb.on_pending("r", &msg);

        cb.on_upload_progress("p", 10, 1000).ok();
        assert!(cb.on_upload_progress("p", 30, 3000).is_err());
        cb.on_failed("r", "p", &msg);
        assert!(matches!(cb.events().last(), Some(CbEvent::Failed(..))));
    }

    #[test]
    fn send_result_serialize() {
        let r = SendResult { pending_id: "p".into(), event_id: Some("e".into()), chat_id: "c".into() };
        let j = serde_json::to_string(&r).unwrap();
        assert!(j.contains("\"pending_id\":\"p\""));
    }

    #[test]
    fn send_result_none_event() {
        let r = SendResult { pending_id: "p".into(), event_id: None, chat_id: "c".into() };
        let j = serde_json::to_string(&r).unwrap();
        assert!(j.contains("null"));
    }

    // ========================================================================
    // File DM callback sequences
    // ========================================================================

    #[test]
    fn file_dm_fresh_upload_full_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // 1. Pending message created
        cb.on_pending("npub1recv", &msg);
        // 2. Attachment preview added

        // 3. Upload progress (0% → 25% → 50% → 75% → 100%)
        cb.on_upload_progress("pending-42", 0, 0).unwrap();
        cb.on_upload_progress("pending-42", 25, 2500).unwrap();
        cb.on_upload_progress("pending-42", 50, 5000).unwrap();
        cb.on_upload_progress("pending-42", 75, 7500).unwrap();
        cb.on_upload_progress("pending-42", 100, 10000).unwrap();
        // 4. Upload complete
        cb.on_upload_complete("npub1recv", "pending-42", "deadbeef", "https://blossom.example/deadbeef");
        // 5. Gift-wrap sent successfully
        cb.on_sent("npub1recv", "pending-42", &msg);
        // 6. Persisted to DB
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 9);
        assert!(matches!(&e[0], CbEvent::Pending(c) if c == "npub1recv"));
        assert!(matches!(&e[1], CbEvent::UploadProgress(_, 0, 0)));
        assert!(matches!(&e[5], CbEvent::UploadProgress(_, 100, 10000)));
        assert!(matches!(&e[6], CbEvent::UploadComplete(_, url) if url.contains("deadbeef")));
        assert!(matches!(&e[7], CbEvent::Sent(..)));
        assert!(matches!(&e[8], CbEvent::Persist(..)));
    }

    #[test]
    fn file_dm_skip_upload_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Dedup hit: no upload, existing URL reused
        // 1. Pending message
        cb.on_pending("npub1recv", &msg);
        // 2. Attachment preview (with reused URL already set)

        // 3. Upload complete (immediate — URL was already known)
        cb.on_upload_complete("npub1recv", "pending-99", "existinghash", "https://blossom.example/existing");
        // 4. Gift-wrap sent
        cb.on_sent("npub1recv", "pending-99", &msg);
        // 5. Persisted
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 4);
        // No UploadProgress events — upload was skipped
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadProgress(..))));
        assert!(matches!(&e[1], CbEvent::UploadComplete(..)));
    }

    #[test]
    fn file_dm_upload_cancelled_at_30pct() {
        let cb = MockCallback::with_cancel(30);
        let msg = Message::default();

        cb.on_pending("npub1recv", &msg);

        assert!(cb.on_upload_progress("p", 10, 1000).is_ok());
        assert!(cb.on_upload_progress("p", 20, 2000).is_ok());
        // Cancel triggers at 30%
        let err = cb.on_upload_progress("p", 30, 3000);
        assert!(err.is_err());
        assert!(err.unwrap_err().contains("Cancelled"));
        // Pipeline marks as failed
        cb.on_failed("npub1recv", "p", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        // No Sent, no Persist after cancel — just Failed
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
        assert!(matches!(e.last(), Some(CbEvent::Failed(..))));
    }

    #[test]
    fn file_dm_upload_fails_marks_failed() {
        let cb = MockCallback::new();
        let msg = Message::default();

        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 10, 500).ok();
        // Upload fails (server error, all retries exhausted)
        cb.on_failed("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        assert!(matches!(&e[3], CbEvent::Failed(..)));
        assert!(matches!(&e[4], CbEvent::Persist(..)));
        // No UploadComplete, no Sent
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadComplete(..))));
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
    }

    #[test]
    fn file_dm_gift_wrap_fails_after_upload() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Upload succeeds but gift-wrap fails
        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 100, 10000).ok();
        cb.on_upload_complete("npub1recv", "p", "hash", "https://blossom/hash");
        // Gift-wrap retry exhausted
        cb.on_failed("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        // Upload succeeded but send failed
        assert!(matches!(&e[2], CbEvent::UploadComplete(..)));
        assert!(matches!(&e[3], CbEvent::Failed(..)));
    }

    #[test]
    fn file_dm_with_image_metadata_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Image with thumbhash + dimensions
        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 50, 50000).ok();
        cb.on_upload_progress("p", 100, 100000).ok();
        cb.on_upload_complete("npub1recv", "p", "imghash", "https://blossom/imghash.jpg");
        cb.on_sent("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 7);
        // Verify ordering: pending → progress(3x) → complete → sent → persist
        assert!(matches!(&e[0], CbEvent::Pending(..)));
        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.ends_with(".jpg")));
        assert!(matches!(&e[5], CbEvent::Sent(..)));
    }

    #[test]
    fn cancel_token_config_with_upload() {
        let token = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let c = SendConfig {
            cancel_token: Some(token.clone()),
            ..SendConfig::gui()
        };
        assert!(c.cancel_token.is_some());
        assert!(!token.load(std::sync::atomic::Ordering::Relaxed));

        // Simulate cancel
        token.store(true, std::sync::atomic::Ordering::Relaxed);
        assert!(c.cancel_token.as_ref().unwrap().load(std::sync::atomic::Ordering::Relaxed));
    }
}

#[cfg(test)]
mod seal_tests {
    use super::*;
    use std::sync::Mutex;

    #[derive(Default)]
    struct Stages(Mutex<Vec<(String, Option<u8>)>>);
    impl SendCallback for Stages {
        fn on_upload_stage(&self, _: &str, stage: &str, pct: Option<u8>) {
            self.0.lock().unwrap().push((stage.to_string(), pct));
        }
    }

    #[tokio::test]
    async fn bytes_and_files_seal_to_what_their_key_opens() {
        let plain: Vec<u8> = (0..300_000u32).map(|i| (i * 7 % 251) as u8).collect();
        let params = crypto::generate_encryption_params();
        let hash = crypto::sha256_hex(&plain);
        let src = std::env::temp_dir().join(format!("vector-seal-{}.bin", std::process::id()));
        std::fs::write(&src, &plain).unwrap();

        for source in [FileSource::Bytes(Arc::new(plain.clone())), FileSource::Path(src.clone())] {
            let from_file = matches!(source, FileSource::Path(_));
            let stages = Arc::new(Stages::default());
            let sealed = seal_or_reuse(source, &hash, &params.key, &params.nonce, "pending-1", stages.clone(), None).await.unwrap();
            let Sealed::Body(body, guard) = sealed else { panic!("nothing to reuse without a database") };
            let ciphertext = match &body {
                crate::blossom::UploadBody::Memory(b) => b.to_vec(),
                crate::blossom::UploadBody::File { path, .. } => std::fs::read(path).unwrap(),
            };
            assert_eq!(body.len(), plain.len() as u64 + 16);
            assert_eq!(crypto::decrypt_data(&ciphertext, &params.key, &params.nonce).unwrap(), plain);
            let stages = stages.0.lock().unwrap().clone();
            assert_eq!(stages.first().unwrap().0, "encrypting");
            assert_eq!(stages.last().unwrap(), &("starting".to_string(), None));
            assert_eq!(guard.is_some(), from_file);
            if let crate::blossom::UploadBody::File { path, .. } = &body {
                drop(guard);
                assert!(!path.exists(), "the ciphertext goes with its guard");
            }
        }
        let _ = std::fs::remove_file(&src);
    }

    #[tokio::test]
    async fn an_upload_shows_the_bytes_in_hand_while_it_goes() {
        struct Shown(Mutex<Option<Message>>);
        impl SendCallback for Shown {
            fn on_pending(&self, _: &str, msg: &Message) {
                *self.0.lock().unwrap() = Some(msg.clone());
            }
        }
        let session = crate::db::Session::empty();
        let me = Keys::generate();
        let file = std::env::temp_dir().join(format!("vector-shown-{}.bin", std::process::id()));
        std::fs::write(&file, vec![7u8; 4096]).unwrap();
        let shown = Arc::new(Shown(Mutex::new(None)));
        crate::db::with_session(session, async {
            crate::state::set_nostr_client(crate::nostr_client_builder().build());
            crate::state::set_my_public_key(me.public_key());
            crate::signer::set_test_signer(Some(crate::signer::ActiveSigner::Keys(me.clone())));
            // Called off before its seal: nothing reaches a server.
            let config = SendConfig { cancel_token: Some(Arc::new(AtomicBool::new(true))), ..SendConfig::default() };
            let to = Keys::generate().public_key().to_bech32().unwrap();
            let sent = send_file_dm_from(&to, FileSource::Path(file.clone()), "a.bin", "bin", None, None, None, &config, shown.clone()).await;
            crate::signer::set_test_signer(None);
            assert!(sent.is_err(), "the cancelled send ends failed");
        })
        .await;
        let _ = std::fs::remove_file(&file);
        let msg = shown.0.lock().unwrap().clone().expect("the bubble went up");
        let att = &msg.attachments[0];
        assert!(!att.downloaded && att.path.is_empty(), "the sender keeps no copy of its own");
        assert!(att.resident, "the bubble draws the bytes it's sending, rather than offering to download them");
    }

    #[tokio::test]
    async fn a_pending_wrap_confirm_does_not_keep_its_account_alive() {
        let session = crate::db::Session::empty();
        struct NoCallback;
        impl SendCallback for NoCallback {}
        let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hi").finalize_unsigned_with_id(Keys::generate().public_key());
        crate::db::with_session(session.clone(), async {
            register_wrap_confirm(Arc::new(WrapConfirm {
                wrap_id: EventId::from_byte_array([0; 32]),
                chat_id: String::new(),
                pending_id: String::new(),
                rumor_event_id: String::new(),
                rumor,
                callback: Arc::new(NoCallback),
                self_send: false,
                confirmed: AtomicBool::new(false),
                rescued: AtomicBool::new(false),
                loop_exited: AtomicBool::new(true),
                notify: tokio::sync::Notify::new(),
                session: Arc::downgrade(&crate::db::current_session()),
                registered_at: web_time::Instant::now(),
            }));
            assert_eq!(wrap_confirms().lock().unwrap().len(), 1, "registered on this session");
        })
        .await;
        assert_eq!(Arc::strong_count(&session), 1, "the registry's entry holds no strong reference");
        let weak = Arc::downgrade(&session);
        drop(session);
        assert!(weak.upgrade().is_none(), "the account is freed once nothing else holds it");
    }
}