git-remote-htree 0.2.81

Git remote helper for hashtree - push/pull git repos via nostr and hashtree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
//! Nostr client for publishing and fetching git repository references
//!
//! Uses kind 30064 hashtree root events, while still reading legacy kind 30078 roots:
//! {
//!   "kind": 30064,
//!   "tags": [
//!     ["d", "<repo-name>"],
//!     ["l", "hashtree"]
//!   ],
//!   "content": "<merkle-root-hash>"
//! }
//!
//! The merkle tree contains:
//!   root/
//!     refs/heads/main -> <sha>
//!     refs/tags/v1.0 -> <sha>
//!     objects/<sha1> -> data
//!     objects/<sha2> -> data
//!
//! ## Identity file format
//!
//! The secrets file (`~/.hashtree/keys`) supports multiple signing keys with optional
//! petnames:
//! ```text
//! nsec1... default
//! nsec1... work
//! nsec1... personal
//! ```
//!
//! Or hex format:
//! ```text
//! <64-char-hex> default
//! <64-char-hex> work
//! ```
//!
//! Public read-only aliases can be stored in `~/.hashtree/aliases`:
//! ```text
//! npub1... sirius
//! npub1... coworker
//! ```
//!
//! For compatibility, public aliases in `~/.hashtree/keys` are also accepted.
//!
//! Then use: `htree://work/myrepo` or `htree://npub1.../myrepo`

mod identity;
mod repo_metadata;

use crate::runtime::block_on_result;
use anyhow::{Context, Result};
use futures::{SinkExt, StreamExt};
use hashtree_blossom::BlossomClient;
use hashtree_core::{decode_tree_node, decrypt_chk, Cid, LinkType, TreeNode};
use nostr_sdk::prelude::*;
use serde::Deserialize;
use std::collections::HashMap;
use std::time::Duration;
use tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage};
use tracing::{debug, info, warn};

pub use identity::{
    load_key_lists, load_keys, resolve_identity, resolve_self_identity, StoredKey, StoredKeyLists,
};
use repo_metadata::{
    append_repo_discovery_labels, build_git_repo_list_filter, build_repo_announcement_filter,
    build_repo_event_filter, extract_repo_announcement_euc, latest_repo_announcement_created_at,
    latest_repo_event_created_at, latest_trusted_pr_status_kinds, list_git_repo_announcements,
    next_replaceable_created_at, pick_latest_event, pick_latest_repo_event,
    validate_repo_publish_relays,
};

/// Event kind for hashtree roots.
pub const KIND_HASHTREE_ROOT: u16 = 30064;

/// Legacy event kind for hashtree roots originally stored as NIP-78 app data.
pub const KIND_APP_DATA: u16 = 30078;

/// NIP-34 event kinds
pub const KIND_PULL_REQUEST: u16 = 1618;
pub const KIND_STATUS_OPEN: u16 = 1630;
pub const KIND_STATUS_APPLIED: u16 = 1631;
pub const KIND_STATUS_CLOSED: u16 = 1632;
pub const KIND_STATUS_DRAFT: u16 = 1633;
pub const KIND_REPO_ANNOUNCEMENT: u16 = 30617;

pub fn hashtree_root_kinds() -> Vec<Kind> {
    vec![
        Kind::Custom(KIND_HASHTREE_ROOT),
        Kind::Custom(KIND_APP_DATA),
    ]
}

pub fn is_hashtree_root_kind(kind: Kind) -> bool {
    kind == Kind::Custom(KIND_HASHTREE_ROOT) || kind == Kind::Custom(KIND_APP_DATA)
}

/// Label for hashtree events
pub const LABEL_HASHTREE: &str = "hashtree";
pub const LABEL_GIT: &str = "git";
const IRIS_GIT_WEB_BASE_URL: &str = "https://git.iris.to/#";
const LOCAL_DAEMON_QUERY_TIMEOUT_SECS: u64 = 8;
const REPO_PUBLISH_TIMEOUT: Duration = Duration::from_secs(30);

fn local_daemon_query_timeout(request_timeout_secs: u64, local_daemon_only: bool) -> Duration {
    let timeout_secs = if local_daemon_only {
        request_timeout_secs.max(LOCAL_DAEMON_QUERY_TIMEOUT_SECS)
    } else {
        4
    };
    Duration::from_secs(timeout_secs)
}

/// Pull request status derived from trusted NIP-34 status events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestState {
    Open,
    Applied,
    Closed,
    Draft,
}

impl PullRequestState {
    pub fn as_str(self) -> &'static str {
        match self {
            PullRequestState::Open => "open",
            PullRequestState::Applied => "applied",
            PullRequestState::Closed => "closed",
            PullRequestState::Draft => "draft",
        }
    }

    fn from_status_kind(status_kind: u16) -> Option<Self> {
        match status_kind {
            KIND_STATUS_OPEN => Some(PullRequestState::Open),
            KIND_STATUS_APPLIED => Some(PullRequestState::Applied),
            KIND_STATUS_CLOSED => Some(PullRequestState::Closed),
            KIND_STATUS_DRAFT => Some(PullRequestState::Draft),
            _ => None,
        }
    }

    fn from_latest_status_kind(status_kind: Option<u16>) -> Self {
        status_kind
            .and_then(Self::from_status_kind)
            .unwrap_or(PullRequestState::Open)
    }
}

/// Filter used when listing PRs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PullRequestStateFilter {
    #[default]
    Open,
    Applied,
    Closed,
    Draft,
    All,
}

impl PullRequestStateFilter {
    pub fn as_str(self) -> &'static str {
        match self {
            PullRequestStateFilter::Open => "open",
            PullRequestStateFilter::Applied => "applied",
            PullRequestStateFilter::Closed => "closed",
            PullRequestStateFilter::Draft => "draft",
            PullRequestStateFilter::All => "all",
        }
    }

    fn includes(self, state: PullRequestState) -> bool {
        match self {
            PullRequestStateFilter::All => true,
            PullRequestStateFilter::Open => state == PullRequestState::Open,
            PullRequestStateFilter::Applied => state == PullRequestState::Applied,
            PullRequestStateFilter::Closed => state == PullRequestState::Closed,
            PullRequestStateFilter::Draft => state == PullRequestState::Draft,
        }
    }
}

/// PR metadata used by listing/filtering consumers.
#[derive(Debug, Clone)]
pub struct PullRequestListItem {
    pub event_id: String,
    pub author_pubkey: String,
    pub state: PullRequestState,
    pub subject: Option<String>,
    pub commit_tip: Option<String>,
    pub branch: Option<String>,
    pub target_branch: Option<String>,
    pub created_at: u64,
}

async fn fetch_events_via_raw_relay_query(
    relays: &[String],
    filter: Filter,
    timeout: Duration,
) -> Vec<Event> {
    let request_json = ClientMessage::req(SubscriptionId::generate(), vec![filter]).as_json();
    let mut events_by_id = HashMap::<String, Event>::new();

    for relay_url in relays {
        let relay_events = match tokio::time::timeout(timeout, async {
            let (mut ws, _) = connect_async(relay_url).await?;
            ws.send(WsMessage::Text(request_json.clone())).await?;

            let mut relay_events = Vec::new();
            while let Some(message) = ws.next().await {
                let message = message?;
                let WsMessage::Text(text) = message else {
                    continue;
                };

                match RelayMessage::from_json(text.as_str()) {
                    Ok(RelayMessage::Event { event, .. }) => relay_events.push(event.into_owned()),
                    Ok(RelayMessage::EndOfStoredEvents(_)) => break,
                    Ok(RelayMessage::Closed { message, .. }) => {
                        debug!("Raw relay PR query closed by {}: {}", relay_url, message);
                        break;
                    }
                    Ok(_) => {}
                    Err(err) => {
                        debug!(
                            "Failed to parse raw relay response from {}: {}",
                            relay_url, err
                        );
                    }
                }
            }

            let _ = ws.close(None).await;
            Ok::<Vec<Event>, anyhow::Error>(relay_events)
        })
        .await
        {
            Ok(Ok(events)) => events,
            Ok(Err(err)) => {
                debug!("Raw relay PR query failed for {}: {}", relay_url, err);
                continue;
            }
            Err(_) => {
                debug!("Raw relay PR query timed out for {}", relay_url);
                continue;
            }
        };

        for event in relay_events {
            events_by_id.insert(event.id.to_hex(), event);
        }
    }

    events_by_id.into_values().collect()
}

async fn connected_relay_count(client: &Client) -> (usize, usize) {
    let relays = client.relays().await;
    let total = relays.len();
    let mut connected = 0;
    for relay in relays.values() {
        if relay.is_connected() {
            connected += 1;
        }
    }
    (connected, total)
}

async fn wait_for_any_connected_relay(client: &Client, timeout: Duration) -> bool {
    let start = std::time::Instant::now();
    loop {
        if connected_relay_count(client).await.0 > 0 {
            return true;
        }
        if start.elapsed() > timeout {
            return false;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
}

type FetchedRefs = (HashMap<String, String>, Option<String>, Option<[u8; 32]>);

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum RootResolveSource {
    #[default]
    Relay,
    LocalDaemon,
}

#[derive(Debug, Clone)]
struct ResolvedRoot {
    root_hash: Option<String>,
    encryption_key: Option<[u8; 32]>,
    source: Option<RootResolveSource>,
}
use hashtree_config::Config;

/// Result of publishing to relays
#[derive(Debug, Clone)]
pub struct RelayResult {
    /// Relays that were configured
    #[allow(dead_code)]
    pub configured: Vec<String>,
    /// Relays that connected
    pub connected: Vec<String>,
    /// Relays that failed to connect
    pub failed: Vec<String>,
}

/// Optional NIP-34 metadata to publish alongside the htree root event.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RepoAnnouncementOptions {
    /// NIP-34 earliest unique commit. Usually the root commit; forks should keep the source euc.
    pub earliest_unique_commit: Option<String>,
    /// Mark the repo announcement as a personal fork (`["t", "personal-fork"]`).
    pub personal_fork: bool,
    /// Iris/htree extension for showing the exact htree source URL.
    pub forked_from: Option<String>,
}

/// Result of uploading to blossom servers
#[derive(Debug, Clone)]
pub struct BlossomResult {
    /// Servers that were configured
    #[allow(dead_code)]
    pub configured: Vec<String>,
    /// Servers that accepted uploads
    pub succeeded: Vec<String>,
    /// Servers that failed
    pub failed: Vec<String>,
    /// Whether the repo tree is complete in the local hashtree store.
    pub local_complete: bool,
    /// Whether remote replication was incomplete.
    pub degraded: bool,
}

/// Nostr client for git operations
pub struct NostrClient {
    pubkey: String,
    /// nostr-sdk Keys for signing
    keys: Option<Keys>,
    relays: Vec<String>,
    blossom: BlossomClient,
    /// Cached refs from remote
    cached_refs: HashMap<String, HashMap<String, String>>,
    /// Cached root hashes (hashtree SHA256)
    cached_root_hash: HashMap<String, String>,
    /// Cached encryption keys
    cached_encryption_key: HashMap<String, [u8; 32]>,
    /// Source of the cached root hash, used to retry tentative daemon roots via relays.
    cached_root_source: HashMap<String, RootResolveSource>,
    /// URL secret for link-visible repos (#k=<hex>)
    /// If set, encryption keys from nostr are XOR-masked and need unmasking
    url_secret: Option<[u8; 32]>,
    /// Whether this is a private (author-only) repo using NIP-44 encryption
    is_private: bool,
    /// Local htree daemon URL for peer-assisted root discovery
    local_daemon_url: Option<String>,
    /// Require all root and blob reads to use the local daemon.
    local_daemon_only: bool,
    #[cfg(test)]
    forced_fetch_refs_results: std::collections::VecDeque<Result<FetchedRefs, String>>,
}

#[derive(Debug, Clone, Default)]
struct RootEventData {
    root_hash: String,
    encryption_key: Option<[u8; 32]>,
    key_tag_name: Option<String>,
    self_encrypted_ciphertext: Option<String>,
    source: RootResolveSource,
    daemon_source: Option<String>,
    event_created_at: Option<u64>,
    event_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct DaemonResolveResponse {
    hash: Option<String>,
    #[serde(default)]
    cid: Option<String>,
    #[serde(default, rename = "key_tag")]
    key: Option<String>,
    #[serde(default, rename = "encryptedKey")]
    encrypted_key: Option<String>,
    #[serde(default, rename = "selfEncryptedKey")]
    self_encrypted_key: Option<String>,
    #[serde(default)]
    source: Option<String>,
    #[serde(default)]
    created_at: Option<u64>,
    #[serde(default)]
    event_id: Option<String>,
}

impl NostrClient {
    /// Create a new client with pubkey, optional secret key, url secret, is_private flag, and config
    pub fn new(
        pubkey: &str,
        secret_key: Option<String>,
        url_secret: Option<[u8; 32]>,
        is_private: bool,
        config: &Config,
    ) -> Result<Self> {
        let local_daemon_only = std::env::var("HTREE_LOCAL_DAEMON_ONLY")
            .map(|value| {
                !matches!(
                    value.trim().to_ascii_lowercase().as_str(),
                    "" | "0" | "false" | "no" | "off"
                )
            })
            .unwrap_or(false);
        Self::new_with_local_daemon_only(
            pubkey,
            secret_key,
            url_secret,
            is_private,
            config,
            local_daemon_only,
        )
    }

    fn new_with_local_daemon_only(
        pubkey: &str,
        secret_key: Option<String>,
        url_secret: Option<[u8; 32]>,
        is_private: bool,
        config: &Config,
        local_daemon_only: bool,
    ) -> Result<Self> {
        // Ensure rustls has a process-wide crypto provider even when used as a library (tests).
        let _ = rustls::crypto::ring::default_provider().install_default();

        // Use provided secret, or try environment variable
        let secret_key = secret_key.or_else(|| std::env::var("NOSTR_SECRET_KEY").ok());

        // Create nostr-sdk Keys if we have a secret
        let keys = if let Some(ref secret_hex) = secret_key {
            let secret_bytes = hex::decode(secret_hex).context("Invalid secret key hex")?;
            let secret = nostr::SecretKey::from_slice(&secret_bytes)
                .map_err(|e| anyhow::anyhow!("Invalid secret key: {}", e))?;
            Some(Keys::new(secret))
        } else {
            None
        };

        let detected_local_daemon =
            hashtree_config::detect_local_daemon_url(Some(config.server.bind_address.as_str()));
        let local_daemon_url = detected_local_daemon.clone().or_else(|| {
            config
                .blossom
                .read_servers
                .iter()
                .find(|url| {
                    url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:")
                })
                .cloned()
        });
        if local_daemon_only && local_daemon_url.is_none() {
            anyhow::bail!(
                "HTREE_LOCAL_DAEMON_ONLY requires a running local htree daemon at {}",
                config.server.bind_address
            );
        }

        // Create BlossomClient (needs keys for upload auth) from the resolved
        // config passed by the helper instead of reloading defaults from disk.
        let blossom_keys = keys.clone().unwrap_or_else(Keys::generate);
        let mut read_servers = if local_daemon_only {
            vec![local_daemon_url.clone().expect("checked above")]
        } else {
            config.blossom.all_read_servers()
        };
        if let Some(local_url) = detected_local_daemon {
            if !read_servers.iter().any(|server| server == &local_url) {
                read_servers.insert(0, local_url);
            }
        }
        let write_servers = if local_daemon_only {
            vec![local_daemon_url.clone().expect("checked above")]
        } else {
            config.blossom.all_write_servers()
        };
        let blossom = BlossomClient::new_empty(blossom_keys)
            .with_read_servers(read_servers)
            .with_write_servers(write_servers)
            .with_timeout(Duration::from_secs(120));

        tracing::info!(
            "BlossomClient created with read_servers: {:?}, write_servers: {:?}",
            blossom.read_servers(),
            blossom.write_servers()
        );

        let relays = if local_daemon_only {
            Vec::new()
        } else {
            hashtree_config::resolve_relays(
                &config.nostr.relays,
                Some(config.server.bind_address.as_str()),
            )
        };

        Ok(Self {
            pubkey: pubkey.to_string(),
            keys,
            relays,
            blossom,
            cached_refs: HashMap::new(),
            cached_root_hash: HashMap::new(),
            cached_encryption_key: HashMap::new(),
            cached_root_source: HashMap::new(),
            url_secret,
            is_private,
            local_daemon_url,
            local_daemon_only,
            #[cfg(test)]
            forced_fetch_refs_results: std::collections::VecDeque::new(),
        })
    }

    #[cfg(test)]
    pub(crate) fn force_fetch_refs_error_for_test(&mut self, message: impl Into<String>) {
        self.forced_fetch_refs_results
            .push_back(Err(message.into()));
    }

    #[cfg(test)]
    pub(crate) fn force_fetch_refs_success_for_test(
        &mut self,
        refs: HashMap<String, String>,
        root_hash: Option<String>,
        encryption_key: Option<[u8; 32]>,
    ) {
        self.forced_fetch_refs_results
            .push_back(Ok((refs, root_hash, encryption_key)));
    }

    #[cfg(test)]
    pub(crate) fn cache_root_for_test(
        &mut self,
        repo_name: &str,
        root_hash: String,
        encryption_key: Option<[u8; 32]>,
    ) {
        self.cached_root_hash
            .insert(repo_name.to_string(), root_hash);
        if let Some(key) = encryption_key {
            self.cached_encryption_key
                .insert(repo_name.to_string(), key);
        } else {
            self.cached_encryption_key.remove(repo_name);
        }
        self.cached_root_source
            .insert(repo_name.to_string(), RootResolveSource::Relay);
    }

    #[cfg(test)]
    fn pop_forced_fetch_refs_result(&mut self, repo_name: &str) -> Option<Result<FetchedRefs>> {
        self.forced_fetch_refs_results
            .pop_front()
            .map(|result| match result {
                Ok((refs, root_hash, encryption_key)) => {
                    if let Some(root) = &root_hash {
                        self.cached_root_hash
                            .insert(repo_name.to_string(), root.clone());
                    } else {
                        self.cached_root_hash.remove(repo_name);
                    }
                    if let Some(key) = encryption_key {
                        self.cached_encryption_key
                            .insert(repo_name.to_string(), key);
                    } else {
                        self.cached_encryption_key.remove(repo_name);
                    }
                    self.cached_root_source
                        .insert(repo_name.to_string(), RootResolveSource::Relay);
                    self.cached_refs.insert(repo_name.to_string(), refs.clone());
                    Ok((refs, root_hash, encryption_key))
                }
                Err(message) => Err(anyhow::anyhow!(message)),
            })
    }

    fn format_repo_author(pubkey_hex: &str) -> String {
        PublicKey::from_hex(pubkey_hex)
            .ok()
            .and_then(|pk| pk.to_bech32().ok())
            .unwrap_or_else(|| pubkey_hex.to_string())
    }

    fn daemon_pubkey_identifier(&self) -> String {
        Self::format_repo_author(&self.pubkey)
    }

    /// Check if we can sign (have secret key for this pubkey)
    #[allow(dead_code)]
    pub fn can_sign(&self) -> bool {
        self.keys.is_some()
    }

    pub fn list_repos(&self) -> Result<Vec<String>> {
        block_on_result(self.list_repos_async())
    }

    pub async fn list_repos_async(&self) -> Result<Vec<String>> {
        let client = Client::default();

        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                warn!("Failed to add relay {}: {}", relay, e);
            }
        }
        client.connect().await;

        if !wait_for_any_connected_relay(&client, Duration::from_secs(2)).await {
            let _ = client.disconnect().await;
            return Err(anyhow::anyhow!(
                "Failed to connect to any relay while listing repos"
            ));
        }

        let author = PublicKey::from_hex(&self.pubkey)
            .map_err(|e| anyhow::anyhow!("Invalid pubkey: {}", e))?;
        let filter = build_git_repo_list_filter(author);

        let events = match tokio::time::timeout(
            Duration::from_secs(3),
            client.fetch_events(filter, Duration::from_secs(3)),
        )
        .await
        {
            Ok(Ok(events)) => events,
            Ok(Err(e)) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!(
                    "Failed to fetch git repo events from relays: {}",
                    e
                ));
            }
            Err(_) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!(
                    "Timed out fetching git repo events from relays"
                ));
            }
        };

        let _ = client.disconnect().await;
        let events = events.to_vec();

        Ok(list_git_repo_announcements(&events)
            .into_iter()
            .map(|repo| repo.repo_name)
            .collect())
    }

    /// Fetch refs for a repository from nostr
    /// Returns refs parsed from the hashtree at the root hash
    pub fn fetch_refs(&mut self, repo_name: &str) -> Result<HashMap<String, String>> {
        #[cfg(test)]
        if let Some(result) = self.pop_forced_fetch_refs_result(repo_name) {
            let (refs, _, _) = result?;
            return Ok(refs);
        }

        let (refs, _, _) = self.fetch_refs_with_timeout(repo_name, 10)?;
        Ok(refs)
    }

    /// Fetch refs with a quick timeout (3s) for push operations
    /// Returns empty if timeout - allows push to proceed
    #[allow(dead_code)]
    pub fn fetch_refs_quick(&mut self, repo_name: &str) -> Result<HashMap<String, String>> {
        let (refs, _, _) = self.fetch_refs_with_timeout(repo_name, 3)?;
        Ok(refs)
    }

    /// Fetch refs and root hash info from nostr
    /// Returns (refs, root_hash, encryption_key)
    #[allow(dead_code)]
    pub fn fetch_refs_with_root(&mut self, repo_name: &str) -> Result<FetchedRefs> {
        #[cfg(test)]
        if let Some(result) = self.pop_forced_fetch_refs_result(repo_name) {
            return result;
        }

        self.fetch_refs_with_timeout(repo_name, 10)
    }

    pub(crate) fn refetch_refs_without_local_daemon(
        &mut self,
        repo_name: &str,
        timeout_secs: u64,
    ) -> Result<FetchedRefs> {
        self.clear_cached_remote_state(repo_name);
        self.fetch_refs_with_timeout_uncached(repo_name, timeout_secs, false)
    }

    fn clear_cached_remote_state(&mut self, repo_name: &str) {
        self.cached_refs.remove(repo_name);
        self.cached_root_hash.remove(repo_name);
        self.cached_encryption_key.remove(repo_name);
        self.cached_root_source.remove(repo_name);
    }

    fn cache_resolved_root(&mut self, repo_name: &str, resolved: &ResolvedRoot) {
        if let Some(ref root) = resolved.root_hash {
            self.cached_root_hash
                .insert(repo_name.to_string(), root.clone());
        } else {
            self.cached_root_hash.remove(repo_name);
        }

        if let Some(key) = resolved.encryption_key {
            self.cached_encryption_key
                .insert(repo_name.to_string(), key);
        } else {
            self.cached_encryption_key.remove(repo_name);
        }

        if let Some(source) = resolved.source {
            self.cached_root_source
                .insert(repo_name.to_string(), source);
        } else {
            self.cached_root_source.remove(repo_name);
        }
    }

    /// Fetch refs with configurable timeout
    fn fetch_refs_with_timeout(
        &mut self,
        repo_name: &str,
        timeout_secs: u64,
    ) -> Result<FetchedRefs> {
        debug!(
            "Fetching refs for {} from {} (timeout {}s)",
            repo_name, self.pubkey, timeout_secs
        );

        // Check cache first
        if let Some(refs) = self.cached_refs.get(repo_name) {
            let root = self.cached_root_hash.get(repo_name).cloned();
            let key = self.cached_encryption_key.get(repo_name).cloned();
            return Ok((refs.clone(), root, key));
        }

        self.fetch_refs_with_timeout_uncached(repo_name, timeout_secs, true)
    }

    fn fetch_refs_with_timeout_uncached(
        &mut self,
        repo_name: &str,
        timeout_secs: u64,
        allow_local_daemon: bool,
    ) -> Result<FetchedRefs> {
        let resolved = block_on_result(self.resolve_root_async_with_timeout(
            repo_name,
            timeout_secs,
            allow_local_daemon,
        ))?;

        match self.fetch_refs_for_resolved_root(repo_name, &resolved) {
            Ok(fetched) => Ok(fetched),
            Err(err)
                if resolved.source == Some(RootResolveSource::LocalDaemon)
                    && allow_local_daemon
                    && self.local_daemon_only =>
            {
                Err(err).with_context(|| {
                    format!(
                        "local-daemon-only fetch for {repo_name} failed; relay/Blossom fallback disabled"
                    )
                })
            }
            Err(err)
                if resolved.source == Some(RootResolveSource::LocalDaemon)
                    && allow_local_daemon
                    && !self.local_daemon_only =>
            {
                warn!(
                    "Local daemon root for {} could not be read as a valid git tree: {}. Retrying via relays.",
                    repo_name, err
                );
                self.clear_cached_remote_state(repo_name);
                self.fetch_refs_with_timeout_uncached(repo_name, timeout_secs, false)
            }
            Err(err) => Err(err),
        }
    }

    fn fetch_refs_for_resolved_root(
        &mut self,
        repo_name: &str,
        resolved: &ResolvedRoot,
    ) -> Result<FetchedRefs> {
        if resolved.source != Some(RootResolveSource::LocalDaemon) {
            self.cache_resolved_root(repo_name, resolved);
        }

        let refs = if let Some(ref root) = resolved.root_hash {
            block_on_result(self.fetch_refs_from_hashtree(root, resolved.encryption_key.as_ref()))?
        } else {
            HashMap::new()
        };

        self.cache_resolved_root(repo_name, resolved);
        self.cached_refs.insert(repo_name.to_string(), refs.clone());
        Ok((refs, resolved.root_hash.clone(), resolved.encryption_key))
    }

    fn parse_root_event_data_from_event(event: &Event) -> RootEventData {
        let root_hash = event
            .tags
            .iter()
            .find(|t| t.as_slice().len() >= 2 && t.as_slice()[0].as_str() == "hash")
            .map(|t| t.as_slice()[1].to_string())
            .unwrap_or_else(|| event.content.to_string());

        let (encryption_key, key_tag_name, self_encrypted_ciphertext) = event
            .tags
            .iter()
            .find_map(|t| {
                let slice = t.as_slice();
                if slice.len() < 2 {
                    return None;
                }
                let tag_name = slice[0].as_str();
                let tag_value = slice[1].to_string();
                if tag_name == "selfEncryptedKey" {
                    return Some((None, Some(tag_name.to_string()), Some(tag_value)));
                }
                if tag_name == "key" || tag_name == "encryptedKey" {
                    if let Ok(bytes) = hex::decode(&tag_value) {
                        if bytes.len() == 32 {
                            let mut key = [0u8; 32];
                            key.copy_from_slice(&bytes);
                            return Some((Some(key), Some(tag_name.to_string()), None));
                        }
                    }
                }
                None
            })
            .unwrap_or((None, None, None));

        RootEventData {
            root_hash,
            encryption_key,
            key_tag_name,
            self_encrypted_ciphertext,
            source: RootResolveSource::Relay,
            daemon_source: None,
            event_created_at: Some(event.created_at.as_secs()),
            event_id: Some(event.id.to_hex()),
        }
    }

    fn parse_daemon_response_to_root_data(
        response: DaemonResolveResponse,
    ) -> Option<RootEventData> {
        let parsed_cid = response.cid.as_deref().and_then(|cid| Cid::parse(cid).ok());
        let daemon_source = response.source.clone();
        let event_created_at = response.created_at;
        let event_id = response.event_id.clone();
        let root_hash = response
            .hash
            .or_else(|| parsed_cid.as_ref().map(|cid| hex::encode(cid.hash)))?;
        if root_hash.is_empty() {
            return None;
        }

        let mut data = RootEventData {
            root_hash,
            encryption_key: parsed_cid.and_then(|cid| cid.key),
            key_tag_name: None,
            self_encrypted_ciphertext: None,
            source: RootResolveSource::LocalDaemon,
            daemon_source,
            event_created_at,
            event_id,
        };

        if let Some(ciphertext) = response.self_encrypted_key {
            data.key_tag_name = Some("selfEncryptedKey".to_string());
            data.self_encrypted_ciphertext = Some(ciphertext);
            return Some(data);
        }

        let (tag_name, tag_value) = if let Some(v) = response.encrypted_key {
            ("encryptedKey", v)
        } else if let Some(v) = response.key {
            ("key", v)
        } else {
            return Some(data);
        };

        if let Ok(bytes) = hex::decode(&tag_value) {
            if bytes.len() == 32 {
                let mut key = [0u8; 32];
                key.copy_from_slice(&bytes);
                data.encryption_key = Some(key);
                data.key_tag_name = Some(tag_name.to_string());
            }
        }

        Some(data)
    }

    async fn fetch_root_from_local_daemon(
        &self,
        repo_name: &str,
        timeout: Duration,
    ) -> Option<RootEventData> {
        let base = self.local_daemon_url.as_ref()?;
        let pubkey = self.daemon_pubkey_identifier();
        let refresh = if self.local_daemon_only {
            ""
        } else {
            "?refresh=1"
        };
        let url = format!(
            "{}/api/nostr/resolve/{}/{}{}",
            base.trim_end_matches('/'),
            pubkey,
            repo_name,
            refresh,
        );

        let client = reqwest::Client::builder().timeout(timeout).build().ok()?;
        let response = client.get(&url).send().await.ok()?;
        if !response.status().is_success() {
            return None;
        }

        let payload: DaemonResolveResponse = response.json().await.ok()?;
        let source = payload
            .source
            .clone()
            .unwrap_or_else(|| "unknown".to_string());
        let parsed = Self::parse_daemon_response_to_root_data(payload)?;
        debug!(
            "Resolved repo {} via local daemon source={}",
            repo_name, source
        );
        Some(parsed)
    }

    fn daemon_root_needs_relay_confirmation(data: &RootEventData) -> bool {
        if data.source != RootResolveSource::LocalDaemon {
            return false;
        }

        !matches!(data.daemon_source.as_deref(), Some("nostr-relay" | "nostr"))
    }

    fn root_event_is_newer(left: &RootEventData, right: &RootEventData) -> bool {
        match (left.event_created_at, right.event_created_at) {
            (Some(left_time), Some(right_time)) => {
                (left_time, left.event_id.as_deref().unwrap_or(""))
                    > (right_time, right.event_id.as_deref().unwrap_or(""))
            }
            (Some(_), None) => true,
            _ => false,
        }
    }

    fn choose_newer_root_data(fallback: RootEventData, relay: RootEventData) -> RootEventData {
        if Self::root_event_is_newer(&fallback, &relay) {
            fallback
        } else {
            relay
        }
    }

    async fn cache_public_root_in_local_daemon(
        &self,
        repo_name: &str,
        root_hash: &str,
        encryption_key: Option<(&[u8; 32], bool, bool)>,
    ) {
        let Some(base) = self.local_daemon_url.as_ref() else {
            return;
        };

        match encryption_key {
            Some((_key, false, false)) => {}
            Some((_key, _is_link_visible, _is_self_private)) => return,
            None => {}
        }

        let url = format!("{}/api/cache-tree-root", base.trim_end_matches('/'));
        let pubkey = self.daemon_pubkey_identifier();
        let payload = serde_json::json!({
            "npub": pubkey,
            "treeName": repo_name,
            "hash": root_hash,
            "visibility": "public",
        });

        let client = match reqwest::Client::builder()
            .timeout(Duration::from_secs(2))
            .build()
        {
            Ok(client) => client,
            Err(err) => {
                debug!("Could not build local daemon cache client: {}", err);
                return;
            }
        };

        match client.post(url).json(&payload).send().await {
            Ok(response) if response.status().is_success() => {
                debug!("Cached repo root for {} in local daemon", repo_name);
            }
            Ok(response) => {
                debug!(
                    "Local daemon root cache returned status {} for {}",
                    response.status(),
                    repo_name
                );
            }
            Err(err) => {
                debug!("Could not cache repo root in local daemon: {}", err);
            }
        }
    }

    async fn resolve_root_async_with_timeout(
        &self,
        repo_name: &str,
        timeout_secs: u64,
        allow_local_daemon: bool,
    ) -> Result<ResolvedRoot> {
        // The daemon gathers verified observations for its own bounded window. In local-only
        // mode the HTTP client must outlive that window; Nostr EOSE is not a completeness signal.
        let local_daemon_timeout = local_daemon_query_timeout(timeout_secs, self.local_daemon_only);
        if self.local_daemon_only {
            if !allow_local_daemon {
                anyhow::bail!(
                    "local-daemon-only root lookup for {repo_name} failed; relay fallback disabled"
                );
            }
            let root_data = self
                .fetch_root_from_local_daemon(repo_name, local_daemon_timeout)
                .await
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "local-daemon-only root lookup returned no root for {repo_name}; relay fallback disabled"
                    )
                })?;
            return self.finish_resolved_root(repo_name, root_data);
        }

        // Create nostr-sdk client
        let client = Client::default();

        // Add relays
        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                warn!("Failed to add relay {}: {}", relay, e);
            }
        }

        // Connect to relays - this starts async connection
        client.connect().await;

        let connect_timeout = Duration::from_secs(2);
        let query_timeout = Duration::from_secs(timeout_secs.saturating_sub(2).max(3));
        let retry_delay = Duration::from_millis(300);
        let max_attempts = 2;

        let start = std::time::Instant::now();

        // Build filter for hashtree root events from this author with matching d-tag
        let author = PublicKey::from_hex(&self.pubkey)
            .map_err(|e| anyhow::anyhow!("Invalid pubkey: {}", e))?;

        let filter = build_repo_event_filter(author, repo_name);

        debug!("Querying relays for repo {} events", repo_name);

        let mut root_data = None;
        let mut daemon_fallback: Option<RootEventData> = None;
        for attempt in 1..=max_attempts {
            if allow_local_daemon {
                if let Some(data) = self
                    .fetch_root_from_local_daemon(repo_name, local_daemon_timeout)
                    .await
                {
                    if Self::daemon_root_needs_relay_confirmation(&data) {
                        debug!(
                            "Local daemon resolved {} via {}; checking relays for fresher root",
                            repo_name,
                            data.daemon_source.as_deref().unwrap_or("unknown")
                        );
                        daemon_fallback = Some(data);
                    } else {
                        root_data = Some(data);
                        break;
                    }
                }
            }

            if !allow_local_daemon && attempt == 1 {
                debug!(
                    "Skipping local daemon while resolving {} because relay retry was requested",
                    repo_name
                );
            }

            if allow_local_daemon && daemon_fallback.is_none() {
                debug!(
                    "Local daemon did not resolve {}; querying relays",
                    repo_name
                );
            }

            // Wait for at least one relay to connect (quick timeout - break immediately when one
            // connects). We retry once because relays and the local daemon can both lag briefly.
            let connect_start = std::time::Instant::now();
            let mut last_log = std::time::Instant::now();
            let mut has_connected_relay = false;
            loop {
                let (connected, total) = connected_relay_count(&client).await;
                if connected > 0 {
                    debug!(
                        "Connected to {}/{} relay(s) in {:?} (attempt {}/{})",
                        connected,
                        total,
                        start.elapsed(),
                        attempt,
                        max_attempts
                    );
                    has_connected_relay = true;
                    break;
                }
                if last_log.elapsed() > Duration::from_millis(500) {
                    debug!(
                        "Connecting to relays... (0/{} after {:?}, attempt {}/{})",
                        total,
                        start.elapsed(),
                        attempt,
                        max_attempts
                    );
                    last_log = std::time::Instant::now();
                }
                if connect_start.elapsed() > connect_timeout {
                    debug!(
                        "Timeout waiting for relay connections - continuing with local-daemon fallback"
                    );
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }

            // Query with relay-level timeout.
            // Using `EventSource::relays(Some(...))` preserves partial results from responsive
            // relays instead of discarding everything when one relay stalls.
            if !has_connected_relay {
                if let Some(data) = daemon_fallback.take() {
                    debug!(
                        "Using local daemon root for {} because no relay connected",
                        repo_name
                    );
                    root_data = Some(data);
                    break;
                }
            }

            let events = if has_connected_relay {
                match client.fetch_events(filter.clone(), query_timeout).await {
                    Ok(events) => events.to_vec(),
                    Err(e) => {
                        warn!("Failed to fetch events: {}", e);
                        vec![]
                    }
                }
            } else {
                vec![]
            };

            debug!(
                "Got {} events from relays on attempt {}/{}",
                events.len(),
                attempt,
                max_attempts
            );
            let relay_event = pick_latest_repo_event(events.iter(), repo_name);

            if let Some(event) = relay_event {
                debug!(
                    "Found relay event with root hash: {}",
                    &event.content[..12.min(event.content.len())]
                );
                let relay_data = Self::parse_root_event_data_from_event(event);
                root_data = Some(match daemon_fallback.take() {
                    Some(fallback) => Self::choose_newer_root_data(fallback, relay_data),
                    None => relay_data,
                });
                break;
            }

            if attempt < max_attempts {
                debug!(
                    "No relay hashtree event found for {} on attempt {}/{}; retrying",
                    repo_name, attempt, max_attempts
                );
                tokio::time::sleep(retry_delay).await;
            } else if let Some(data) = daemon_fallback.take() {
                debug!(
                    "Using local daemon root for {} after relay lookup returned no event",
                    repo_name
                );
                root_data = Some(data);
                break;
            }
        }

        // Disconnect
        let _ = client.disconnect().await;

        let root_data = match root_data {
            Some(data) => data,
            None => {
                anyhow::bail!(
                    "Repository '{}' not found (no hashtree event published by {})",
                    repo_name,
                    Self::format_repo_author(&self.pubkey)
                );
            }
        };

        self.finish_resolved_root(repo_name, root_data)
    }

    fn finish_resolved_root(
        &self,
        repo_name: &str,
        root_data: RootEventData,
    ) -> Result<ResolvedRoot> {
        let root_hash = root_data.root_hash;

        if root_hash.is_empty() {
            debug!("Empty root hash in event");
            return Ok(ResolvedRoot {
                root_hash: None,
                encryption_key: None,
                source: None,
            });
        }

        let encryption_key = root_data.encryption_key;
        let key_tag_name = root_data.key_tag_name;
        let self_encrypted_ciphertext = root_data.self_encrypted_ciphertext;
        let root_source = root_data.source;

        // Process encryption key based on tag type
        let unmasked_key = match key_tag_name.as_deref() {
            Some("encryptedKey") => {
                // Link-visible: XOR the masked key with url_secret
                if let (Some(masked), Some(secret)) = (encryption_key, self.url_secret) {
                    let mut unmasked = [0u8; 32];
                    for i in 0..32 {
                        unmasked[i] = masked[i] ^ secret[i];
                    }
                    Some(unmasked)
                } else {
                    anyhow::bail!(
                        "This repo is link-visible and requires a secret key.\n\
                         Use: htree://.../{repo_name}#k=<secret>\n\
                         Ask the repo owner for the full URL with the secret."
                    );
                }
            }
            Some("selfEncryptedKey") => {
                // Private: only decrypt if #private is in the URL
                if !self.is_private {
                    anyhow::bail!(
                        "This repo is private (author-only).\n\
                         Use: htree://.../{repo_name}#private\n\
                         Only the author can access this repo."
                    );
                }

                // Decrypt with NIP-44 using our secret key
                if let Some(keys) = &self.keys {
                    if let Some(ciphertext) = self_encrypted_ciphertext {
                        // Decrypt with NIP-44 (encrypted to self)
                        let pubkey = keys.public_key();
                        match nip44::decrypt(keys.secret_key(), &pubkey, &ciphertext) {
                            Ok(key_hex) => {
                                let key_bytes =
                                    hex::decode(&key_hex).context("Invalid decrypted key hex")?;
                                if key_bytes.len() != 32 {
                                    anyhow::bail!("Decrypted key wrong length");
                                }
                                let mut key = [0u8; 32];
                                key.copy_from_slice(&key_bytes);
                                Some(key)
                            }
                            Err(e) => {
                                anyhow::bail!(
                                    "Failed to decrypt private repo: {}\n\
                                     The repo may be corrupted or published with a different key.",
                                    e
                                );
                            }
                        }
                    } else {
                        anyhow::bail!("selfEncryptedKey tag has invalid format");
                    }
                } else {
                    anyhow::bail!(
                        "Cannot access this private repo.\n\
                         Private repos can only be accessed by their author.\n\
                         You don't have the secret key for this repo's owner."
                    );
                }
            }
            Some("key") | None => {
                // Public: use key directly
                encryption_key
            }
            Some(other) => {
                warn!("Unknown key tag type: {}", other);
                encryption_key
            }
        };

        info!(
            "Found root hash {} for {} (encrypted: {}, link_visible: {})",
            &root_hash[..12.min(root_hash.len())],
            repo_name,
            unmasked_key.is_some(),
            self.url_secret.is_some()
        );

        Ok(ResolvedRoot {
            root_hash: Some(root_hash),
            encryption_key: unmasked_key,
            source: Some(root_source),
        })
    }

    /// Decrypt data if encryption key is provided, then decode as tree node
    fn decrypt_and_decode(&self, data: &[u8], key: Option<&[u8; 32]>) -> Result<TreeNode> {
        let decrypted_data: Vec<u8>;
        let data_to_decode = if let Some(k) = key {
            decrypted_data = decrypt_chk(data, k).context("Decryption failed")?;
            &decrypted_data
        } else {
            data
        };

        decode_tree_node(data_to_decode).context("Failed to decode tree node")
    }

    /// Fetch git refs from hashtree structure
    /// Structure: root -> .git/ -> refs/ -> heads/main -> <sha>
    async fn fetch_refs_from_hashtree(
        &self,
        root_hash: &str,
        encryption_key: Option<&[u8; 32]>,
    ) -> Result<HashMap<String, String>> {
        let mut refs = HashMap::new();
        debug!(
            "fetch_refs_from_hashtree: downloading root {}",
            &root_hash[..12]
        );

        // Download root directory from Blossom - propagate errors properly
        let root_data = match self.blossom.download(root_hash).await {
            Ok(data) => {
                debug!("Downloaded {} bytes from blossom", data.len());
                data
            }
            Err(e) => {
                anyhow::bail!(
                    "Failed to download root hash {}: {}",
                    &root_hash[..12.min(root_hash.len())],
                    e
                );
            }
        };

        // Parse root as directory node (decrypt if needed)
        let root_node = self
            .decrypt_and_decode(&root_data, encryption_key)
            .with_context(|| {
                format!(
                    "Failed to decode root node {} (encrypted: {})",
                    &root_hash[..12.min(root_hash.len())],
                    encryption_key.is_some()
                )
            })?;
        debug!("Decoded root node with {} links", root_node.links.len());

        // Find .git directory
        debug!(
            "Root links: {:?}",
            root_node
                .links
                .iter()
                .map(|l| l.name.as_deref())
                .collect::<Vec<_>>()
        );
        let git_link = root_node
            .links
            .iter()
            .find(|l| l.name.as_deref() == Some(".git"));
        let (git_hash, git_key) = match git_link {
            Some(link) => {
                debug!("Found .git link with key: {}", link.key.is_some());
                (hex::encode(link.hash), link.key)
            }
            None => {
                debug!("No .git directory in hashtree root");
                return Ok(refs);
            }
        };

        // Download .git directory
        let git_data = match self.blossom.download(&git_hash).await {
            Ok(data) => data,
            Err(e) => {
                anyhow::bail!(
                    "Failed to download .git directory ({}): {}",
                    &git_hash[..12],
                    e
                );
            }
        };

        let git_node = self
            .decrypt_and_decode(&git_data, git_key.as_ref())
            .with_context(|| {
                format!(
                    "Failed to decode .git directory {} (encrypted: {})",
                    &git_hash[..12.min(git_hash.len())],
                    git_key.is_some()
                )
            })?;
        debug!(
            "Decoded .git node with {} links: {:?}",
            git_node.links.len(),
            git_node
                .links
                .iter()
                .map(|l| l.name.as_deref())
                .collect::<Vec<_>>()
        );

        // Find refs directory
        let refs_link = git_node
            .links
            .iter()
            .find(|l| l.name.as_deref() == Some("refs"));
        let (refs_hash, refs_key) = match refs_link {
            Some(link) => (hex::encode(link.hash), link.key),
            None => {
                debug!("No refs directory in .git");
                return Ok(refs);
            }
        };

        // Download refs directory
        let refs_data =
            self.blossom.download(&refs_hash).await.with_context(|| {
                format!("Failed to download refs directory {}", &refs_hash[..12])
            })?;

        let refs_node = self
            .decrypt_and_decode(&refs_data, refs_key.as_ref())
            .with_context(|| {
                format!(
                    "Failed to decode refs directory {} (encrypted: {})",
                    &refs_hash[..12.min(refs_hash.len())],
                    refs_key.is_some()
                )
            })?;

        // Look for HEAD in .git directory
        if let Some(head_link) = git_node
            .links
            .iter()
            .find(|l| l.name.as_deref() == Some("HEAD"))
        {
            let head_hash = hex::encode(head_link.hash);
            let head_data = self
                .blossom
                .download(&head_hash)
                .await
                .with_context(|| format!("Failed to download HEAD {}", &head_hash[..12]))?;
            // HEAD is a blob, decrypt if needed
            let head_content = if let Some(k) = head_link.key.as_ref() {
                let decrypted = decrypt_chk(&head_data, k)
                    .with_context(|| format!("Failed to decrypt HEAD {}", &head_hash[..12]))?;
                String::from_utf8_lossy(&decrypted).trim().to_string()
            } else {
                String::from_utf8_lossy(&head_data).trim().to_string()
            };
            refs.insert("HEAD".to_string(), head_content);
        }

        // Recursively walk refs/ subdirectories (heads, tags, etc.)
        for subdir_link in &refs_node.links {
            if subdir_link.link_type != LinkType::Dir {
                continue;
            }
            let subdir_name = match &subdir_link.name {
                Some(n) => n.clone(),
                None => continue,
            };
            let subdir_hash = hex::encode(subdir_link.hash);

            self.collect_refs_recursive(
                &subdir_hash,
                subdir_link.key.as_ref(),
                &format!("refs/{}", subdir_name),
                &mut refs,
            )
            .await?;
        }

        debug!("Found {} refs from hashtree", refs.len());
        Ok(refs)
    }

    /// Recursively collect refs from a directory
    async fn collect_refs_recursive(
        &self,
        dir_hash: &str,
        dir_key: Option<&[u8; 32]>,
        prefix: &str,
        refs: &mut HashMap<String, String>,
    ) -> Result<()> {
        let dir_data = self
            .blossom
            .download(dir_hash)
            .await
            .with_context(|| format!("Failed to download refs subtree {}", &dir_hash[..12]))?;

        let dir_node = self
            .decrypt_and_decode(&dir_data, dir_key)
            .with_context(|| {
                format!(
                    "Failed to decode refs subtree {} (encrypted: {})",
                    &dir_hash[..12.min(dir_hash.len())],
                    dir_key.is_some()
                )
            })?;

        for link in &dir_node.links {
            let name = match &link.name {
                Some(n) => n.clone(),
                None => continue,
            };
            let link_hash = hex::encode(link.hash);
            let ref_path = format!("{}/{}", prefix, name);

            if link.link_type == LinkType::Dir {
                // Recurse into subdirectory
                Box::pin(self.collect_refs_recursive(
                    &link_hash,
                    link.key.as_ref(),
                    &ref_path,
                    refs,
                ))
                .await?;
            } else {
                // This is a ref file - read the SHA
                let ref_data = self
                    .blossom
                    .download(&link_hash)
                    .await
                    .with_context(|| format!("Failed to download ref {}", ref_path))?;
                // Decrypt if needed
                let sha = if let Some(k) = link.key.as_ref() {
                    let decrypted = decrypt_chk(&ref_data, k)
                        .with_context(|| format!("Failed to decrypt ref {}", ref_path))?;
                    String::from_utf8_lossy(&decrypted).trim().to_string()
                } else {
                    String::from_utf8_lossy(&ref_data).trim().to_string()
                };
                if !sha.is_empty() {
                    debug!("Found ref {} -> {}", ref_path, sha);
                    refs.insert(ref_path, sha);
                }
            }
        }

        Ok(())
    }

    /// Update a ref in local cache (will be published with publish_repo)
    #[allow(dead_code)]
    pub fn update_ref(&mut self, repo_name: &str, ref_name: &str, sha: &str) -> Result<()> {
        info!("Updating ref {} -> {} for {}", ref_name, sha, repo_name);

        let refs = self.cached_refs.entry(repo_name.to_string()).or_default();
        refs.insert(ref_name.to_string(), sha.to_string());

        Ok(())
    }

    /// Delete a ref from local cache
    pub fn delete_ref(&mut self, repo_name: &str, ref_name: &str) -> Result<()> {
        info!("Deleting ref {} for {}", ref_name, repo_name);

        if let Some(refs) = self.cached_refs.get_mut(repo_name) {
            refs.remove(ref_name);
        }

        Ok(())
    }

    /// Get cached root hash for a repository
    pub fn get_cached_root_hash(&self, repo_name: &str) -> Option<&String> {
        self.cached_root_hash.get(repo_name)
    }

    /// Get cached encryption key for a repository
    pub fn get_cached_encryption_key(&self, repo_name: &str) -> Option<&[u8; 32]> {
        self.cached_encryption_key.get(repo_name)
    }

    pub(crate) fn cached_root_is_from_local_daemon(&self, repo_name: &str) -> bool {
        self.cached_root_source.get(repo_name) == Some(&RootResolveSource::LocalDaemon)
    }

    pub(crate) fn local_daemon_only(&self) -> bool {
        self.local_daemon_only
    }

    /// Get the Blossom client for direct downloads
    pub fn blossom(&self) -> &BlossomClient {
        &self.blossom
    }

    /// Get the configured relay URLs
    pub fn relay_urls(&self) -> Vec<String> {
        self.relays.clone()
    }

    /// Get the public key (hex)
    #[allow(dead_code)]
    pub fn pubkey(&self) -> &str {
        &self.pubkey
    }

    /// Get the public key as npub bech32
    pub fn npub(&self) -> String {
        PublicKey::from_hex(&self.pubkey)
            .ok()
            .and_then(|pk| pk.to_bech32().ok())
            .unwrap_or_else(|| self.pubkey.clone())
    }

    /// Publish repository to nostr as kind 30064 event
    /// Format:
    ///   kind: 30064
    ///   tags: [["d", repo_name], ["l", "hashtree"], ["hash", root_hash], ["key"|"encryptedKey", encryption_key]]
    ///   content: <merkle-root-hash>
    /// Returns: (npub URL, relay result with connected/failed details)
    /// If is_private is true, uses "encryptedKey" tag (XOR masked); otherwise uses "key" tag (plaintext CHK)
    pub fn publish_repo(
        &self,
        repo_name: &str,
        root_hash: &str,
        encryption_key: Option<(&[u8; 32], bool, bool)>,
    ) -> Result<(String, RelayResult)> {
        self.publish_repo_with_announcement(repo_name, root_hash, encryption_key, None)
    }

    pub fn publish_repo_with_announcement(
        &self,
        repo_name: &str,
        root_hash: &str,
        encryption_key: Option<(&[u8; 32], bool, bool)>,
        repo_announcement: Option<RepoAnnouncementOptions>,
    ) -> Result<(String, RelayResult)> {
        let keys = self.keys.as_ref().context(format!(
            "Cannot push: no secret key for {}. You can only push to your own repos.",
            &self.pubkey[..16]
        ))?;

        info!(
            "Publishing repo {} with root hash {} (encrypted: {})",
            repo_name,
            root_hash,
            encryption_key.is_some()
        );

        // Create a new multi-threaded runtime for nostr-sdk which spawns background tasks
        block_on_result(async {
            tokio::time::timeout(
                REPO_PUBLISH_TIMEOUT,
                self.publish_repo_async(
                    keys,
                    repo_name,
                    root_hash,
                    encryption_key,
                    repo_announcement,
                ),
            )
            .await
            .map_err(|_| anyhow::anyhow!("Repository metadata publication timed out"))?
        })
    }

    async fn publish_repo_async(
        &self,
        keys: &Keys,
        repo_name: &str,
        root_hash: &str,
        encryption_key: Option<(&[u8; 32], bool, bool)>,
        repo_announcement: Option<RepoAnnouncementOptions>,
    ) -> Result<(String, RelayResult)> {
        if self.local_daemon_only {
            return self
                .publish_repo_to_local_daemon(keys, repo_name, root_hash, encryption_key)
                .await;
        }

        // Create nostr-sdk client with our keys
        let client = Client::new(keys.clone());

        let configured: Vec<String> = self.relays.clone();
        let mut connected: Vec<String> = Vec::new();
        let mut failed: Vec<String> = Vec::new();

        // Add relays
        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                warn!("Failed to add relay {}: {}", relay, e);
                failed.push(relay.clone());
            }
        }

        // Connect to relays - this starts async connection in background
        client.connect().await;

        // Wait for at least one relay to connect (same pattern as fetch)
        let _ = wait_for_any_connected_relay(&client, Duration::from_secs(3)).await;

        let publish_created_at = next_replaceable_created_at(
            Timestamp::now(),
            latest_repo_event_created_at(
                &client,
                keys.public_key(),
                repo_name,
                Duration::from_secs(2),
            )
            .await,
        );

        // Build event with tags
        let mut tags = vec![
            Tag::custom(TagKind::custom("d"), vec![repo_name.to_string()]),
            Tag::custom(TagKind::custom("l"), vec![LABEL_HASHTREE.to_string()]),
            Tag::custom(TagKind::custom("hash"), vec![root_hash.to_string()]),
        ];

        // Add encryption key if present (required for decryption)
        // Key modes:
        // - selfEncryptedKey: NIP-44 encrypted to self (author-only private)
        // - encryptedKey: XOR masked with URL secret (link-visible)
        // - key: plaintext CHK (public)
        if let Some((key, is_link_visible, is_self_private)) = encryption_key {
            if is_self_private {
                // NIP-44 encrypt to self
                let pubkey = keys.public_key();
                let key_hex = hex::encode(key);
                let encrypted =
                    nip44::encrypt(keys.secret_key(), &pubkey, &key_hex, nip44::Version::V2)
                        .map_err(|e| anyhow::anyhow!("NIP-44 encryption failed: {}", e))?;
                tags.push(Tag::custom(
                    TagKind::custom("selfEncryptedKey"),
                    vec![encrypted],
                ));
            } else if is_link_visible {
                // XOR masked key
                tags.push(Tag::custom(
                    TagKind::custom("encryptedKey"),
                    vec![hex::encode(key)],
                ));
            } else {
                // Public: plaintext CHK
                tags.push(Tag::custom(TagKind::custom("key"), vec![hex::encode(key)]));
            }
        }

        append_repo_discovery_labels(&mut tags, repo_name);

        // Sign the event
        let event = EventBuilder::new(Kind::Custom(KIND_HASHTREE_ROOT), root_hash)
            .tags(tags)
            .custom_created_at(publish_created_at)
            .sign_with_keys(keys)
            .map_err(|e| anyhow::anyhow!("Failed to sign event: {}", e))?;

        let ready_relays = client
            .relays()
            .await
            .into_iter()
            .filter_map(|(url, relay)| relay.is_connected().then_some(url))
            .collect::<Vec<_>>();

        // Send only to relays that connected within the bounded wait above.
        match client.send_event_to(ready_relays, &event).await {
            Ok(output) => {
                // Track which relays confirmed
                for url in output.success.iter() {
                    let url_str = url.to_string();
                    if !connected.contains(&url_str) {
                        connected.push(url_str);
                    }
                }
                // Only mark as failed if we got explicit rejection
                for (url, _err) in output.failed.iter() {
                    let url_str = url.to_string();
                    if !failed.contains(&url_str) && !connected.contains(&url_str) {
                        failed.push(url_str);
                    }
                }
                info!(
                    "Sent event {} to {} relays ({} failed)",
                    output.id(),
                    output.success.len(),
                    output.failed.len()
                );
            }
            Err(e) => {
                warn!("Failed to send event: {}", e);
                // Mark all as failed
                for relay in &self.relays {
                    if !failed.contains(relay) {
                        failed.push(relay.clone());
                    }
                }
            }
        };

        // Build the full htree:// URL with npub
        let npub_url = keys
            .public_key()
            .to_bech32()
            .map(|npub| format!("htree://{}/{}", npub, repo_name))
            .unwrap_or_else(|_| format!("htree://{}/{}", &self.pubkey[..16], repo_name));

        let relay_validation = validate_repo_publish_relays(&configured, &connected);

        if relay_validation.is_ok() {
            if let Some(repo_announcement) = repo_announcement.as_ref() {
                if let Err(err) = self
                    .publish_repo_announcement_async(
                        &client,
                        keys,
                        repo_name,
                        &npub_url,
                        repo_announcement,
                    )
                    .await
                {
                    warn!("Failed to publish NIP-34 repo announcement: {}", err);
                }
            }
        }

        // Disconnect and give time for cleanup
        let _ = client.disconnect().await;
        tokio::time::sleep(Duration::from_millis(50)).await;

        relay_validation?;

        self.cache_public_root_in_local_daemon(repo_name, root_hash, encryption_key)
            .await;

        Ok((
            npub_url,
            RelayResult {
                configured,
                connected,
                failed,
            },
        ))
    }

    async fn publish_repo_to_local_daemon(
        &self,
        keys: &Keys,
        repo_name: &str,
        root_hash: &str,
        encryption_key: Option<(&[u8; 32], bool, bool)>,
    ) -> Result<(String, RelayResult)> {
        let existing_created_at = self
            .fetch_root_from_local_daemon(repo_name, Duration::from_secs(2))
            .await
            .and_then(|root| root.event_created_at)
            .map(Timestamp::from_secs);
        let mut tags = vec![
            Tag::custom(TagKind::custom("d"), vec![repo_name.to_string()]),
            Tag::custom(TagKind::custom("l"), vec![LABEL_HASHTREE.to_string()]),
            Tag::custom(TagKind::custom("hash"), vec![root_hash.to_string()]),
        ];
        if let Some((key, is_link_visible, is_self_private)) = encryption_key {
            if is_self_private {
                let key_hex = hex::encode(key);
                let encrypted = nip44::encrypt(
                    keys.secret_key(),
                    &keys.public_key(),
                    &key_hex,
                    nip44::Version::V2,
                )
                .map_err(|error| anyhow::anyhow!("NIP-44 encryption failed: {error}"))?;
                tags.push(Tag::custom(
                    TagKind::custom("selfEncryptedKey"),
                    vec![encrypted],
                ));
            } else if is_link_visible {
                tags.push(Tag::custom(
                    TagKind::custom("encryptedKey"),
                    vec![hex::encode(key)],
                ));
            } else {
                tags.push(Tag::custom(TagKind::custom("key"), vec![hex::encode(key)]));
            }
        }
        append_repo_discovery_labels(&mut tags, repo_name);
        let event = EventBuilder::new(Kind::Custom(KIND_HASHTREE_ROOT), root_hash)
            .tags(tags)
            .custom_created_at(next_replaceable_created_at(
                Timestamp::now(),
                existing_created_at,
            ))
            .sign_with_keys(keys)
            .map_err(|error| anyhow::anyhow!("Failed to sign event: {error}"))?;
        self.publish_event_to_local_daemon(&event).await?;

        let npub_url = keys
            .public_key()
            .to_bech32()
            .map(|npub| format!("htree://{npub}/{repo_name}"))
            .unwrap_or_else(|_| format!("htree://{}/{repo_name}", &self.pubkey[..16]));
        Ok((
            npub_url,
            RelayResult {
                configured: Vec::new(),
                connected: Vec::new(),
                failed: Vec::new(),
            },
        ))
    }

    async fn publish_event_to_local_daemon(&self, event: &Event) -> Result<()> {
        let base = self.local_daemon_url.as_ref().ok_or_else(|| {
            anyhow::anyhow!("local-daemon-only publication requires a running htree daemon")
        })?;
        let response = reqwest::Client::builder()
            .timeout(Duration::from_secs(4))
            .build()?
            .post(format!("{}/api/nostr/events", base.trim_end_matches('/')))
            .json(event)
            .send()
            .await
            .context("local-daemon-only Nostr publication failed")?;
        if !response.status().is_success() {
            let status = response.status();
            let detail = response.text().await.unwrap_or_default();
            anyhow::bail!(
                "local-daemon-only Nostr publication failed with {status}: {detail}; relay fallback disabled"
            );
        }
        Ok(())
    }

    fn build_repo_announcement_tags(
        repo_name: &str,
        clone_url: &str,
        relays: &[String],
        options: &RepoAnnouncementOptions,
    ) -> Vec<Tag> {
        let mut tags = vec![
            Tag::custom(TagKind::custom("d"), vec![repo_name.to_string()]),
            Tag::custom(TagKind::custom("name"), vec![repo_name.to_string()]),
            Tag::custom(TagKind::custom("clone"), vec![clone_url.to_string()]),
        ];

        if let Some(web_url) = Self::iris_git_web_url_for_htree_clone(clone_url) {
            tags.push(Tag::custom(TagKind::custom("web"), vec![web_url]));
        }

        if !relays.is_empty() {
            tags.push(Tag::custom(TagKind::custom("relays"), relays.to_vec()));
        }

        if let Some(euc) = options
            .earliest_unique_commit
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        {
            tags.push(Tag::custom(
                TagKind::custom("r"),
                vec![euc.to_string(), "euc".to_string()],
            ));
        }

        if options.personal_fork {
            tags.push(Tag::custom(
                TagKind::custom("t"),
                vec!["personal-fork".to_string()],
            ));
        }

        if let Some(forked_from) = options
            .forked_from
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        {
            tags.push(Tag::custom(
                TagKind::custom("forked-from"),
                vec![forked_from.to_string()],
            ));
        }

        tags
    }

    fn iris_git_web_url_for_htree_clone(clone_url: &str) -> Option<String> {
        let raw = clone_url.strip_prefix("htree://")?;
        let path = raw.split('#').next().unwrap_or(raw);
        let (owner, repo_path) = path.split_once('/')?;
        if !owner.starts_with("npub1") || repo_path.is_empty() {
            return None;
        }

        let path = std::iter::once(owner)
            .chain(repo_path.split('/').filter(|segment| !segment.is_empty()))
            .map(Self::percent_encode_path_segment)
            .collect::<Vec<_>>()
            .join("/");

        Some(format!("{IRIS_GIT_WEB_BASE_URL}/{path}"))
    }

    fn percent_encode_path_segment(segment: &str) -> String {
        let mut encoded = String::with_capacity(segment.len());
        for byte in segment.bytes() {
            match byte {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                    encoded.push(byte as char)
                }
                _ => encoded.push_str(&format!("%{byte:02X}")),
            }
        }
        encoded
    }

    async fn publish_repo_announcement_async(
        &self,
        client: &Client,
        keys: &Keys,
        repo_name: &str,
        clone_url: &str,
        options: &RepoAnnouncementOptions,
    ) -> Result<()> {
        let created_at = next_replaceable_created_at(
            Timestamp::now(),
            latest_repo_announcement_created_at(
                client,
                keys.public_key(),
                repo_name,
                Duration::from_secs(2),
            )
            .await,
        );
        let tags = Self::build_repo_announcement_tags(repo_name, clone_url, &self.relays, options);
        let event = EventBuilder::new(Kind::Custom(KIND_REPO_ANNOUNCEMENT), "")
            .tags(tags)
            .custom_created_at(created_at)
            .sign_with_keys(keys)
            .map_err(|e| anyhow::anyhow!("Failed to sign NIP-34 repo announcement: {}", e))?;

        let output = client
            .send_event(&event)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to publish NIP-34 repo announcement: {}", e))?;
        if output.success.is_empty() {
            anyhow::bail!("NIP-34 repo announcement was not confirmed by any relay");
        }

        info!(
            "Published NIP-34 repo announcement {} to {} relays",
            output.id(),
            output.success.len()
        );
        Ok(())
    }

    pub fn fetch_repo_announcement_euc(
        &self,
        owner_pubkey_hex: &str,
        repo_name: &str,
    ) -> Result<Option<String>> {
        block_on_result(self.fetch_repo_announcement_euc_async(owner_pubkey_hex, repo_name))
    }

    async fn fetch_repo_announcement_euc_async(
        &self,
        owner_pubkey_hex: &str,
        repo_name: &str,
    ) -> Result<Option<String>> {
        let owner = PublicKey::from_hex(owner_pubkey_hex)
            .map_err(|e| anyhow::anyhow!("Invalid repo owner pubkey: {}", e))?;
        let client = Client::default();

        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                debug!(
                    "Failed to add relay {} for repo announcement lookup: {}",
                    relay, e
                );
            }
        }
        client.connect().await;

        if !wait_for_any_connected_relay(&client, Duration::from_secs(2)).await {
            let _ = client.disconnect().await;
            return Ok(None);
        }

        let filter = build_repo_announcement_filter(owner, repo_name);
        let events = match tokio::time::timeout(
            Duration::from_secs(3),
            client.fetch_events(filter, Duration::from_secs(3)),
        )
        .await
        {
            Ok(Ok(events)) => events.to_vec(),
            Ok(Err(err)) => {
                debug!(
                    "Failed to fetch NIP-34 repo announcement for {}: {}",
                    repo_name, err
                );
                Vec::new()
            }
            Err(_) => {
                debug!(
                    "Timed out fetching NIP-34 repo announcement for {}",
                    repo_name
                );
                Vec::new()
            }
        };

        let _ = client.disconnect().await;
        Ok(pick_latest_event(events.iter()).and_then(extract_repo_announcement_euc))
    }

    /// Fetch pull requests targeting this repo, filtered by state.
    pub fn fetch_prs(
        &self,
        repo_name: &str,
        state_filter: PullRequestStateFilter,
    ) -> Result<Vec<PullRequestListItem>> {
        block_on_result(self.fetch_prs_async(repo_name, state_filter))
    }

    pub async fn fetch_prs_async(
        &self,
        repo_name: &str,
        state_filter: PullRequestStateFilter,
    ) -> Result<Vec<PullRequestListItem>> {
        let client = Client::default();

        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                warn!("Failed to add relay {}: {}", relay, e);
            }
        }
        client.connect().await;

        // Wait for at least one relay (quick timeout)
        if !wait_for_any_connected_relay(&client, Duration::from_secs(2)).await {
            let _ = client.disconnect().await;
            return Err(anyhow::anyhow!(
                "Failed to connect to any relay while fetching PRs"
            ));
        }

        // Query for kind 1618 PRs targeting this repo
        let repo_address = format!("{}:{}:{}", KIND_REPO_ANNOUNCEMENT, self.pubkey, repo_name);
        let pull_request_filter = Filter::new()
            .kind(Kind::Custom(KIND_PULL_REQUEST))
            .custom_tag(
                SingleLetterTag::lowercase(Alphabet::A),
                repo_address.clone(),
            );

        let mut pr_events = match tokio::time::timeout(
            Duration::from_secs(3),
            client.fetch_events(pull_request_filter.clone(), Duration::from_secs(3)),
        )
        .await
        {
            Ok(Ok(events)) => events.to_vec(),
            Ok(Err(e)) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!(
                    "Failed to fetch PR events from relays: {}",
                    e
                ));
            }
            Err(_) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!("Timed out fetching PR events from relays"));
            }
        };

        if pr_events.is_empty() {
            let fallback_events = fetch_events_via_raw_relay_query(
                &self.relays,
                pull_request_filter,
                Duration::from_secs(3),
            )
            .await;
            if !fallback_events.is_empty() {
                debug!(
                    "Raw relay fallback recovered {} PR event(s) for {}",
                    fallback_events.len(),
                    repo_name
                );
                pr_events = fallback_events;
            }
        }

        if pr_events.is_empty() {
            let _ = client.disconnect().await;
            return Ok(Vec::new());
        }

        // Collect PR event IDs for status query
        let pr_ids: Vec<String> = pr_events.iter().map(|e| e.id.to_hex()).collect();

        // Query for status events referencing these PRs
        let status_event_filter = Filter::new()
            .kinds(vec![
                Kind::Custom(KIND_STATUS_OPEN),
                Kind::Custom(KIND_STATUS_APPLIED),
                Kind::Custom(KIND_STATUS_CLOSED),
                Kind::Custom(KIND_STATUS_DRAFT),
            ])
            .custom_tags(
                SingleLetterTag::lowercase(Alphabet::E),
                pr_ids.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            );

        let mut status_events = match tokio::time::timeout(
            Duration::from_secs(3),
            client.fetch_events(status_event_filter.clone(), Duration::from_secs(3)),
        )
        .await
        {
            Ok(Ok(events)) => events.to_vec(),
            Ok(Err(e)) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!(
                    "Failed to fetch PR status events from relays: {}",
                    e
                ));
            }
            Err(_) => {
                let _ = client.disconnect().await;
                return Err(anyhow::anyhow!(
                    "Timed out fetching PR status events from relays"
                ));
            }
        };

        if status_events.is_empty() {
            let fallback_events = fetch_events_via_raw_relay_query(
                &self.relays,
                status_event_filter,
                Duration::from_secs(3),
            )
            .await;
            if !fallback_events.is_empty() {
                debug!(
                    "Raw relay fallback recovered {} PR status event(s) for {}",
                    fallback_events.len(),
                    repo_name
                );
                status_events = fallback_events;
            }
        }

        let _ = client.disconnect().await;

        // Build map: pr_event_id -> latest trusted status kind
        let latest_status =
            latest_trusted_pr_status_kinds(&pr_events, &status_events, &self.pubkey);

        let mut prs = Vec::new();
        for event in &pr_events {
            let pr_id = event.id.to_hex();
            let state =
                PullRequestState::from_latest_status_kind(latest_status.get(&pr_id).copied());
            if !state_filter.includes(state) {
                continue;
            }

            let mut subject = None;
            let mut commit_tip = None;
            let mut branch = None;
            let mut target_branch = None;

            for tag in event.tags.iter() {
                let slice = tag.as_slice();
                if slice.len() >= 2 {
                    match slice[0].as_str() {
                        "subject" => subject = Some(slice[1].to_string()),
                        "c" => commit_tip = Some(slice[1].to_string()),
                        "branch" => branch = Some(slice[1].to_string()),
                        "target-branch" => target_branch = Some(slice[1].to_string()),
                        _ => {}
                    }
                }
            }

            prs.push(PullRequestListItem {
                event_id: pr_id,
                author_pubkey: event.pubkey.to_hex(),
                state,
                subject,
                commit_tip,
                branch,
                target_branch,
                created_at: event.created_at.as_secs(),
            });
        }

        // Newest first; tie-break by event id for deterministic output.
        prs.sort_by(|left, right| {
            right
                .created_at
                .cmp(&left.created_at)
                .then_with(|| right.event_id.cmp(&left.event_id))
        });

        debug!(
            "Found {} PRs for {} (filter: {:?})",
            prs.len(),
            repo_name,
            state_filter
        );
        Ok(prs)
    }

    /// Publish a kind 1631 (STATUS_APPLIED) event to mark a PR as merged
    pub fn publish_pr_merged_status(
        &self,
        pr_event_id: &str,
        pr_author_pubkey: &str,
    ) -> Result<()> {
        let keys = self
            .keys
            .as_ref()
            .context("Cannot publish status: no secret key")?;

        block_on_result(self.publish_pr_merged_status_async(keys, pr_event_id, pr_author_pubkey))
    }

    async fn publish_pr_merged_status_async(
        &self,
        keys: &Keys,
        pr_event_id: &str,
        pr_author_pubkey: &str,
    ) -> Result<()> {
        let client = Client::new(keys.clone());

        for relay in &self.relays {
            if let Err(e) = client.add_relay(relay).await {
                warn!("Failed to add relay {}: {}", relay, e);
            }
        }
        client.connect().await;

        // Wait for at least one relay
        if !wait_for_any_connected_relay(&client, Duration::from_secs(3)).await {
            anyhow::bail!("Failed to connect to any relay for status publish");
        }

        let tags = vec![
            Tag::custom(TagKind::custom("e"), vec![pr_event_id.to_string()]),
            Tag::custom(TagKind::custom("p"), vec![pr_author_pubkey.to_string()]),
        ];

        let event = EventBuilder::new(Kind::Custom(KIND_STATUS_APPLIED), "")
            .tags(tags)
            .sign_with_keys(keys)
            .map_err(|e| anyhow::anyhow!("Failed to sign status event: {}", e))?;

        let publish_result = match client.send_event(&event).await {
            Ok(output) => {
                if output.success.is_empty() {
                    Err(anyhow::anyhow!(
                        "PR merged status was not confirmed by any relay"
                    ))
                } else {
                    info!(
                        "Published PR merged status to {} relays",
                        output.success.len()
                    );
                    Ok(())
                }
            }
            Err(e) => Err(anyhow::anyhow!("Failed to publish PR merged status: {}", e)),
        };

        let _ = client.disconnect().await;
        tokio::time::sleep(Duration::from_millis(50)).await;
        publish_result
    }

    /// Upload blob to blossom server
    #[allow(dead_code)]
    pub async fn upload_blob(&self, _hash: &str, data: &[u8]) -> Result<String> {
        let hash = self
            .blossom
            .upload(data)
            .await
            .map_err(|e| anyhow::anyhow!("Blossom upload failed: {}", e))?;
        Ok(hash)
    }

    /// Upload blob only if it doesn't exist
    #[allow(dead_code)]
    pub async fn upload_blob_if_missing(&self, data: &[u8]) -> Result<(String, bool)> {
        self.blossom
            .upload_if_missing(data)
            .await
            .map_err(|e| anyhow::anyhow!("Blossom upload failed: {}", e))
    }

    /// Download blob from blossom server
    #[allow(dead_code)]
    pub async fn download_blob(&self, hash: &str) -> Result<Vec<u8>> {
        self.blossom
            .download(hash)
            .await
            .map_err(|e| anyhow::anyhow!("Blossom download failed: {}", e))
    }

    /// Try to download blob, returns None if not found
    #[allow(dead_code)]
    pub async fn try_download_blob(&self, hash: &str) -> Option<Vec<u8>> {
        self.blossom.try_download(hash).await
    }
}

#[cfg(test)]
mod tests;