git-remote-htree 0.2.44

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
#![allow(dead_code)]
//! Shared test infrastructure for git-remote-htree integration tests
//!
//! Provides:
//! - TestRelay: In-memory nostr relay
//! - TestServer: Local blossom server
//! - TestEnv: Test environment with config and keys
//! - Helper functions for creating test repos

use nostr::ToBech32;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use tempfile::TempDir;

/// Minimal in-memory nostr relay for testing with real-time event broadcasting
pub mod test_relay {
    use futures::{SinkExt, StreamExt};
    use std::collections::{HashMap, HashSet};
    use std::net::{TcpListener, TcpStream as StdTcpStream};
    use std::sync::Arc;
    use std::time::{Duration, Instant};
    use tokio::net::TcpStream;
    use tokio::sync::{broadcast, RwLock};
    use tokio_tungstenite::{accept_async, tungstenite::Message};

    /// Stored filter for matching events
    #[derive(Clone)]
    struct StoredFilter {
        sub_id: String,
        kind: Option<u64>,
        kinds: Vec<u64>,
        authors: Vec<String>,
        p_tag: Option<String>, // #p tag for directed messages
        l_tag: Option<String>, // #l tag for hello messages
        a_tag: Option<String>, // #a tag for addressable references
        e_tags: Vec<String>,   // #e tag for event references
        d_tag: Option<String>, // #d tag for replaceable event identifier
    }

    impl StoredFilter {
        fn matches(&self, event: &serde_json::Value) -> bool {
            // Check kind (single)
            if let Some(k) = self.kind {
                if event.get("kind").and_then(|v| v.as_u64()) != Some(k) {
                    return false;
                }
            }

            // Check kinds (multiple)
            if !self.kinds.is_empty() {
                let event_kind = event.get("kind").and_then(|v| v.as_u64()).unwrap_or(0);
                if !self.kinds.contains(&event_kind) {
                    return false;
                }
            }

            // Check authors
            if !self.authors.is_empty() {
                let event_author = event.get("pubkey").and_then(|v| v.as_str()).unwrap_or("");
                if !self.authors.iter().any(|a| a == event_author) {
                    return false;
                }
            }

            let tags = event.get("tags").and_then(|t| t.as_array());

            // Check #p tag
            if let Some(ref p) = self.p_tag {
                let has_p = tags
                    .map(|tags| {
                        tags.iter().any(|tag| {
                            tag.as_array()
                                .map(|arr| {
                                    arr.len() >= 2
                                        && arr[0].as_str() == Some("p")
                                        && arr[1].as_str() == Some(p.as_str())
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if !has_p {
                    return false;
                }
            }

            // Check #l tag
            if let Some(ref l) = self.l_tag {
                let has_l = tags
                    .map(|tags| {
                        tags.iter().any(|tag| {
                            tag.as_array()
                                .map(|arr| {
                                    arr.len() >= 2
                                        && arr[0].as_str() == Some("l")
                                        && arr[1].as_str() == Some(l.as_str())
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if !has_l {
                    return false;
                }
            }

            // Check #a tag
            if let Some(ref a) = self.a_tag {
                let has_a = tags
                    .map(|tags| {
                        tags.iter().any(|tag| {
                            tag.as_array()
                                .map(|arr| {
                                    arr.len() >= 2
                                        && arr[0].as_str() == Some("a")
                                        && arr[1].as_str() == Some(a.as_str())
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if !has_a {
                    return false;
                }
            }

            // Check #e tags (any of the filter e_tags must match)
            if !self.e_tags.is_empty() {
                let has_e = tags
                    .map(|tags| {
                        tags.iter().any(|tag| {
                            tag.as_array()
                                .map(|arr| {
                                    arr.len() >= 2
                                        && arr[0].as_str() == Some("e")
                                        && self
                                            .e_tags
                                            .iter()
                                            .any(|e| arr[1].as_str() == Some(e.as_str()))
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if !has_e {
                    return false;
                }
            }

            // Check #d tag
            if let Some(ref d) = self.d_tag {
                let has_d = tags
                    .map(|tags| {
                        tags.iter().any(|tag| {
                            tag.as_array()
                                .map(|arr| {
                                    arr.len() >= 2
                                        && arr[0].as_str() == Some("d")
                                        && arr[1].as_str() == Some(d.as_str())
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if !has_d {
                    return false;
                }
            }

            true
        }
    }

    pub struct TestRelay {
        port: u16,
        shutdown: broadcast::Sender<()>,
        events: Arc<RwLock<HashMap<String, serde_json::Value>>>,
    }

    #[derive(Clone, Default)]
    pub struct TestRelayOptions {
        pub reject_event_kinds: Vec<u64>,
        pub ignore_req_kinds: Vec<u64>,
        pub respond_empty_req_kinds_once: Vec<u64>,
    }

    impl TestRelay {
        pub fn new(port: u16) -> Self {
            Self::with_options(port, TestRelayOptions::default())
        }

        pub fn with_options(port: u16, options: TestRelayOptions) -> Self {
            let events: Arc<RwLock<HashMap<String, serde_json::Value>>> =
                Arc::new(RwLock::new(HashMap::new()));
            let (shutdown, _) = broadcast::channel(1);
            // Broadcast channel for new events - larger buffer for busy relays
            let (event_tx, _) = broadcast::channel::<serde_json::Value>(1000);
            let reject_event_kinds: Arc<HashSet<u64>> =
                Arc::new(options.reject_event_kinds.iter().copied().collect());
            let ignore_req_kinds: Arc<HashSet<u64>> =
                Arc::new(options.ignore_req_kinds.iter().copied().collect());
            let respond_empty_req_kinds_once: Arc<tokio::sync::Mutex<HashSet<u64>>> =
                Arc::new(tokio::sync::Mutex::new(
                    options
                        .respond_empty_req_kinds_once
                        .iter()
                        .copied()
                        .collect(),
                ));

            let relay = TestRelay {
                port,
                shutdown: shutdown.clone(),
                events: events.clone(),
            };

            // Start relay in background
            let events_clone = events.clone();
            let mut shutdown_rx = shutdown.subscribe();
            let event_tx_clone = event_tx.clone();
            let ignore_req_kinds_clone = ignore_req_kinds.clone();
            let respond_empty_req_kinds_once_clone = respond_empty_req_kinds_once.clone();

            std::thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .worker_threads(2)
                    .enable_all()
                    .build()
                    .unwrap();

                rt.block_on(async move {
                    let listener = TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap();
                    listener.set_nonblocking(true).unwrap();
                    let listener = tokio::net::TcpListener::from_std(listener).unwrap();

                    loop {
                        tokio::select! {
                            _ = shutdown_rx.recv() => break,
                            result = listener.accept() => {
                                if let Ok((stream, _)) = result {
                                    let events = events_clone.clone();
                                    let event_tx = event_tx_clone.clone();
                                    let event_rx = event_tx_clone.subscribe();
                                    let reject_event_kinds = reject_event_kinds.clone();
                                    let ignore_req_kinds = ignore_req_kinds_clone.clone();
                                    let respond_empty_req_kinds_once =
                                        respond_empty_req_kinds_once_clone.clone();
                                    tokio::spawn(handle_connection(
                                        stream,
                                        events,
                                        event_tx,
                                        event_rx,
                                        reject_event_kinds,
                                        ignore_req_kinds,
                                        respond_empty_req_kinds_once,
                                    ));
                                }
                            }
                        }
                    }
                });
            });

            // Wait until the listener is actually bound before returning.
            let deadline = Instant::now() + Duration::from_secs(5);
            let addr = format!("127.0.0.1:{}", port);
            while Instant::now() < deadline {
                if StdTcpStream::connect(&addr).is_ok() {
                    return relay;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            panic!("Test relay did not start on {}", addr);
        }

        pub fn url(&self) -> String {
            format!("ws://127.0.0.1:{}", self.port)
        }

        pub fn stored_events(&self) -> Vec<serde_json::Value> {
            let events = self.events.clone();
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("Failed to build runtime");
            rt.block_on(async move { events.read().await.values().cloned().collect() })
        }
    }

    impl Drop for TestRelay {
        fn drop(&mut self) {
            let _ = self.shutdown.send(());
            // Give time for cleanup
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }

    async fn handle_connection(
        stream: TcpStream,
        events: Arc<RwLock<HashMap<String, serde_json::Value>>>,
        event_tx: broadcast::Sender<serde_json::Value>,
        mut event_rx: broadcast::Receiver<serde_json::Value>,
        reject_event_kinds: Arc<HashSet<u64>>,
        ignore_req_kinds: Arc<HashSet<u64>>,
        respond_empty_req_kinds_once: Arc<tokio::sync::Mutex<HashSet<u64>>>,
    ) {
        let ws_stream = match accept_async(stream).await {
            Ok(s) => s,
            Err(_) => return,
        };

        let (write, mut read) = ws_stream.split();
        let write = Arc::new(tokio::sync::Mutex::new(write));

        // Track active subscriptions for this connection
        let subscriptions: Arc<RwLock<HashMap<String, Vec<StoredFilter>>>> =
            Arc::new(RwLock::new(HashMap::new()));

        // Spawn task to handle incoming broadcast events
        let write_clone = write.clone();
        let subs_clone = subscriptions.clone();
        let broadcast_task = tokio::spawn(async move {
            loop {
                match event_rx.recv().await {
                    Ok(event) => {
                        let subs = subs_clone.read().await;
                        for (_, filters) in subs.iter() {
                            for filter in filters {
                                if filter.matches(&event) {
                                    let event_msg =
                                        serde_json::json!(["EVENT", &filter.sub_id, &event]);
                                    let mut w = write_clone.lock().await;
                                    let _ = w.send(Message::Text(event_msg.to_string())).await;
                                    break; // Only send once per subscription
                                }
                            }
                        }
                    }
                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(broadcast::error::RecvError::Closed) => break,
                }
            }
        });

        // Handle incoming messages from client
        while let Some(msg) = read.next().await {
            let msg = match msg {
                Ok(Message::Text(t)) => t,
                Ok(Message::Close(_)) => break,
                Ok(Message::Ping(data)) => {
                    let mut w = write.lock().await;
                    let _ = w.send(Message::Pong(data)).await;
                    continue;
                }
                _ => continue,
            };

            let parsed: Result<Vec<serde_json::Value>, _> = serde_json::from_str(&msg);
            let parsed = match parsed {
                Ok(p) => p,
                Err(_) => continue,
            };

            if parsed.is_empty() {
                continue;
            }

            let msg_type = parsed[0].as_str().unwrap_or("");

            match msg_type {
                "EVENT" => {
                    if parsed.len() >= 2 {
                        let event = parsed[1].clone();
                        if let Some(id) = event.get("id").and_then(|v| v.as_str()) {
                            let kind = event.get("kind").and_then(|v| v.as_u64()).unwrap_or(0);
                            if reject_event_kinds.contains(&kind) {
                                let ok_msg =
                                    serde_json::json!(["OK", id, false, "rejected for test"]);
                                let mut w = write.lock().await;
                                let _ = w.send(Message::Text(ok_msg.to_string())).await;
                                continue;
                            }

                            // Store event
                            events.write().await.insert(id.to_string(), event.clone());

                            // Send OK response
                            let ok_msg = serde_json::json!(["OK", id, true, ""]);
                            {
                                let mut w = write.lock().await;
                                let _ = w.send(Message::Text(ok_msg.to_string())).await;
                            }

                            // Broadcast to all connections
                            let _ = event_tx.send(event);
                        }
                    }
                }
                "REQ" => {
                    if parsed.len() >= 3 {
                        let sub_id = parsed[1].as_str().unwrap_or("sub").to_string();

                        // Parse all filters (can have multiple)
                        let mut filters = Vec::new();
                        for i in 2..parsed.len() {
                            let filter = &parsed[i];

                            let kinds_arr: Vec<u64> = filter
                                .get("kinds")
                                .and_then(|k| k.as_array())
                                .map(|arr| arr.iter().filter_map(|v| v.as_u64()).collect())
                                .unwrap_or_default();

                            // Single kind for backward compat
                            let kind = if kinds_arr.len() == 1 {
                                Some(kinds_arr[0])
                            } else {
                                None
                            };

                            // If more than one kind, use kinds vec
                            let kinds = if kinds_arr.len() > 1 {
                                kinds_arr
                            } else {
                                vec![]
                            };

                            let authors: Vec<String> = filter
                                .get("authors")
                                .and_then(|a| a.as_array())
                                .map(|arr| {
                                    arr.iter()
                                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                                        .collect()
                                })
                                .unwrap_or_default();

                            let p_tag = filter
                                .get("#p")
                                .and_then(|p| p.as_array())
                                .and_then(|a| a.first())
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());

                            let l_tag = filter
                                .get("#l")
                                .and_then(|l| l.as_array())
                                .and_then(|a| a.first())
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());

                            let a_tag = filter
                                .get("#a")
                                .and_then(|a| a.as_array())
                                .and_then(|a| a.first())
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());

                            let e_tags: Vec<String> = filter
                                .get("#e")
                                .and_then(|e| e.as_array())
                                .map(|arr| {
                                    arr.iter()
                                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                                        .collect()
                                })
                                .unwrap_or_default();

                            let d_tag = filter
                                .get("#d")
                                .and_then(|d| d.as_array())
                                .and_then(|a| a.first())
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());

                            filters.push(StoredFilter {
                                sub_id: sub_id.clone(),
                                kind,
                                kinds,
                                authors,
                                p_tag,
                                l_tag,
                                a_tag,
                                e_tags,
                                d_tag,
                            });
                        }

                        let should_ignore_req = filters.iter().any(|filter| {
                            filter
                                .kind
                                .into_iter()
                                .chain(filter.kinds.iter().copied())
                                .any(|kind| ignore_req_kinds.contains(&kind))
                        });
                        if should_ignore_req {
                            continue;
                        }

                        let req_kinds: Vec<u64> = filters
                            .iter()
                            .flat_map(|filter| {
                                filter.kind.into_iter().chain(filter.kinds.iter().copied())
                            })
                            .collect();
                        let should_respond_empty_once = {
                            let mut remaining = respond_empty_req_kinds_once.lock().await;
                            req_kinds.into_iter().any(|kind| remaining.remove(&kind))
                        };
                        if should_respond_empty_once {
                            let eose = serde_json::json!(["EOSE", &sub_id]);
                            let mut w = write.lock().await;
                            let _ = w.send(Message::Text(eose.to_string())).await;
                            continue;
                        }

                        // Store subscription
                        subscriptions
                            .write()
                            .await
                            .insert(sub_id.clone(), filters.clone());

                        // Send matching historical events
                        let events_lock = events.read().await;
                        let mut w = write.lock().await;

                        for event in events_lock.values() {
                            for filter in &filters {
                                if filter.matches(event) {
                                    let event_msg = serde_json::json!(["EVENT", &sub_id, event]);
                                    let _ = w.send(Message::Text(event_msg.to_string())).await;
                                    break;
                                }
                            }
                        }
                        drop(events_lock);

                        // Send EOSE
                        let eose = serde_json::json!(["EOSE", &sub_id]);
                        let _ = w.send(Message::Text(eose.to_string())).await;
                    }
                }
                "CLOSE" => {
                    if parsed.len() >= 2 {
                        if let Some(sub_id) = parsed[1].as_str() {
                            subscriptions.write().await.remove(sub_id);
                        }
                    }
                }
                _ => {}
            }
        }

        // Clean up broadcast task
        broadcast_task.abort();
    }
}

/// Local blossom server for testing
pub struct TestServer {
    _data_dir: TempDir,
    _home_dir: TempDir,
    process: Child,
    port: u16,
}

impl TestServer {
    pub fn new(port: u16) -> Option<Self> {
        let htree_bin = find_htree_binary()?;
        let data_dir = TempDir::new().expect("Failed to create temp dir");
        let home_dir = TempDir::new().expect("Failed to create home dir");

        // Create .hashtree config dir for the server
        let config_dir = home_dir.path().join(".hashtree");
        std::fs::create_dir_all(&config_dir).expect("Failed to create config dir");

        // Server config - no auth for testing
        let config_content = r#"
[server]
bind_address = "127.0.0.1:0"
enable_auth = false
stun_port = 0
enable_webrtc = false
public_writes = true

[nostr]
relays = []
"#;
        std::fs::write(config_dir.join("config.toml"), config_content)
            .expect("Failed to write config");

        // Generate keys for server
        let keys = nostr::Keys::generate();
        let nsec = keys
            .secret_key()
            .to_bech32()
            .expect("Failed to encode nsec");
        std::fs::write(config_dir.join("keys"), &nsec).expect("Failed to write keys");

        let process = Command::new(&htree_bin)
            .arg("--data-dir")
            .arg(data_dir.path())
            .arg("start")
            .arg("--addr")
            .arg(format!("127.0.0.1:{}", port))
            .env("HOME", home_dir.path())
            .env("RUST_LOG", "warn")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to start htree server");

        // Wait for server to start
        std::thread::sleep(Duration::from_secs(2));

        Some(TestServer {
            _data_dir: data_dir,
            _home_dir: home_dir,
            process,
            port,
        })
    }

    pub fn base_url(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        let _ = self.process.kill();
        let _ = self.process.wait();
    }
}

fn find_htree_binary() -> Option<PathBuf> {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let workspace_root = PathBuf::from(manifest_dir)
        .parent()?
        .parent()?
        .to_path_buf();
    let target_dir = cargo_target_dir(&workspace_root);
    let debug_bin = target_dir.join("debug/htree");
    let release_bin = target_dir.join("release/htree");

    if release_bin.exists() {
        Some(release_bin)
    } else if debug_bin.exists() {
        Some(debug_bin)
    } else {
        None
    }
}

fn cargo_target_dir(workspace_root: &std::path::Path) -> PathBuf {
    match std::env::var_os("CARGO_TARGET_DIR") {
        Some(path) => {
            let path = PathBuf::from(path);
            if path.is_absolute() {
                path
            } else {
                workspace_root.join(path)
            }
        }
        None => workspace_root.join("target"),
    }
}

/// Test environment with config and keys
pub struct TestEnv {
    _data_dir: TempDir,
    pub home_dir: PathBuf,
    pub nsec: String,
    pub npub: String,
}

impl TestEnv {
    pub fn new(blossom_server: Option<&str>, nostr_relay: Option<&str>) -> Self {
        let keys = nostr::Keys::generate();
        let nsec = keys
            .secret_key()
            .to_bech32()
            .expect("Failed to encode nsec");
        Self::with_nsec(blossom_server, nostr_relay, &nsec)
    }

    pub fn with_nsec(blossom_server: Option<&str>, nostr_relay: Option<&str>, nsec: &str) -> Self {
        let data_dir = TempDir::new().expect("Failed to create temp dir");
        let home_dir = data_dir.path().to_path_buf();

        // Create .hashtree config dir
        let config_dir = home_dir.join(".hashtree");
        std::fs::create_dir_all(&config_dir).expect("Failed to create config dir");

        // Build config
        let relays = match nostr_relay {
            Some(url) => format!(r#"relays = ["{}"]"#, url),
            None => format!(
                "relays = [{}]",
                hashtree_config::DEFAULT_RELAYS
                    .iter()
                    .map(|url| format!(r#""{}""#, url))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        };

        let blossom = match blossom_server {
            Some(url) => format!(
                r#"
[blossom]
read_servers = ["{url}"]
write_servers = ["{url}"]
"#
            ),
            None => String::new(),
        };

        let config_content = format!(
            r#"
[server]
bind_address = "127.0.0.1:0"
enable_auth = false
stun_port = 0

[nostr]
{relays}
social_graph_crawl_depth = 0

{blossom}
"#
        );

        std::fs::write(config_dir.join("config.toml"), config_content)
            .expect("Failed to write config");

        // Reuse or generate a test key for isolation.
        let secret = nostr::SecretKey::parse(nsec).expect("Failed to parse nsec");
        let keys = nostr::Keys::new(secret);
        let npub = keys
            .public_key()
            .to_bech32()
            .expect("Failed to encode npub");
        let key_line = format!("{} self\n", nsec);
        std::fs::write(config_dir.join("keys"), &key_line).expect("Failed to write keys");
        println!("Using test key: {} (petname: self)", &nsec[..20]);

        TestEnv {
            _data_dir: data_dir,
            home_dir,
            nsec: nsec.to_string(),
            npub,
        }
    }

    pub fn env(&self) -> Vec<(String, String)> {
        let config_dir = self.home_dir.join(".hashtree");
        vec![
            (
                "HOME".to_string(),
                self.home_dir.to_string_lossy().to_string(),
            ),
            ("NOSTR_PREFER_LOCAL".to_string(), "0".to_string()),
            (
                "HTREE_CONFIG_DIR".to_string(),
                config_dir.to_string_lossy().to_string(),
            ),
            (
                "PATH".to_string(),
                format!(
                    "{}:{}",
                    find_git_remote_htree_dir()
                        .map(|p| p.to_string_lossy().to_string())
                        .unwrap_or_default(),
                    std::env::var("PATH").unwrap_or_default()
                ),
            ),
            ("HTREE_VERBOSE".to_string(), "1".to_string()),
        ]
    }

    /// Update blossom servers in config (for testing server coverage)
    pub fn update_blossom_servers(&self, servers: &[&str], relay_url: &str) {
        let config_dir = self.home_dir.join(".hashtree");
        let servers_json: Vec<String> = servers.iter().map(|s| format!("\"{}\"", s)).collect();
        let servers_str = servers_json.join(", ");

        let config_content = format!(
            r#"
[server]
enable_auth = false
stun_port = 0

[nostr]
relays = ["{}"]
social_graph_crawl_depth = 0

[blossom]
read_servers = [{servers_str}]
write_servers = [{servers_str}]
"#,
            relay_url
        );

        std::fs::write(config_dir.join("config.toml"), config_content)
            .expect("Failed to update config");
    }
}

pub fn find_git_remote_htree_dir() -> Option<PathBuf> {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let workspace_root = PathBuf::from(manifest_dir)
        .parent()?
        .parent()?
        .to_path_buf();
    let target_dir = cargo_target_dir(&workspace_root);
    let release_dir = target_dir.join("release");
    let debug_dir = target_dir.join("debug");

    // Prefer debug so `cargo test` uses a freshly built helper binary from current sources.
    if debug_dir.join("git-remote-htree").exists() {
        Some(debug_dir)
    } else if release_dir.join("git-remote-htree").exists() {
        Some(release_dir)
    } else {
        // Binary not found - print helpful message
        eprintln!("WARNING: git-remote-htree binary not found in target/debug or target/release.");
        eprintln!("Run: cargo build -p git-remote-htree");
        None
    }
}

/// Create a test git repository with some files
pub fn create_test_repo() -> TempDir {
    let dir = TempDir::new().expect("Failed to create temp dir");
    let path = dir.path();

    // Init git repo
    let status = Command::new("git")
        .args(["init", "-b", "master"])
        .current_dir(path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("Failed to run git init");
    assert!(status.success(), "git init failed");

    // Configure git
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(path)
        .status()
        .expect("Failed to configure git");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(path)
        .status()
        .expect("Failed to configure git");

    // Create test files
    std::fs::write(
        path.join("README.md"),
        "# Test Repository\n\nThis is a test.\n",
    )
    .unwrap();
    std::fs::write(path.join("hello.txt"), "Hello, World!\n").unwrap();
    std::fs::create_dir_all(path.join("src")).unwrap();
    std::fs::write(
        path.join("src/main.rs"),
        r#"fn main() {
    println!("Hello from test repo!");
}
"#,
    )
    .unwrap();

    // Commit
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(path)
        .status()
        .expect("Failed to git add");
    Command::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(path)
        .stdout(Stdio::null())
        .status()
        .expect("Failed to git commit");

    dir
}

/// Check if prerequisites are met for tests
pub fn check_prerequisites() -> bool {
    find_git_remote_htree_dir().is_some()
}

/// Print skip message if prerequisites not met
pub fn skip_if_no_binary() -> bool {
    if find_git_remote_htree_dir().is_none() {
        println!(
            "SKIP: git-remote-htree binary not found. Run `cargo build -p git-remote-htree` first."
        );
        true
    } else {
        false
    }
}