vector-core 0.11.0

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
//! Profile sync — priority queue, background processor, and relay fetching.
//!
//! The sync queue batches profile fetches by priority (Critical → High → Medium → Low),
//! with cache windows to avoid hammering relays. The background processor
//! drains the queue and calls `load_profile` for each entry.
//!
//! Platform-specific work (DB persistence, image caching) is handled by the
//! `ProfileSyncHandler` trait — src-tauri provides `TauriProfileSyncHandler`,
//! CLI provides a no-op or logging implementation.

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use web_time::Instant;

use nostr_sdk::prelude::*;

use crate::compact::{secs_from_compact, secs_to_compact};
use crate::profile::Profile;
use crate::state::{nostr_client, my_public_key, STATE};
use crate::traits::emit_event;

// ============================================================================
// SyncPriority
// ============================================================================

/// Priority levels for profile syncing, most urgent first (`Critical < Low`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
pub enum SyncPriority {
    Critical,  // No metadata OR user clicked — fetch immediately
    High,      // Active chats — fetch soon
    Medium,    // Recent chats — fetch eventually
    Low,       // Old chats with metadata — passive refresh
}

impl SyncPriority {
    /// Cache window duration — how long before a profile can be re-fetched.
    pub fn cache_window(&self) -> Duration {
        match self {
            SyncPriority::Critical => Duration::from_secs(0),
            SyncPriority::High => Duration::from_secs(5 * 60),
            SyncPriority::Medium => Duration::from_secs(30 * 60),
            SyncPriority::Low => Duration::from_secs(24 * 60 * 60),
        }
    }

    /// Processing delay — how long after queuing before fetching.
    pub fn processing_delay(&self) -> Duration {
        match self {
            SyncPriority::Critical => Duration::from_secs(0),
            SyncPriority::High => Duration::from_secs(5),
            SyncPriority::Medium => Duration::from_secs(30),
            SyncPriority::Low => Duration::from_secs(5 * 60),
        }
    }

    /// Maximum batch size for this priority.
    pub fn batch_size(&self) -> usize {
        match self {
            SyncPriority::Critical => 10,
            SyncPriority::High => 20,
            SyncPriority::Medium => 30,
            SyncPriority::Low => 50,
        }
    }
}

// ============================================================================
// QueueEntry
// ============================================================================

#[derive(Debug, Clone)]
pub(crate) struct QueueEntry {
    npub: String,
    added_at: Instant,
    /// Matches `ProfileSyncQueue::queued` while this is the npub's live entry; a re-add
    /// supersedes it in place rather than sweeping the lanes for it.
    gen: u64,
}

// ============================================================================
// ProfileSyncQueue
// ============================================================================

/// Profile sync queue manager with four priority lanes.
pub struct ProfileSyncQueue {
    critical_queue: VecDeque<QueueEntry>,
    high_queue: VecDeque<QueueEntry>,
    medium_queue: VecDeque<QueueEntry>,
    low_queue: VecDeque<QueueEntry>,
    /// Each waiting npub's live entry generation and lane. Superseded entries stay in their
    /// lane and are dropped when they reach its front.
    queued: HashMap<String, (u64, SyncPriority)>,
    next_gen: u64,
    processing: HashSet<String>,
    /// Seconds after `epoch` each npub was last fetched; pruned past the longest cache window.
    last_fetched: crate::profile::NpubMap<u32>,
    epoch: Instant,
    done_since_prune: u32,
    is_processing: bool,
}

/// `mark_done` calls between sweeps of `last_fetched`.
const PRUNE_EVERY: u32 = 256;

impl Default for ProfileSyncQueue {
    fn default() -> Self { Self::new() }
}

impl ProfileSyncQueue {
    pub fn new() -> Self {
        Self {
            critical_queue: VecDeque::new(),
            high_queue: VecDeque::new(),
            medium_queue: VecDeque::new(),
            low_queue: VecDeque::new(),
            queued: HashMap::new(),
            next_gen: 0,
            processing: HashSet::new(),
            last_fetched: Default::default(),
            epoch: Instant::now(),
            done_since_prune: 0,
            is_processing: false,
        }
    }

    /// Add a profile to the sync queue.
    pub fn add(&mut self, npub: impl AsRef<str> + Into<String>, priority: SyncPriority, force_refresh: bool) {
        let key = npub.as_ref();
        if self.processing.contains(key) {
            return;
        }
        // An entry already waiting at this priority or higher keeps its place and age: a
        // periodic re-add would otherwise restart the delay and never let a Low entry ripen.
        if self.queued.get(key).is_some_and(|&(_, waiting)| waiting <= priority) {
            return;
        }

        // Check cache window (unless force_refresh)
        if !force_refresh {
            if let Some(&fetched_at) = self.last_fetched.get(key) {
                if u64::from(self.secs().saturating_sub(fetched_at)) < priority.cache_window().as_secs() {
                    return;
                }
            }
        }

        let npub: String = npub.into();
        self.next_gen += 1;
        let gen = self.next_gen;
        self.queued.insert(npub.clone(), (gen, priority));

        let entry = QueueEntry { npub, added_at: Instant::now(), gen };
        // Re-adds while the processor is stalled (offline) would otherwise grow the lanes
        // without bound; one sweep once stale entries outnumber live ones keeps them linear.
        let len = self.critical_queue.len() + self.high_queue.len() + self.medium_queue.len() + self.low_queue.len();
        if len > 2 * self.queued.len() + 64 {
            for lane in [&mut self.critical_queue, &mut self.high_queue, &mut self.medium_queue, &mut self.low_queue] {
                lane.retain(|e| Self::is_live(&self.queued, e));
            }
        }
        match priority {
            SyncPriority::Critical => self.critical_queue.push_back(entry),
            SyncPriority::High => self.high_queue.push_back(entry),
            SyncPriority::Medium => self.medium_queue.push_back(entry),
            SyncPriority::Low => self.low_queue.push_back(entry),
        }
        PROCESSOR_WAKE.notify_one();
    }

    /// How long until [`Self::get_next_batch`] has something to return; `None` when every lane
    /// is empty. Mirrors its lane choice: a waiting higher lane holds the lower ones back.
    fn next_ready_in(&mut self) -> Option<Duration> {
        self.prune_fronts();
        [
            (&self.critical_queue, SyncPriority::Critical),
            (&self.high_queue, SyncPriority::High),
            (&self.medium_queue, SyncPriority::Medium),
            (&self.low_queue, SyncPriority::Low),
        ]
        .into_iter()
        .find_map(|(lane, p)| lane.front().map(|e| p.processing_delay().saturating_sub(e.added_at.elapsed())))
    }

    fn is_live(queued: &HashMap<String, (u64, SyncPriority)>, e: &QueueEntry) -> bool {
        queued.get(&e.npub).is_some_and(|&(gen, _)| gen == e.gen)
    }

    /// Drop superseded entries from the front of every lane, so a non-empty lane has a
    /// live entry first.
    fn prune_fronts(&mut self) {
        for lane in [&mut self.critical_queue, &mut self.high_queue, &mut self.medium_queue, &mut self.low_queue] {
            while lane.front().is_some_and(|e| !Self::is_live(&self.queued, e)) {
                lane.pop_front();
            }
        }
    }

    /// Drop every queued + in-flight entry. Used by `reset_session()` so a
    /// post-reset processor doesn't keep fetching the prior account's contacts.
    pub fn clear(&mut self) {
        self.critical_queue.clear();
        self.high_queue.clear();
        self.medium_queue.clear();
        self.low_queue.clear();
        self.queued.clear();
        self.processing.clear();
        self.last_fetched.clear();
    }

    /// Get the next batch of profiles ready to process (highest priority first).
    pub(crate) fn get_next_batch(&mut self) -> Vec<QueueEntry> {
        let mut batch = Vec::new();
        self.prune_fronts();

        let (queue, priority) = if !self.critical_queue.is_empty() {
            (&mut self.critical_queue, SyncPriority::Critical)
        } else if !self.high_queue.is_empty() {
            (&mut self.high_queue, SyncPriority::High)
        } else if !self.medium_queue.is_empty() {
            (&mut self.medium_queue, SyncPriority::Medium)
        } else if !self.low_queue.is_empty() {
            (&mut self.low_queue, SyncPriority::Low)
        } else {
            return batch;
        };

        let batch_size = priority.batch_size();
        let processing_delay = priority.processing_delay();

        while batch.len() < batch_size {
            let Some(entry) = queue.front() else { break };
            if !Self::is_live(&self.queued, entry) {
                queue.pop_front();
                continue;
            }
            if entry.added_at.elapsed() < processing_delay {
                break;
            }
            let entry = queue.pop_front().unwrap();
            self.queued.remove(&entry.npub);
            batch.push(entry);
        }

        batch
    }

    pub fn mark_processing(&mut self, npub: &str) {
        self.processing.insert(npub.to_string());
    }

    pub fn mark_done(&mut self, npub: &str) {
        self.processing.remove(npub);
        let now = self.secs();
        self.last_fetched.insert(npub, now);
        self.done_since_prune += 1;
        if self.done_since_prune >= PRUNE_EVERY {
            self.done_since_prune = 0;
            self.prune_fetched(now);
        }
    }

    /// Forget fetches older than every cache window: they no longer hold anything back.
    fn prune_fetched(&mut self, now: u32) {
        let window = [SyncPriority::Critical, SyncPriority::High, SyncPriority::Medium, SyncPriority::Low]
            .map(|p| p.cache_window().as_secs())
            .into_iter()
            .max()
            .unwrap_or(0);
        self.last_fetched.retain(|&at| u64::from(now.saturating_sub(at)) < window);
    }

    fn secs(&self) -> u32 {
        u32::try_from(self.epoch.elapsed().as_secs()).unwrap_or(u32::MAX)
    }
}

// ============================================================================
// Global queue
// ============================================================================

/// Queued work for THIS account's contacts. The processor loop is
/// process-lifetime and services whichever queue the live session holds, so a
/// swap leaves the prior account's entries behind rather than fetching them.
struct ProfileSyncQueueKey;

fn profile_sync_queue() -> Arc<Mutex<ProfileSyncQueue>> {
    crate::db::current_session().scoped::<ProfileSyncQueueKey, _>()
}

/// Wakes the idle processor when an entry is queued. Process-wide like the processor itself; a
/// stored permit covers an add that lands between its last look and its wait.
static PROCESSOR_WAKE: tokio::sync::Notify = tokio::sync::Notify::const_new();

/// Wake the idle processor to look at the live session's queue: entries added before that
/// session went live woke it against the previous one.
pub(crate) fn wake_processor() {
    #[cfg(test)]
    SESSION_WAKES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    PROCESSOR_WAKE.notify_one();
}

/// Wakes sent by [`wake_processor`], apart from the ones queue adds send.
#[cfg(test)]
pub(crate) static SESSION_WAKES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

// ============================================================================
// ProfileSyncHandler — platform-specific callbacks
// ============================================================================

/// Callback trait for platform-specific profile sync work.
///
/// The core `load_profile` handles relay fetching, STATE updates, and
/// EventEmitter notifications. This trait covers what differs per platform:
/// - **DB persistence** (SQLite upsert)
/// - **Image caching** (avatar/banner download + disk cache)
pub trait ProfileSyncHandler: Send + Sync {
    /// Called after a profile is fetched from relays and updated in STATE.
    /// `slim` is ready for DB persistence. `avatar_url`/`banner_url` are
    /// for image caching (may be empty).
    fn on_profile_fetched(&self, _slim: &crate::SlimProfile, _avatar_url: &str, _banner_url: &str) {}

    /// Delete a blocked profile's cached pictures from disk. No other profile points at them.
    fn forget_images(&self, _images: Vec<super::CachedImage>) {}
}

/// `images` less any file another unblocked profile still shows: the cache is keyed by URL,
/// so two profiles can share one copy.
pub(crate) fn unshared(state: &crate::state::ChatState, owner: u16, images: Vec<super::CachedImage>) -> Vec<super::CachedImage> {
    images
        .into_iter()
        .filter(|img| {
            !state.profiles.iter().any(|p| {
                p.id != owner && !p.flags.is_blocked() && (*p.avatar_cached() == *img.path || *p.banner_cached() == *img.path)
            })
        })
        .collect()
}

/// No-op handler for CLI/tests.
pub struct NoOpProfileSyncHandler;
impl ProfileSyncHandler for NoOpProfileSyncHandler {}

// ============================================================================
// load_profile — core relay fetch + STATE update
// ============================================================================

/// The newest kind-0 the relays hold for `pubkey`, or `None` when they hold none.
async fn fetch_newest_metadata(client: &Client, pubkey: PublicKey) -> Result<Option<Metadata>, String> {
    // `Client::fetch_metadata` is gone: fetch the newest kind-0 and parse it.
    client
        .fetch_events(Filter::new().author(pubkey).kind(Kind::Metadata).limit(1))
        .timeout(crate::relay_request_timeout(Duration::from_secs(15)))
        .await
        .map(|events| {
            events
                .into_iter()
                .max_by_key(|e| e.created_at)
                .and_then(|e| Metadata::from_json(&e.content).ok())
        })
        .map_err(|e| e.to_string())
}

/// Our kind-0 as it stands on the relays, whole: its content's JSON object with every key it
/// holds, whatever Vector makes of them, and every tag. Profiles carry what other clients
/// invented (emoji in names, profile fields, identity proofs); a save edits, never rebuilds.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct OwnKind0 {
    content: serde_json::Map<String, serde_json::Value>,
    tags: Vec<Vec<String>>,
}

/// What a save changes. Every other key and tag of the relay copy stands.
#[derive(Default)]
pub(crate) struct Kind0Edit<'a> {
    name: &'a str,
    avatar: &'a str,
    banner: &'a str,
    about: &'a str,
    bot: bool,
    consent: Option<bool>,
}

/// Our newest kind-0, `Ok(None)` when the relays hold none, `Err` when none of them answered or the
/// newest is no JSON object: unreadable is not absent, and publishing over it would erase it.
async fn fetch_own_kind0(client: &Client, pubkey: PublicKey) -> Result<Option<OwnKind0>, String> {
    let filter = Filter::new().author(pubkey).kind(Kind::Metadata).limit(1);
    let timeout = crate::relay_request_timeout(Duration::from_secs(15));
    let mut events = crate::fetch_answered(client, filter.clone(), timeout).await?;
    // The Discovery Relays too: a profile last written elsewhere may be newest there.
    let pooled = client.relays().all().await;
    let discovery: Vec<RelayUrl> = crate::state::discovery_relay_iter()
        .filter_map(|u| RelayUrl::parse(u).ok())
        .filter(|u| pooled.contains_key(u))
        .collect();
    drop(pooled);
    if !discovery.is_empty() {
        let target = ReqTarget::manual(discovery.into_iter().map(|u| (u, vec![filter.clone()])));
        if let Ok(more) = client.fetch_events(target).timeout(timeout).await {
            events.extend(more);
        }
    }
    crate::newest_replaceable(events).map(|e| kind0_of(&e)).transpose()
}

fn kind0_of(event: &Event) -> Result<OwnKind0, String> {
    match serde_json::from_str::<serde_json::Value>(&event.content) {
        Ok(serde_json::Value::Object(content)) => Ok(OwnKind0 {
            content,
            tags: event.tags.iter().map(|t| t.as_slice().to_vec()).collect(),
        }),
        _ => Err("your profile on the relays isn't one Vector can read, so it was left as it is".to_string()),
    }
}

/// `base` with `edit` applied and our client tag in place of any other: keys and tags it doesn't
/// touch are carried verbatim.
fn edit_kind0(base: OwnKind0, edit: &Kind0Edit) -> OwnKind0 {
    let mut content = base.content;
    let mut put = |key: &str, value: serde_json::Value| { content.insert(key.to_string(), value); };
    if !edit.name.is_empty() {
        put("name", edit.name.into());
    }
    if let Ok(url) = Url::parse(edit.avatar) {
        put("picture", url.to_string().into());
    }
    if let Ok(url) = Url::parse(edit.banner) {
        put("banner", url.to_string().into());
    }
    if !edit.about.is_empty() {
        put("about", edit.about.into());
    }
    if edit.bot {
        put("bot", true.into());
    }
    if edit.consent == Some(true) {
        put(crate::profile::STREAM_CONSENT_KEY, true.into());
    }
    if removes(edit.banner) {
        content.remove("banner");
    }
    if edit.consent == Some(false) {
        content.remove(crate::profile::STREAM_CONSENT_KEY);
    }
    OwnKind0 { content, tags: with_client_tag(base.tags) }
}

/// A first kind-0, from what this device holds of the profile.
fn fresh_kind0(local: &Profile, edit: &Kind0Edit) -> OwnKind0 {
    let mut meta = own_metadata(local, edit.name, edit.avatar, edit.banner, edit.about, edit.bot);
    if let Some(on) = edit.consent {
        meta = crate::profile::with_stream_consent(meta, on);
    }
    let content = match serde_json::to_value(&meta) {
        Ok(serde_json::Value::Object(map)) => map,
        _ => serde_json::Map::new(),
    };
    OwnKind0 { content, tags: with_client_tag(Vec::new()) }
}

fn with_client_tag(tags: Vec<Vec<String>>) -> Vec<Vec<String>> {
    tags.into_iter()
        .filter(|t| t.first().map(String::as_str) != Some("client"))
        .chain(std::iter::once(vec!["client".to_string(), "vector".to_string()]))
        .collect()
}

fn names_vector(tags: &[Vec<String>]) -> bool {
    tags.iter().any(|t| t.len() >= 2 && t[0] == "client" && t[1] == "vector")
}

fn consents(content: &serde_json::Map<String, serde_json::Value>) -> bool {
    content.get(crate::profile::STREAM_CONSENT_KEY).is_some_and(|v| match v.as_bool() {
        Some(b) => b,
        None => v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("true")),
    })
}

/// The fields Vector reads, from a content whose keys may hold anything: a known field of an
/// unexpected type is left out rather than failing the whole profile.
fn metadata_view(content: &serde_json::Map<String, serde_json::Value>) -> Metadata {
    const KNOWN: [&str; 9] = ["name", "display_name", "about", "picture", "banner", "website", "nip05", "lud06", "lud16"];
    let readable = content
        .iter()
        .filter(|(k, v)| !KNOWN.contains(&k.as_str()) || v.is_string())
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    serde_json::from_value(serde_json::Value::Object(readable)).unwrap_or_default()
}

/// Fetch a profile's metadata and status from relays, update STATE, and
/// notify via EventEmitter + handler callback.
///
/// Returns `true` if the fetch succeeded (even if nothing changed).
pub async fn load_profile(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
    let client = match nostr_client() {
        Some(c) => c,
        None => return false,
    };

    // Session captured for the whole load_profile lifecycle. Relay
    // fetches can sleep multi-second; we re-check before writing back
    // to STATE / DB so a mid-fetch swap doesn't land account A's
    // profile in account B's storage.

    let profile_pubkey = match PublicKey::from_bech32(npub.as_str()) {
        Ok(pk) => pk,
        Err(_) => return false,
    };

    let my_public_key = match my_public_key() {
        Some(pk) => pk,
        None => return false,
    };

    // Grab old status (or create profile if missing)
    let (old_status_title, old_status_purpose, old_status_url): (String, String, String);
    let old_status_emoji_tags: Vec<crate::types::EmojiTag>;
    {
        let mut state = STATE.lock().await;
        match state.get_profile(&npub) {
            Some(p) => {
                old_status_title = p.status_title().to_string();
                old_status_purpose = p.status_purpose().to_string();
                old_status_url = p.status_url().to_string();
                old_status_emoji_tags = p.status_emoji_tags();
            }
            None => {
                state.insert_or_replace_profile(&npub, Profile::new());
                old_status_title = String::new();
                old_status_purpose = String::new();
                old_status_url = String::new();
                old_status_emoji_tags = Vec::new();
            }
        }
    }

    // Fetch status (kind 30315) from relays
    let status_filter = Filter::new()
        .author(profile_pubkey)
        .kind(Kind::from_u16(30315))
        .limit(1);

    let (status_title, status_purpose, status_url, status_emoji_tags) = match client
        .fetch_events(status_filter).timeout(crate::relay_request_timeout(Duration::from_secs(15)))
        .await
    {
        Ok(res) => {
            if !res.is_empty() {
                let status_event = res.first().unwrap();
                (
                    clamp_status(status_event.content.clone()),
                    status_event.tags.first()
                        .and_then(|t| t.content())
                        .unwrap_or_default()
                        .to_string(),
                    String::new(),
                    crate::types::EmojiTag::extract_from_tags(status_event.tags.iter()),
                )
            } else {
                (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags)
            }
        }
        Err(_) => (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags),
    };

    let fetch_result = fetch_newest_metadata(&client, profile_pubkey).await;
    if fetch_result.is_ok() {
        let _ = crate::db::profiles::mark_profile_checked(&npub, now_secs());
    }

    match fetch_result {
        Ok(meta) => {
            if let Some(meta) = meta {
                let save_data = {
                    let mut state = STATE.lock().await;
                    let id = match state.interner.lookup(&npub) {
                        Some(id) => id,
                        None => return false,
                    };
                    let (changed, avatar_url, banner_url) = {
                        let profile = match state.get_profile_mut_by_id(id) {
                            Some(p) => p,
                            None => return false,
                        };
                        profile.flags.set_mine(my_public_key == profile_pubkey);

                        // Update status
                        let status_changed = profile.status_title() != status_title.as_str()
                            || profile.status_purpose() != status_purpose.as_str()
                            || profile.status_url() != status_url.as_str()
                            || profile.status_emoji_tags() != status_emoji_tags;
                        profile.set_status(&status_title, &status_purpose, &status_url, &status_emoji_tags);

                        // Update metadata
                        let metadata_changed = profile.from_metadata(meta);

                        // Update timestamp
                        profile.last_updated = secs_to_compact(
                            crate::clock::now_secs()
                        );

                        // A GUI's picture with no local copy goes to the cache too: one held
                        // while a request waited, or one an earlier download lost.
                        let uncached = crate::requests::shielded()
                            && ((!profile.avatar().is_empty() && !profile.has_avatar_cached())
                                || (!profile.banner().is_empty() && !profile.has_banner_cached()));
                        (status_changed || metadata_changed || uncached,
                         profile.avatar().to_string(),
                         profile.banner().to_string())
                    };

                    if changed {
                        let slim = state.serialize_profile(id).unwrap();
                        Some((slim, avatar_url, banner_url))
                    } else {
                        None
                    }
                };

                if let Some((slim, avatar_url, banner_url)) = save_data {
                    // Notify UI via EventEmitter
                    emit_event("profile_update", &slim);
                    // Platform-specific: DB persist + image caching
                    handler.on_profile_fetched(&slim, &avatar_url, &banner_url);
                }
                true
            } else {
                // No metadata on relays — update timestamp so we don't keep retrying
                let mut state = STATE.lock().await;
                if let Some(profile) = state.get_profile_mut(&npub) {
                    profile.last_updated = secs_to_compact(
                        crate::clock::now_secs()
                    );
                }
                true
            }
        }
        Err(_) => false,
    }
}

// ============================================================================
// update_profile — publish metadata to relays
// ============================================================================

/// Update the current user's profile metadata and broadcast to relays.
///
/// Merges the provided fields with the existing profile (empty = keep existing).
/// After successful broadcast, updates STATE and notifies via EventEmitter + handler.
pub async fn update_profile(
    name: String, avatar: String, banner: String, about: String,
    handler: &dyn ProfileSyncHandler,
) -> bool {
    update_profile_inner(name, avatar, banner, about, false, handler).await
}

/// Publish the current user's profile and mark it as a bot (`bot: true` in the metadata). The SDK
/// uses this so every bot it builds is tagged; human clients use [`update_profile`].
pub async fn update_bot_profile(
    name: String, avatar: String, banner: String, about: String,
    handler: &dyn ProfileSyncHandler,
) -> bool {
    update_profile_inner(name, avatar, banner, about, true, handler).await
}

async fn update_profile_inner(
    name: String, avatar: String, banner: String, about: String,
    is_bot: bool,
    handler: &dyn ProfileSyncHandler,
) -> bool {
    let client = match nostr_client() {
        Some(c) => c,
        None => return false,
    };

    let npub = match my_public_key().map(|pk| pk.to_bech32()) {
        Some(Ok(n)) => n,
        _ => return false,
    };

    let Some(pk) = my_public_key() else { return false };
    let edit = Kind0Edit { name: &name, avatar: &avatar, banner: &banner, about: &about, bot: is_bot, consent: None };
    // Always the relay copy, edited: a save that rebuilt from Vector's own fields would drop every
    // key and tag another client wrote. Unread, nothing is published at all.
    let kind0 = match fetch_own_kind0(&client, pk).await {
        Ok(Some(base)) => edit_kind0(base, &edit),
        Ok(None) => {
            let local = STATE.lock().await.get_profile(&npub).cloned().unwrap_or_default();
            fresh_kind0(&local, &edit)
        }
        Err(e) => {
            crate::log_warn!("[update_profile] couldn't read the current profile: {e}");
            return false;
        }
    };

    match publish_kind0(&client, &npub, kind0, handler).await {
        Ok(()) => true,
        Err(e) => {
            crate::log_warn!("[update_profile] {e}");
            false
        }
    }
}

/// A picture argument that removes the field: blank but not empty, since empty leaves it as it is.
fn removes(value: &str) -> bool {
    !value.is_empty() && value.trim().is_empty()
}

/// Our kind-0 rebuilt from `profile`, with each non-empty argument replacing its field.
///
/// Carries stream consent forward, so editing a name or avatar never revokes it.
pub(crate) fn own_metadata(
    profile: &Profile, name: &str, avatar: &str, banner: &str, about: &str, is_bot: bool,
) -> Metadata {
    let pick = |new: &str, old: &str| if new.is_empty() { old.to_string() } else { new.to_string() };

    let mut meta = Metadata::new().name(pick(name, profile.name()));

    let avatar_url = pick(avatar, profile.avatar());
    if let Ok(url) = Url::parse(&avatar_url) {
        meta = meta.picture(url);
    }
    let banner_url = if removes(banner) { String::new() } else { pick(banner, profile.banner()) };
    if let Ok(url) = Url::parse(&banner_url) {
        meta = meta.banner(url);
    }

    if !profile.display_name().is_empty() {
        meta = meta.display_name(profile.display_name());
    }
    meta = meta.about(pick(about, profile.about()));

    if let Ok(url) = Url::parse(profile.website()) {
        meta = meta.website(url);
    }
    if !profile.nip05().is_empty() {
        meta = meta.nip05(profile.nip05());
    }
    if !profile.lud06().is_empty() {
        meta = meta.lud06(profile.lud06());
    }
    if !profile.lud16().is_empty() {
        meta = meta.lud16(profile.lud16());
    }

    // SDK-built bots carry `bot: true` so clients can badge them; human clients never set it.
    if is_bot {
        meta = meta.custom_field("bot", true);
    }
    crate::profile::with_stream_consent(meta, profile.flags.is_stream_consent())
}

/// Sign and broadcast our kind-0, then fold it into STATE, the UI and the DB.
async fn publish_kind0(client: &Client, npub: &str, kind0: OwnKind0, handler: &dyn ProfileSyncHandler) -> Result<(), String> {
    send_kind0(client, &kind0).await?;
    apply_own_metadata(npub, metadata_view(&kind0.content), handler).await
}

async fn send_kind0(client: &Client, kind0: &OwnKind0) -> Result<(), String> {
    let content = serde_json::to_string(&kind0.content).map_err(|e| e.to_string())?;
    let builder = EventBuilder::new(Kind::Metadata, content).tags(kind0.tags.iter().filter_map(|t| Tag::parse(t).ok()));
    let event = crate::sign_builder(builder).await?;
    // First-ACK so the UI updates as soon as the fastest relay responds.
    crate::inbox_relays::send_event_pool_first_ok(client, &event)
        .await
        .map(|_| ())
        .map_err(|e| format!("relay broadcast failed: {e}"))
}

/// Once a login: a profile last written by another client takes our client tag, every key and
/// tag of it kept, so servers that serve Vector's users recognise the account. Returns whether
/// it published.
pub async fn stamp_vector_client() -> Result<bool, String> {
    let client = nostr_client().ok_or("Not connected")?;
    let pk = my_public_key().ok_or("No active account")?;
    let Some(base) = fetch_own_kind0(&client, pk).await? else { return Ok(false) };
    if names_vector(&base.tags) {
        return Ok(false);
    }
    if !crate::db::session_is_live() {
        return Err("account changed during the operation".to_string());
    }
    send_kind0(&client, &OwnKind0 { tags: with_client_tag(base.tags), content: base.content }).await?;
    Ok(true)
}

/// [`stamp_vector_client`] once the login's sync has settled: its relays are busiest before it.
pub async fn stamp_vector_client_after_sync() {
    crate::rt::time::sleep(Duration::from_secs(30)).await;
    match stamp_vector_client().await {
        Ok(true) => crate::log_info!("[Profile] added Vector's client tag to the profile"),
        Ok(false) => {}
        Err(e) => crate::log_warn!("[Profile] client tag not added: {e}"),
    }
}

async fn apply_own_metadata(npub: &str, meta: Metadata, handler: &dyn ProfileSyncHandler) -> Result<(), String> {
    let (slim, avatar_url, banner_url) = {
        let mut state = STATE.lock().await;
        // Creates the entry if this identity had none yet (a fresh account is interned here).
        let mut profile = state.get_profile(npub).cloned().unwrap_or_default();
        profile.from_metadata(meta);
        profile.flags.set_mine(true);
        let urls = (profile.avatar().to_string(), profile.banner().to_string());
        state.insert_or_replace_profile(npub, profile);
        let slim = state
            .interner
            .lookup(npub)
            .and_then(|id| state.serialize_profile(id))
            .ok_or("own profile missing after insert")?;
        (slim, urls.0, urls.1)
    };
    emit_event("profile_update", &slim);
    handler.on_profile_fetched(&slim, &avatar_url, &banner_url);
    Ok(())
}

/// What a consent change does, decided from the relay copy (`None` = the relays hold none).
#[derive(Debug, PartialEq)]
pub(crate) enum ConsentPlan {
    /// The relays already say it: adopt their copy, publish nothing.
    Unchanged(OwnKind0),
    Publish(OwnKind0),
}

/// A read-modify-write of the relay copy, so every key and tag another client wrote survives.
/// With no relay copy, the local profile is carried, and refused when there is none to carry: a
/// fresh device must never publish a blank profile over the real one.
pub(crate) fn consent_plan(fetched: Option<OwnKind0>, local: &Profile, on: bool) -> Result<ConsentPlan, String> {
    let edit = Kind0Edit { consent: Some(on), ..Default::default() };
    match fetched {
        Some(remote) if consents(&remote.content) == on => Ok(ConsentPlan::Unchanged(remote)),
        Some(remote) => Ok(ConsentPlan::Publish(edit_kind0(remote, &edit))),
        None => {
            if local.name().is_empty() && local.display_name().is_empty()
                && local.about().is_empty() && local.avatar().is_empty()
            {
                return Err("Couldn't find your profile on your relays".to_string());
            }
            let edit = Kind0Edit { bot: local.flags.is_bot(), ..edit };
            Ok(ConsentPlan::Publish(fresh_kind0(local, &edit)))
        }
    }
}

/// Publish our kind-0 with stream consent set to `on`; returns the value now in effect.
///
/// Refused when no relay answers the read, so a fresh device never clobbers the real profile.
pub async fn set_stream_consent(on: bool, handler: &dyn ProfileSyncHandler) -> Result<bool, String> {
    let client = nostr_client().ok_or("Not connected")?;
    let my_public_key = my_public_key().ok_or("No active account")?;
    let npub = my_public_key.to_bech32().map_err(|e| e.to_string())?;

    let fetched = fetch_own_kind0(&client, my_public_key)
        .await
        .map_err(|_| "Couldn't read your profile from your relays".to_string())?;
    let local = STATE.lock().await.get_profile(&npub).cloned().unwrap_or_default();
    let plan = consent_plan(fetched, &local, on)?;

    if !crate::db::session_is_live() {
        return Err("account changed during the operation".to_string());
    }
    match plan {
        ConsentPlan::Unchanged(remote) => apply_own_metadata(&npub, metadata_view(&remote.content), handler).await?,
        ConsentPlan::Publish(kind0) => publish_kind0(&client, &npub, kind0, handler).await?,
    }
    Ok(on)
}

// ============================================================================
// update_status — publish status to relays
// ============================================================================

/// Update the current user's status (kind 30315) and broadcast to relays.
///
/// Status length cap in Unicode scalar characters, enforced on BOTH sides:
/// our own publishes and every stored inbound status. Characters, not bytes —
/// a byte cap would chop emoji-heavy statuses to a third of what text gets.
pub const STATUS_MAX_CHARS: usize = 120;

/// Truncate a status to [`STATUS_MAX_CHARS`] on a character boundary.
fn clamp_status(s: String) -> String {
    if s.chars().count() <= STATUS_MAX_CHARS {
        s
    } else {
        s.chars().take(STATUS_MAX_CHARS).collect()
    }
}

/// Status is ephemeral — updated in STATE + frontend but not persisted to DB.
/// (Re-fetched from relays on next `load_profile` call.)
pub async fn update_status(status: String) -> bool {
    let status = clamp_status(status);
    let client = match nostr_client() {
        Some(c) => c,
        None => return false,
    };

    let my_public_key = match my_public_key() {
        Some(pk) => pk,
        None => return false,
    };

    // Build and sign kind 30315 status event. `:shortcode:`s from the user's
    // equipped packs ride along as NIP-30 tags so other clients render them.
    let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(&status);
    let mut status_builder = EventBuilder::new(Kind::from_u16(30315), status.as_str())
        .tag(Tag::custom("d", vec!["general"]));
    for et in &emoji_tags {
        status_builder = status_builder.tag(Tag::custom("emoji", [et.shortcode.clone(), et.url.clone()]));
    }

    let Ok(event) = crate::sign_builder(status_builder).await else {
        return false;
    };

    match crate::inbox_relays::send_event_pool_first_ok(&client, &event).await {
        Ok(_) => {
            let mut state = STATE.lock().await;
            let npub = match my_public_key.to_bech32() {
                Ok(n) => n,
                Err(_) => return false,
            };
            let id = match state.interner.lookup(&npub) {
                Some(id) => id,
                None => return false,
            };
            {
                let profile = match state.get_profile_mut_by_id(id) {
                    Some(p) => p,
                    None => return false,
                };
                profile.set_status_title(&status);
                profile.set_status_purpose("general");
                profile.set_status_emoji_tags(&emoji_tags);
            }

            let slim = state.serialize_profile(id).unwrap();
            // Persist NOW: without this the new status (and its emoji tags)
            // survives a reboot only if a self-profile sync happens to run
            // before the app closes.
            let _ = crate::db::profiles::set_profile(&slim);
            emit_event("profile_update", &slim);
            true
        }
        Err(_) => false,
    }
}

// ============================================================================
// block / unblock / nickname / blocked list
// ============================================================================

/// Block a user by npub. DM events from blocked users are dropped after decryption.
/// Group messages are stored but filtered in the UI.
///
/// Returns `false` if trying to block yourself or if the profile can't be found.
pub async fn block_user(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
    // Prevent blocking yourself
    if let Some(my_pk) = my_public_key() {
        if my_pk.to_bech32().ok().as_deref() == Some(npub.as_str()) {
            return false;
        }
    }

    let mut state = STATE.lock().await;

    // Create profile if it doesn't exist (can block someone with no prior contact)
    if state.interner.lookup(&npub).is_none() {
        state.insert_or_replace_profile(&npub, Profile::new());
    }

    if let Some(id) = state.interner.lookup(&npub) {
        {
            let profile = match state.get_profile_mut_by_id(id) {
                Some(p) => p,
                None => return false,
            };
            profile.flags.set_blocked(true);
        }
        let images = state.get_profile_mut_by_id(id).map(|p| p.forget_imagery()).unwrap_or_default();
        let images = unshared(&state, id, images);
        let slim = state.serialize_profile(id).unwrap();
        drop(state);
        emit_event("profile_update", &slim);
        handler.on_profile_fetched(&slim, "", "");
        handler.forget_images(images);
        crate::push::controls_changed();
        // Their invites go unanswered with them.
        if crate::requests::shielded() && crate::db::community::delete_pending_invites_from(&npub).unwrap_or(0) > 0 {
            emit_event("community_invites_purged", &());
        }
        true
    } else {
        false
    }
}

/// Unblock a user by npub.
pub async fn unblock_user(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
    let mut state = STATE.lock().await;

    if let Some(id) = state.interner.lookup(&npub) {
        {
            let profile = match state.get_profile_mut_by_id(id) {
                Some(p) => p,
                None => return false,
            };
            profile.flags.set_blocked(false);
        }
        let slim = state.serialize_profile(id).unwrap();
        drop(state);
        emit_event("profile_update", &slim);
        handler.on_profile_fetched(&slim, "", "");
        crate::push::controls_changed();
        // Their pictures were dropped at the block: the next fetch brings them back.
        queue_profile_sync(npub, SyncPriority::Critical, true);
        true
    } else {
        false
    }
}

/// Accept a DM request without answering it: what its sender sent, and their
/// pictures, may load from now on.
pub async fn accept_chat(npub: String) -> Result<(), String> {
    crate::db::scoped(async move {
        let slim = {
            let mut guard = STATE.lock().await;
            let state = &mut *guard;
            let chat = state.chats.iter_mut()
                .find(|c| c.id == npub && c.chat_type == crate::ChatType::DirectMessage)
                .ok_or_else(|| "no chat with that npub".to_string())?;
            if !chat.is_request() {
                return Ok(());
            }
            chat.metadata.insert(crate::chat::ACCEPTED_KEY, "true".into());
            crate::db::chats::SlimChatDB::from_chat(chat, &state.interner)
        };
        crate::db::chats::save_slim_chat(&slim)?;
        // Their pictures and wallpaper were held while the request waited.
        crate::wallpaper::release_held(&npub).await;
        queue_profile_sync(npub, SyncPriority::Critical, true);
        Ok(())
    }).await
}

/// Persist what `ChatState::forget_blocked_imagery` dropped and delete the files.
pub fn persist_forgotten_imagery(handler: &dyn ProfileSyncHandler, slims: Vec<crate::SlimProfile>, images: Vec<super::CachedImage>) {
    if slims.is_empty() {
        return;
    }
    log_info!("[Profile] Dropped the pictures of {} blocked profiles", slims.len());
    for slim in &slims {
        handler.on_profile_fetched(slim, "", "");
    }
    handler.forget_images(images);
}

/// Get all blocked profiles.
pub async fn get_blocked_users() -> Vec<crate::SlimProfile> {
    let state = STATE.lock().await;
    state.profiles.iter()
        .filter(|p| p.flags.is_blocked())
        .filter_map(|p| state.serialize_profile(p.id))
        .collect()
}

/// Set a nickname for a profile.
pub async fn set_nickname(npub: String, nickname: String, handler: &dyn ProfileSyncHandler) -> bool {
    let mut state = STATE.lock().await;

    if let Some(id) = state.interner.lookup(&npub) {
        {
            let profile = match state.get_profile_mut_by_id(id) {
                Some(p) => p,
                None => return false,
            };
            profile.set_nickname(&nickname);
        }
        let slim = state.serialize_profile(id).unwrap();
        drop(state);
        emit_event("profile_nick_changed", &serde_json::json!({
            "profile_id": &npub,
            "value": &slim.nickname
        }));
        handler.on_profile_fetched(&slim, "", "");
        true
    } else {
        false
    }
}

// ============================================================================
// Background processor
// ============================================================================

/// Background processor that continuously drains the profile sync queue.
///
/// Spawned once at startup. Processes batches in priority order, calling
/// `load_profile` for each entry with the provided handler.
pub async fn start_profile_sync_processor(handler: Arc<dyn ProfileSyncHandler>) {
    let mut last_own_profile_sync = Instant::now();
    let own_profile_sync_interval = Duration::from_secs(5 * 60);

    loop {
        // Periodically queue our own profile to detect changes from other Nostr apps
        if last_own_profile_sync.elapsed() >= own_profile_sync_interval {
            let state = STATE.lock().await;
            if let Some(own_profile) = state.profiles.iter().find(|p| p.flags.is_mine()) {
                let npub = state.interner.resolve(own_profile.id).unwrap_or("").to_string();
                drop(state);

                let owner = profile_sync_queue();
                let mut queue = owner.lock().unwrap();
                queue.add(npub, SyncPriority::Low, false);
            }
            last_own_profile_sync = Instant::now();
        }

        // Get next batch (lock scoped)
        let (should_wait, batch) = {
            let owner = profile_sync_queue();
            let mut queue = owner.lock().unwrap();

            if queue.is_processing {
                (true, vec![])
            } else {
                queue.is_processing = true;
                let batch = queue.get_next_batch();
                for entry in &batch {
                    queue.mark_processing(&entry.npub);
                }
                (false, batch)
            }
        };

        if should_wait {
            crate::rt::time::sleep(Duration::from_secs(1)).await;
            continue;
        }

        if batch.is_empty() {
            let ready_in = {
                let owner = profile_sync_queue();
                let mut queue = owner.lock().unwrap();
                queue.is_processing = false;
                queue.next_ready_in()
            };
            // Sleep until the next entry ripens or the own-profile check is due, unless an add
            // comes first, so an idle processor costs no wakeups.
            let own_due = own_profile_sync_interval.saturating_sub(last_own_profile_sync.elapsed());
            let wait = ready_in.map_or(own_due, |r| r.min(own_due)).max(Duration::from_millis(50));
            let _ = crate::rt::time::timeout(wait, PROCESSOR_WAKE.notified()).await;
            continue;
        }

        // Session captured per-batch so a swap aborts the loop before
        // account A's queue work lands in account B's DB. The next
        // outer-loop iteration picks up the new session's queue cleanly.

        for entry in &batch {
            load_profile(entry.npub.clone(), handler.as_ref()).await;

            {
                let owner = profile_sync_queue();
                let mut queue = owner.lock().unwrap();
                queue.mark_done(&entry.npub);
            }

            crate::rt::time::sleep(Duration::from_millis(100)).await;
        }

        // Release processing lock
        {
            let owner = profile_sync_queue();
            let mut queue = owner.lock().unwrap();
            queue.is_processing = false;
        }

        crate::rt::time::sleep(Duration::from_millis(500)).await;
    }
}

// ============================================================================
// Public API
// ============================================================================

/// Queue a single profile for syncing.
pub fn queue_profile_sync(npub: String, priority: SyncPriority, force_refresh: bool) {
    let owner = profile_sync_queue();
    let mut queue = owner.lock().unwrap();
    queue.add(npub, priority, force_refresh);
}

fn now_secs() -> u64 {
    crate::clock::now_secs()
}

/// How long a profile's last check stays good enough for one that is merely on screen.
const ON_SCREEN_FRESH: Duration = Duration::from_secs(6 * 60 * 60);

/// What a profile on screen needs: a fetch now when we know nothing of it, a slow refresh when
/// its last check is older than [`ON_SCREEN_FRESH`], otherwise nothing.
fn on_screen_need(profile: Option<&Profile>, now: u64) -> Option<SyncPriority> {
    let Some(p) = profile else { return Some(SyncPriority::Critical) };
    if p.flags.is_mine() {
        return None;
    }
    let checked = secs_from_compact(p.last_updated);
    if checked == 0 {
        let known = !p.name().is_empty() || !p.display_name().is_empty() || !p.avatar().is_empty();
        return Some(if known { SyncPriority::Medium } else { SyncPriority::Critical });
    }
    (now.saturating_sub(checked) >= ON_SCREEN_FRESH.as_secs()).then_some(SyncPriority::Medium)
}

/// Queue the profiles the UI has on screen (or nearly) whose last check has gone stale. Called
/// on every view, so it costs a lookup per npub and a fetch only for those that need one.
pub async fn queue_visible_profiles(npubs: Vec<String>) {
    const MAX_PER_CALL: usize = 200;
    let now = now_secs();
    let picks: Vec<(String, SyncPriority)> = {
        let state = STATE.lock().await;
        npubs
            .into_iter()
            .take(MAX_PER_CALL)
            .filter(|n| n.starts_with("npub1"))
            .filter_map(|npub| on_screen_need(state.get_profile(&npub), now).map(|p| (npub, p)))
            .collect()
    };
    if picks.is_empty() {
        return;
    }
    let owner = profile_sync_queue();
    let mut queue = owner.lock().unwrap();
    for (npub, priority) in picks {
        queue.add(npub, priority, false);
    }
}

/// Queue all profiles for a chat. A community's members refresh as they come on screen
/// ([`queue_visible_profiles`]), so here a community only fetches the ones we know nothing of.
pub async fn queue_chat_profiles(chat_id: String, is_opening: bool) {
    let state = STATE.lock().await;

    let chat = match state.get_chat(&chat_id) {
        Some(c) => c,
        None => return,
    };

    let is_community = chat.is_community();
    let base_priority = if is_opening {
        SyncPriority::High
    } else {
        SyncPriority::Medium
    };

    let mut profiles_to_queue = Vec::new();

    for &handle in chat.participants() {
        let member_npub = match state.interner.resolve(handle) {
            Some(s) => s.to_string(),
            None => continue,
        };

        let has_metadata = state.get_profile_by_id(handle)
            .map(|p| {
                let has_data = !p.name().is_empty() || !p.display_name().is_empty() || !p.avatar().is_empty();
                let was_fetched = p.last_updated > 0;
                has_data || was_fetched
            })
            .unwrap_or(false);

        let priority = if !has_metadata {
            SyncPriority::Critical
        } else if is_community {
            continue;
        } else {
            base_priority
        };

        profiles_to_queue.push((member_npub, priority));
    }

    drop(state);

    let owner = profile_sync_queue();
    let mut queue = owner.lock().unwrap();
    for (npub, priority) in profiles_to_queue {
        queue.add(npub, priority, false);
    }
}

/// Force immediate refresh of a profile (for user clicks).
pub fn refresh_profile_now(npub: String) {
    let owner = profile_sync_queue();
    let mut queue = owner.lock().unwrap();
    queue.add(npub, SyncPriority::Critical, true);
}

/// Queue every profile that has never been fetched. Known profiles refresh when their chat
/// opens or they come on screen ([`queue_visible_profiles`]).
pub async fn sync_all_profiles() {
    let state = STATE.lock().await;
    let owner = profile_sync_queue();
    let mut queue = owner.lock().unwrap();

    for profile in &state.profiles {
        let has_metadata = !profile.name().is_empty() || !profile.display_name().is_empty() || !profile.avatar().is_empty();
        if has_metadata || profile.last_updated > 0 {
            continue;
        }
        if let Some(npub) = state.interner.resolve(profile.id) {
            queue.add(npub, SyncPriority::Critical, false);
        }
    }
}

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

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

    #[test]
    fn a_status_clamps_at_120_characters_not_bytes() {
        assert_eq!(clamp_status("hi".to_string()), "hi");
        let exact: String = "a".repeat(STATUS_MAX_CHARS);
        assert_eq!(clamp_status(exact.clone()), exact, "at the cap is untouched");
        let long = "b".repeat(10_000);
        assert_eq!(clamp_status(long).chars().count(), STATUS_MAX_CHARS);
        // Characters, not bytes: 120 four-byte emoji survive whole.
        let emoji: String = "\u{1F980}".repeat(STATUS_MAX_CHARS);
        let clamped = clamp_status(format!("{emoji}overflow"));
        assert_eq!(clamped.chars().count(), STATUS_MAX_CHARS);
        assert_eq!(clamped, emoji, "truncation lands on a character boundary");
    }
}

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

    #[test]
    fn an_on_screen_profile_is_fetched_only_when_unknown_or_stale() {
        let now = 1_900_000_000;
        assert_eq!(on_screen_need(None, now), Some(SyncPriority::Critical));
        let mut p = Profile::new();
        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Critical));
        p.set_name("kitty");
        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Medium), "named but never checked");
        p.last_updated = secs_to_compact(now - 60);
        assert_eq!(on_screen_need(Some(&p), now), None, "checked a minute ago");
        p.last_updated = secs_to_compact(now - ON_SCREEN_FRESH.as_secs());
        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Medium), "stale");
        p.flags.set_mine(true);
        assert_eq!(on_screen_need(Some(&p), now), None, "our own syncs on its own clock");
    }
}

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

    #[test]
    fn sync_priority_cache_windows() {
        assert_eq!(SyncPriority::Critical.cache_window(), Duration::from_secs(0));
        assert_eq!(SyncPriority::High.cache_window(), Duration::from_secs(300));
        assert_eq!(SyncPriority::Medium.cache_window(), Duration::from_secs(1800));
        assert_eq!(SyncPriority::Low.cache_window(), Duration::from_secs(86400));
    }

    #[test]
    fn sync_priority_batch_sizes() {
        assert_eq!(SyncPriority::Critical.batch_size(), 10);
        assert_eq!(SyncPriority::High.batch_size(), 20);
        assert_eq!(SyncPriority::Medium.batch_size(), 30);
        assert_eq!(SyncPriority::Low.batch_size(), 50);
    }

    impl ProfileSyncQueue {
        fn push_raw(&mut self, priority: SyncPriority, npub: &str, added_at: Instant) {
            self.next_gen += 1;
            self.queued.insert(npub.to_string(), (self.next_gen, priority));
            let entry = QueueEntry { npub: npub.to_string(), added_at, gen: self.next_gen };
            match priority {
                SyncPriority::Critical => self.critical_queue.push_back(entry),
                SyncPriority::High => self.high_queue.push_back(entry),
                SyncPriority::Medium => self.medium_queue.push_back(entry),
                SyncPriority::Low => self.low_queue.push_back(entry),
            }
        }

        fn live(&self, lane: &VecDeque<QueueEntry>) -> Vec<String> {
            lane.iter().filter(|e| Self::is_live(&self.queued, e)).map(|e| e.npub.clone()).collect()
        }
    }

    #[test]
    fn next_ready_in_follows_the_lane_the_batch_would_take() {
        let mut queue = ProfileSyncQueue::new();
        assert_eq!(queue.next_ready_in(), None, "empty: nothing to wake for");
        let now = Instant::now();
        queue.push_raw(SyncPriority::Low, "npub1low", now - Duration::from_secs(10 * 60));
        assert_eq!(queue.next_ready_in(), Some(Duration::ZERO), "a ripe low entry is due now");
        queue.push_raw(SyncPriority::High, "npub1high", now);
        let wait = queue.next_ready_in().unwrap();
        assert!(wait > Duration::from_secs(4) && wait <= Duration::from_secs(5), "a waiting high entry holds the low lane back: {wait:?}");
        assert!(queue.get_next_batch().is_empty());
        queue.add("npub1high", SyncPriority::Critical, true);
        assert_eq!(queue.next_ready_in(), Some(Duration::ZERO), "the superseded high entry no longer counts");
    }

    #[test]
    fn re_adds_while_stalled_stay_bounded() {
        let mut queue = ProfileSyncQueue::new();
        for _ in 0..100 {
            for i in 0..50 {
                queue.add(format!("npub1{i}"), SyncPriority::Low, true);
            }
        }
        assert_eq!(queue.live(&queue.low_queue).len(), 50);
        assert!(queue.low_queue.len() <= 2 * 50 + 64 + 1, "{} entries for 50 profiles", queue.low_queue.len());
    }

    #[test]
    fn queue_add_and_dedup() {
        let mut queue = ProfileSyncQueue::new();

        queue.add("npub1alice", SyncPriority::Low, false);
        queue.add("npub1alice", SyncPriority::High, false);

        // Should be in High queue only (deduped from Low)
        assert!(queue.live(&queue.low_queue).is_empty());
        assert_eq!(queue.live(&queue.high_queue), ["npub1alice"]);
    }

    #[test]
    fn queue_skips_processing() {
        let mut queue = ProfileSyncQueue::new();
        queue.mark_processing("npub1bob");

        queue.add("npub1bob", SyncPriority::Critical, false);
        assert!(queue.critical_queue.is_empty(), "should skip profiles being processed");
    }

    #[test]
    fn queue_cache_window_skips() {
        let mut queue = ProfileSyncQueue::new();

        // Mark as recently fetched
        queue.mark_done("npub1carol");

        // Try to add with Low priority (24h cache window) — should skip
        queue.add("npub1carol", SyncPriority::Low, false);
        assert!(queue.low_queue.is_empty(), "should skip within cache window");

        // Force refresh should bypass cache
        queue.add("npub1carol", SyncPriority::Low, true);
        assert_eq!(queue.low_queue.len(), 1, "force_refresh should bypass cache");
    }

    #[test]
    fn queue_critical_skips_cache() {
        let mut queue = ProfileSyncQueue::new();

        // Critical has 0s cache window — always fetches
        queue.mark_done("npub1dave");
        queue.add("npub1dave", SyncPriority::Critical, false);
        assert_eq!(queue.critical_queue.len(), 1, "Critical should always fetch");
    }

    #[test]
    fn re_adding_moves_an_entry_between_lanes() {
        let mut queue = ProfileSyncQueue::new();
        queue.add("npub1a", SyncPriority::Low, true);
        queue.add("npub1b", SyncPriority::Low, true);
        queue.add("npub1a", SyncPriority::Critical, true);
        assert_eq!(queue.live(&queue.low_queue), ["npub1b"]);
        assert_eq!(queue.live(&queue.critical_queue), ["npub1a"]);
        let batch = queue.get_next_batch();
        assert_eq!(batch.len(), 1);
        assert_eq!(batch[0].npub, "npub1a");
        // Its superseded Low entry never surfaces, even once the Low lane's delay passes.
        queue.critical_queue.clear();
        queue.add("npub1c", SyncPriority::Low, true);
        assert_eq!(queue.live(&queue.low_queue), ["npub1b", "npub1c"]);
    }

    #[test]
    fn a_periodic_re_add_keeps_the_waiting_entry() {
        let mut queue = ProfileSyncQueue::new();
        queue.push_raw(SyncPriority::Low, "npub1low", Instant::now() - Duration::from_secs(10 * 60));
        queue.push_raw(SyncPriority::High, "npub1high", Instant::now() - Duration::from_secs(10));
        queue.add("npub1low", SyncPriority::Low, false);
        queue.add("npub1high", SyncPriority::Low, false);
        assert_eq!(queue.live(&queue.high_queue), ["npub1high"], "a lower re-add never demotes");
        assert_eq!(queue.get_next_batch().len(), 1);
        let batch = queue.get_next_batch();
        assert_eq!(batch.len(), 1, "the ripe Low entry keeps its age");
        assert_eq!(batch[0].npub, "npub1low");
    }

    #[test]
    fn get_next_batch_priority_order() {
        let mut queue = ProfileSyncQueue::new();

        // Add to Low and Critical queues
        queue.push_raw(SyncPriority::Low, "npub1low", Instant::now() - Duration::from_secs(600));
        queue.push_raw(SyncPriority::Critical, "npub1critical", Instant::now());

        let batch = queue.get_next_batch();
        assert_eq!(batch.len(), 1);
        assert_eq!(batch[0].npub, "npub1critical", "Critical should process before Low");
    }

    #[test]
    fn get_next_batch_respects_delay() {
        let mut queue = ProfileSyncQueue::new();

        // Add a High priority entry just now (5s delay required)
        queue.push_raw(SyncPriority::High, "npub1new", Instant::now());

        let batch = queue.get_next_batch();
        assert!(batch.is_empty(), "should not process before delay elapses");
    }

    #[test]
    fn mark_done_updates_last_fetched() {
        let mut queue = ProfileSyncQueue::new();
        queue.mark_processing("npub1eve");
        assert!(queue.processing.contains("npub1eve"));

        queue.mark_done("npub1eve");
        assert!(!queue.processing.contains("npub1eve"));
        assert!(queue.last_fetched.contains("npub1eve"));
    }

    #[test]
    fn fetches_older_than_every_window_are_forgotten() {
        let mut queue = ProfileSyncQueue::new();
        let day = 24 * 60 * 60;
        let now = 3 * day;
        queue.last_fetched.insert("npub1stale", now - day);
        queue.last_fetched.insert("npub1edge", now - day + 1);
        queue.last_fetched.insert("npub1fresh", now - 10);
        queue.prune_fetched(now);
        assert!(!queue.last_fetched.contains("npub1stale"), "a day old gates nothing");
        assert!(queue.last_fetched.contains("npub1edge"), "inside the Low window it still gates a Low re-add");
        assert!(queue.last_fetched.contains("npub1fresh"));
    }

    #[test]
    fn mark_done_sweeps_every_so_often() {
        let mut queue = ProfileSyncQueue::new();
        for i in 0..PRUNE_EVERY - 1 {
            queue.mark_done(&format!("npub1done{i}"));
        }
        assert_eq!(queue.done_since_prune, PRUNE_EVERY - 1);
        queue.last_fetched.insert("npub1future", u32::MAX);
        queue.mark_done("npub1last");
        assert_eq!(queue.done_since_prune, 0, "the sweep ran");
        assert_eq!(queue.last_fetched.len(), PRUNE_EVERY as usize + 1, "nothing recent was dropped");
    }

    #[test]
    fn the_cache_window_reads_whole_seconds_since_the_fetch() {
        use nostr_sdk::prelude::{Keys, ToBech32};
        let npub = Keys::generate().public_key().to_bech32().unwrap();
        let mut queue = ProfileSyncQueue::new();
        let now = queue.secs();
        queue.last_fetched.insert(&npub, now);
        queue.add(npub.clone(), SyncPriority::High, false);
        assert!(queue.high_queue.is_empty(), "a canonical npub is found by its key bytes");

        let mut queue = ProfileSyncQueue::new();
        queue.epoch = queue.epoch.checked_sub(Duration::from_secs(400)).unwrap_or(queue.epoch);
        if queue.secs() >= 400 {
            queue.last_fetched.insert(&npub, queue.secs() - 301);
            queue.add(npub.clone(), SyncPriority::Medium, false);
            assert!(queue.medium_queue.is_empty(), "301 s is inside Medium's 30 min");
            queue.add(npub.clone(), SyncPriority::High, false);
            assert_eq!(queue.live(&queue.high_queue), [npub.as_str()], "and past High's 5 min");
        }
    }

    fn consenting_profile() -> Profile {
        let mut p = Profile::new();
        p.from_metadata(
            Metadata::from_json(r#"{"name":"old","about":"bio","picture":"https://x/a.png","lud16":"a@b.c","stream_consent":true}"#).unwrap(),
        );
        p
    }

    #[test]
    fn an_own_profile_edit_carries_stream_consent_forward() {
        let p = consenting_profile();
        assert!(p.flags.is_stream_consent());

        let meta = own_metadata(&p, "new", "", "", "", false);
        assert!(crate::profile::metadata_stream_consent(&meta), "a rename keeps consent");
        assert_eq!(meta.name.as_deref(), Some("new"));
        assert_eq!(meta.about.as_deref(), Some("bio"));
        assert_eq!(meta.picture.as_deref(), Some("https://x/a.png"));
        assert_eq!(meta.lud16.as_deref(), Some("a@b.c"));
        assert!(!meta.custom.contains_key("bot"));

        let mut republished = p.clone();
        assert!(!republished.from_metadata(own_metadata(&p, "", "", "", "", false)), "a no-op edit changes nothing");
        assert!(republished.flags.is_stream_consent());
    }

    /// A relay copy, as `fetch_own_kind0` reads one.
    fn kind0(content: &str, tags: &[&[&str]]) -> OwnKind0 {
        OwnKind0 {
            content: serde_json::from_str(content).unwrap(),
            tags: tags.iter().map(|t| t.iter().map(|s| s.to_string()).collect()).collect(),
        }
    }

    /// A real profile that leans on what Vector doesn't model: `emoji` tags drawing a name
    /// from custom emoji, Ditto's `fields`, a camelCase `displayName`.
    fn henky() -> OwnKind0 {
        let content: String = serde_json::from_str(HENKY_CONTENT).unwrap();
        OwnKind0 { content: serde_json::from_str(&content).unwrap(), tags: serde_json::from_str(HENKY_TAGS).unwrap() }
    }
    const HENKY_CONTENT: &str = r#####""{\"about\":\"Sysadmin | AI Entertainment Enthusiast | Game Server Operator | Liberal (as in Liberty) Nationalist (each country has a right to be sovereign and should not impose their will on other countries)\\r\\n- There is only a paradox if you don't admit it\\r\\n\\r\\nSee me post with a really long address on mastodon? That's a bridge. My real profile is : https://ditto.pub/@henk.tech\\n\\nMy webhost blocks some requests behind proof of work, if my NIP-05 errors for you then you can verify it manually. I unfortunately can't disable this.\",\"bot\":false,\"name\":\":H::e::n::k::y:!!\",\"nip05\":\"Henk.Tech\",\"picture\":\"https://turbo.henk.tech/avatar/HenkyAnimated.gif\",\"fields\":[[\"KoboldAI\",\"https://koboldai.com\"]],\"website\":\"https://henk.tech\",\"displayName\":\"Henky!!\",\"banner\":\"https://turbo.henk.tech/avatar/BannerHenky.png\"}""#####;
    const HENKY_TAGS: &str = r#####"[["emoji", "H", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/h.png"], ["emoji", "e", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/e.png"], ["emoji", "n", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/n.png"], ["emoji", "k", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/k.png"], ["emoji", "y", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/y.png"], ["alt", "User profile for :H::e::n::k::y:!!"], ["name", ":H::e::n::k::y:!!"], ["picture", "https://turbo.henk.tech/avatar/HenkyAnimated.gif"], ["website", "https://henk.tech"], ["about", "Sysadmin | AI Entertainment Enthusiast | Game Server Operator | Liberal (as in Liberty) Nationalist (each country has a right to be sovereign and should not impose their will on other countries)\r\n- There is only a paradox if you don't admit it\r\n\r\nSee me post with a really long address on mastodon? That's a bridge. My real profile is : https://ditto.pub/@henk.tech\n\nMy webhost blocks some requests behind proof of work, if my NIP-05 errors for you then you can verify it manually. I unfortunately can't disable this."], ["nip05", "Henk.Tech"], ["client", "Amethyst"], ["banner", "https://turbo.henk.tech/avatar/BannerHenky.png"]]"#####;

    #[test]
    fn a_save_keeps_every_key_and_tag_another_client_wrote() {
        let before = henky();
        let edit = Kind0Edit { about: "new bio", ..Default::default() };
        let after = edit_kind0(before.clone(), &edit);

        assert_eq!(after.content.get("about"), Some(&serde_json::json!("new bio")));
        for (key, value) in &before.content {
            if key != "about" {
                assert_eq!(after.content.get(key), Some(value), "{key} is carried verbatim");
            }
        }
        let emoji = |k: &OwnKind0| k.tags.iter().filter(|t| t[0] == "emoji").cloned().collect::<Vec<_>>();
        assert!(!emoji(&before).is_empty());
        assert_eq!(emoji(&after), emoji(&before), "the name's custom emoji survive");
        assert!(names_vector(&after.tags));
        assert_eq!(after.tags.len(), before.tags.iter().filter(|t| t[0] != "client").count() + 1);
    }

    #[test]
    fn our_client_tag_replaces_another_clients_and_is_never_doubled() {
        let other = kind0(r#"{"name":"a"}"#, &[&["client", "Amethyst"], &["i", "github:a", "proof"]]);
        let saved = edit_kind0(other, &Kind0Edit::default());
        assert_eq!(saved.tags, vec![vec!["i".to_string(), "github:a".into(), "proof".into()], vec!["client".into(), "vector".into()]]);
        let again = edit_kind0(saved.clone(), &Kind0Edit::default());
        assert_eq!(again.tags, saved.tags);
    }

    #[test]
    fn a_profile_vector_reads_oddly_still_shows_what_it_can() {
        let odd = kind0(r#"{"name":"a","website":42,"about":["x"],"fields":[["k","v"]]}"#, &[]);
        let view = metadata_view(&odd.content);
        assert_eq!(view.name.as_deref(), Some("a"));
        assert_eq!(view.website, None);
        // Edited, the odd values go back out exactly as they came.
        let saved = edit_kind0(odd, &Kind0Edit { name: "b", ..Default::default() });
        assert_eq!(saved.content.get("website"), Some(&serde_json::json!(42)));
        assert_eq!(saved.content.get("fields"), Some(&serde_json::json!([["k", "v"]])));
    }

    #[test]
    fn a_blank_banner_removes_it_and_an_empty_one_keeps_it() {
        let mut p = Profile::new();
        p.from_metadata(Metadata::from_json(r#"{"name":"a","banner":"https://x/b.png"}"#).unwrap());
        assert_eq!(p.banner(), "https://x/b.png");

        assert_eq!(own_metadata(&p, "", "", "", "", false).banner.as_deref(), Some("https://x/b.png"));
        let removed = own_metadata(&p, "", "", " ", "", false);
        assert_eq!(removed.banner, None);
        let remote = kind0(r#"{"name":"a","banner":"https://x/b.png","website":"https://w"}"#, &[]);
        let kept = edit_kind0(remote.clone(), &Kind0Edit::default());
        assert_eq!(kept.content.get("banner"), Some(&serde_json::json!("https://x/b.png")));
        let edited = edit_kind0(remote, &Kind0Edit { banner: " ", ..Default::default() });
        assert!(!edited.content.contains_key("banner"));
        assert_eq!(edited.content.get("website"), Some(&serde_json::json!("https://w")), "every other key stands");

        assert!(p.from_metadata(removed), "a kind-0 without its banner clears it");
        assert_eq!(p.banner(), "");
    }

    #[test]
    fn an_own_profile_without_consent_publishes_no_key() {
        let mut p = consenting_profile();
        p.flags.set_stream_consent(false);
        let meta = own_metadata(&p, "", "", "", "about", true);
        assert!(!meta.custom.contains_key(crate::profile::STREAM_CONSENT_KEY));
        assert_eq!(meta.custom.get("bot"), Some(&serde_json::Value::Bool(true)));
    }

    #[test]
    fn a_fresh_device_with_no_relay_copy_never_publishes_a_blank_profile() {
        assert!(consent_plan(None, &Profile::default(), true).is_err());
        // With a profile of its own to carry, it publishes that.
        let mut p = consenting_profile();
        p.flags.set_stream_consent(false);
        let Ok(ConsentPlan::Publish(kind0)) = consent_plan(None, &p, true) else { panic!("publishes the local copy") };
        assert!(consents(&kind0.content));
        assert_eq!(kind0.content.get("name"), Some(&serde_json::json!("old")));
        assert!(names_vector(&kind0.tags));
    }

    #[test]
    fn a_consent_change_keeps_every_key_and_tag_the_relay_copy_holds() {
        let remote = kind0(r#"{"name":"r","pronouns":"they","bot":true}"#, &[&["emoji", "r", "https://x/r.png"]]);
        let Ok(ConsentPlan::Publish(on)) = consent_plan(Some(remote), &Profile::default(), true) else {
            panic!("a change is published")
        };
        assert!(consents(&on.content));
        assert_eq!(on.content.get("pronouns"), Some(&serde_json::json!("they")));
        assert_eq!(on.content.get("bot"), Some(&serde_json::json!(true)));
        assert_eq!(on.content.get("name"), Some(&serde_json::json!("r")), "the relay copy wins over the local one");
        assert!(on.tags.contains(&vec!["emoji".to_string(), "r".into(), "https://x/r.png".into()]));

        let Ok(ConsentPlan::Publish(off)) = consent_plan(Some(on), &consenting_profile(), false) else {
            panic!("withdrawing is published")
        };
        assert!(!off.content.contains_key(crate::profile::STREAM_CONSENT_KEY), "off is the absent key");
        assert_eq!(off.content.get("pronouns"), Some(&serde_json::json!("they")));
    }

    #[test]
    fn a_relay_copy_that_already_says_it_publishes_nothing() {
        let remote = kind0(r#"{"name":"r","stream_consent":true}"#, &[]);
        assert!(matches!(consent_plan(Some(remote), &Profile::default(), true), Ok(ConsentPlan::Unchanged(_))));
        let bare = kind0(r#"{"name":"r"}"#, &[]);
        assert!(matches!(consent_plan(Some(bare), &consenting_profile(), false), Ok(ConsentPlan::Unchanged(_))));
    }

    #[test]
    fn an_sdk_edit_of_the_relay_copy_keeps_its_other_fields() {
        let remote = kind0(
            r#"{"name":"old","display_name":"Old","nip05":"a@b.c","lud16":"z@b.c","stream_consent":true,"pronouns":"they"}"#,
            &[],
        );
        let edit = Kind0Edit { name: "new", avatar: "https://x/a.png", bot: true, ..Default::default() };
        let saved = edit_kind0(remote, &edit);
        let meta = metadata_view(&saved.content);
        assert_eq!(meta.name.as_deref(), Some("new"));
        assert_eq!(meta.picture.as_deref(), Some("https://x/a.png"));
        assert_eq!(meta.display_name.as_deref(), Some("Old"));
        assert_eq!(meta.nip05.as_deref(), Some("a@b.c"));
        assert_eq!(meta.lud16.as_deref(), Some("z@b.c"));
        assert!(consents(&saved.content), "consent is not revoked by an edit");
        assert_eq!(saved.content.get("pronouns"), Some(&serde_json::json!("they")));
        assert_eq!(saved.content.get("bot"), Some(&serde_json::json!(true)));
    }

    #[test]
    fn noop_handler_compiles() {
        let handler = NoOpProfileSyncHandler;
        let slim = crate::SlimProfile::default();
        handler.on_profile_fetched(&slim, "", "");
    }
}

/// The profile processor's benchmark, run by `benches/core`: in-crate for the private queue.
#[cfg(feature = "bench")]
#[doc(hidden)]
pub mod bench {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Thread wakeups while the queue sits empty, and how long a user-clicked refresh waits
    /// before the processor picks it up.
    pub fn processor() {
        static UNPARKS: AtomicUsize = AtomicUsize::new(0);
        const IDLE: Duration = Duration::from_secs(20);
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .on_thread_unpark(|| {
                UNPARKS.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();
        rt.block_on(async {
            // spawn-detached: the benchmark's own runtime, no account.
            tokio::spawn(start_profile_sync_processor(Arc::new(NoOpProfileSyncHandler)));
            tokio::time::sleep(Duration::from_millis(50)).await;
            let before = UNPARKS.load(Ordering::Relaxed);
            tokio::time::sleep(IDLE).await;
            let woke = UNPARKS.load(Ordering::Relaxed) - before;
            println!("idle wakeups: {woke} in {IDLE:?} ({:.2}/min)", woke as f64 * 60.0 / IDLE.as_secs_f64());

            let mut waits = Vec::new();
            for i in 0..20u64 {
                tokio::time::sleep(Duration::from_millis(700 + i * 37)).await;
                let npub = format!("npub1bench{i}");
                let t = Instant::now();
                refresh_profile_now(npub.clone());
                while profile_sync_queue().lock().unwrap().last_fetched.get(&npub).is_none() {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
                waits.push(t.elapsed().as_secs_f64() * 1e3);
            }
            waits.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "critical refresh pickup: median {:.1} ms, max {:.1} ms",
                waits[waits.len() / 2],
                waits[waits.len() - 1]
            );
        });
    }
}

#[cfg(test)]
mod request_tests {
    use super::*;
    use crate::chat::Chat;

    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        let account = Keys::generate().public_key().to_bech32().unwrap();
        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        (tmp, guard)
    }

    fn theirs(seed: u8) -> crate::types::Message {
        crate::types::Message { id: format!("{:02x}", seed).repeat(32), content: "hi".into(), at: 1_700_000_000_000 + seed as u64, ..Default::default() }
    }

    #[tokio::test]
    async fn accepting_a_request_releases_its_sender_and_survives_a_reload() {
        let (_tmp, _guard) = init_test_db();
        let peer = Keys::generate().public_key().to_bech32().unwrap();
        {
            let mut guard = STATE.lock().await;
            let state = &mut *guard;
            let mut chat = Chat::new_dm(peer.clone(), &mut state.interner);
            chat.add_message(theirs(1), &mut state.interner);
            state.chats.push(chat);
        }
        assert!(crate::requests::pictures_held(&peer).await, "a stranger's pictures wait");

        accept_chat(peer.clone()).await.unwrap();
        assert!(!crate::requests::pictures_held(&peer).await, "accepted: their pictures may load");

        let row = crate::db::chats::get_all_chats().unwrap().into_iter().find(|c| c.id == peer).expect("chat saved");
        let mut interner = crate::compact::NpubInterner::new();
        let mut reloaded = row.to_chat(&mut interner);
        reloaded.add_message(theirs(2), &mut interner);
        assert!(!reloaded.is_request(), "the acceptance outlives a reload");
    }
}