gity 0.1.2

Make large Git repositories feel instant - a lightweight daemon that accelerates Git operations
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
//! Integration tests for core gity workflows with real Git repositories.
//!
//! These tests verify the end-to-end behavior of:
//! - Repository registration and configuration
//! - File change detection via watchers
//! - Status queries returning correct dirty paths
//! - FSMonitor protocol compliance
//! - Job scheduling and execution

use git2::{Repository, Signature};
use gity_daemon::{NngClient, NngServer, Runtime};
use gity_git::{working_tree_status, RepoConfigurator};
use gity_ipc::{
    DaemonCommand, DaemonResponse, DaemonService, FsMonitorSnapshot, JobKind, ValidatedPath,
};
use gity_storage::{InMemoryMetadataStore, MetadataStore, SledMetadataStore};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::sleep;

/// Helper to convert PathBuf to ValidatedPath (for tests with valid temp paths)
fn validated_path(path: &Path) -> ValidatedPath {
    ValidatedPath::new(path.to_path_buf()).expect("valid path for test")
}

/// Helper to create a Git repository with an initial commit.
fn create_test_repo(dir: &Path) -> Repository {
    let repo = Repository::init(dir).expect("init repo");

    // Create initial file and commit
    let file_path = dir.join("README.md");
    fs::write(&file_path, "# Test Repo\n").expect("write file");

    {
        let mut index = repo.index().expect("get index");
        index
            .add_path(Path::new("README.md"))
            .expect("add to index");
        index.write().expect("write index");

        let tree_id = index.write_tree().expect("write tree");
        let tree = repo.find_tree(tree_id).expect("find tree");
        let sig = Signature::now("Test", "test@example.com").expect("signature");

        repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .expect("commit");
    }

    repo
}

/// Helper to modify a file in the repo.
fn modify_file(dir: &Path, filename: &str, content: &str) {
    let path = dir.join(filename);
    fs::write(&path, content).expect("write file");
}

/// Helper to create a new untracked file.
fn create_untracked_file(dir: &Path, filename: &str, content: &str) {
    let path = dir.join(filename);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).ok();
    }
    fs::write(&path, content).expect("write file");
}

// =============================================================================
// Git Status Tests
// =============================================================================

#[test]
fn test_working_tree_status_clean_repo() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let status = working_tree_status(dir.path(), &[]).expect("get status");
    assert!(status.is_empty(), "Clean repo should have no dirty paths");
}

#[test]
fn test_working_tree_status_modified_file() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Modify tracked file
    modify_file(dir.path(), "README.md", "# Modified\n");

    let status = working_tree_status(dir.path(), &[]).expect("get status");
    assert_eq!(status.len(), 1);
    assert_eq!(status[0], PathBuf::from("README.md"));
}

#[test]
fn test_working_tree_status_untracked_file() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Create untracked file
    create_untracked_file(dir.path(), "new_file.txt", "hello");

    let status = working_tree_status(dir.path(), &[]).expect("get status");
    assert_eq!(status.len(), 1);
    assert_eq!(status[0], PathBuf::from("new_file.txt"));
}

#[test]
fn test_working_tree_status_multiple_changes() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Create multiple changes
    modify_file(dir.path(), "README.md", "# Modified\n");
    create_untracked_file(dir.path(), "file1.txt", "one");
    create_untracked_file(dir.path(), "file2.txt", "two");

    let status = working_tree_status(dir.path(), &[]).expect("get status");
    assert_eq!(status.len(), 3);
}

#[test]
fn test_working_tree_status_with_path_filter() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Create multiple changes
    modify_file(dir.path(), "README.md", "# Modified\n");
    create_untracked_file(dir.path(), "src/main.rs", "fn main() {}");

    // Filter to only src/
    let status = working_tree_status(dir.path(), &[PathBuf::from("src")]).expect("get status");
    assert_eq!(status.len(), 1);
    assert!(status[0].starts_with("src"));
}

// =============================================================================
// Repository Configuration Tests
// =============================================================================

#[test]
fn test_repo_configurator_applies_settings() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let configurator = RepoConfigurator::open(dir.path()).expect("open repo");
    configurator
        .apply_performance_settings(Some("gity fsmonitor-helper"))
        .expect("apply settings");

    let config = fs::read_to_string(dir.path().join(".git/config")).expect("read config");
    assert!(config.contains("fsmonitor"));
    assert!(config.contains("untrackedCache"));
}

#[test]
fn test_repo_configurator_clears_settings() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let configurator = RepoConfigurator::open(dir.path()).expect("open repo");
    configurator
        .apply_performance_settings(Some("gity fsmonitor-helper"))
        .expect("apply settings");
    configurator
        .clear_performance_settings()
        .expect("clear settings");

    let config = fs::read_to_string(dir.path().join(".git/config")).expect("read config");
    assert!(!config.contains("fsmonitor = gity"));
}

// =============================================================================
// Storage Tests with Real Paths
// =============================================================================

#[test]
fn test_register_real_repo_in_memory_store() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let meta = store
        .register_repo(dir.path().to_path_buf())
        .expect("register");

    assert_eq!(meta.repo_path, dir.path());
    assert_eq!(meta.pending_jobs, 0);
}

#[test]
fn test_register_real_repo_in_sled_store() {
    let repo_dir = TempDir::new().unwrap();
    let _repo = create_test_repo(repo_dir.path());

    let db_dir = TempDir::new().unwrap();
    let store = SledMetadataStore::open(db_dir.path()).expect("open sled");

    let meta = store
        .register_repo(repo_dir.path().to_path_buf())
        .expect("register");
    assert_eq!(meta.repo_path, repo_dir.path());

    // Verify persistence
    let loaded = store.get_repo(repo_dir.path()).expect("get repo");
    assert!(loaded.is_some());
}

#[test]
fn test_dirty_paths_tracked_correctly() {
    let store = InMemoryMetadataStore::new();
    let repo_path = PathBuf::from("/tmp/test_repo");

    store.register_repo(repo_path.clone()).expect("register");

    // Mark files dirty
    store
        .mark_dirty_path(&repo_path, PathBuf::from("file1.txt"))
        .expect("mark 1");
    store
        .mark_dirty_path(&repo_path, PathBuf::from("file2.txt"))
        .expect("mark 2");
    store
        .mark_dirty_path(&repo_path, PathBuf::from("file1.txt"))
        .expect("mark dup"); // duplicate

    let count = store.dirty_path_count(&repo_path).expect("count");
    assert_eq!(count, 2); // Should dedupe

    let drained = store.drain_dirty_paths(&repo_path).expect("drain");
    assert_eq!(drained.len(), 2);

    // After drain, should be empty
    let count_after = store.dirty_path_count(&repo_path).expect("count after");
    assert_eq!(count_after, 0);
}

// =============================================================================
// Daemon Integration Tests
// =============================================================================

#[tokio::test]
async fn test_daemon_register_and_status_flow() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register repo
    let response = service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    assert!(matches!(response, DaemonResponse::Ack(_)));

    // Get status - should be clean initially
    let response = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status");

    match response {
        DaemonResponse::RepoStatus(detail) => {
            assert_eq!(detail.repo_path, dir.path());
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_status_detects_real_file_changes() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register repo
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    // First status (clean)
    let _response = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status");

    // Now modify a file
    modify_file(dir.path(), "README.md", "# Changed content\n");

    // Get status again - the working_tree_status should detect the change
    let response = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status after change");

    match response {
        DaemonResponse::RepoStatus(detail) => {
            // The status should include the modified file
            assert!(
                detail.dirty_paths.contains(&PathBuf::from("README.md")),
                "Should detect modified README.md, got: {:?}",
                detail.dirty_paths
            );
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_fsmonitor_snapshot() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register repo
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    // Create file changes
    modify_file(dir.path(), "README.md", "# Changed\n");
    create_untracked_file(dir.path(), "new.txt", "new file");

    // Get fsmonitor snapshot
    let response = service
        .execute(DaemonCommand::FsMonitorSnapshot {
            repo_path: validated_path(dir.path()),
            last_seen_generation: None,
        })
        .await
        .expect("snapshot");

    match response {
        DaemonResponse::FsMonitorSnapshot(snapshot) => {
            assert_eq!(snapshot.repo_path, dir.path());
            // Should contain dirty paths from git status
            assert!(!snapshot.dirty_paths.is_empty() || snapshot.generation > 0);
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_job_queueing() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register repo
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    // Queue prefetch job
    let response = service
        .execute(DaemonCommand::QueueJob {
            repo_path: validated_path(dir.path()),
            job: JobKind::Prefetch,
        })
        .await
        .expect("queue job");

    assert!(matches!(response, DaemonResponse::Ack(_)));

    // Check health shows pending job
    let response = service
        .execute(DaemonCommand::HealthCheck)
        .await
        .expect("health");

    match response {
        DaemonResponse::Health(health) => {
            assert!(health.pending_jobs >= 1);
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_repo_health_diagnostics() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register repo
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    // Get repo health
    let response = service
        .execute(DaemonCommand::RepoHealth {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("repo health");

    match response {
        DaemonResponse::RepoHealth(detail) => {
            assert_eq!(detail.repo_path, dir.path());
            assert!(detail.sled_ok);
            assert!(!detail.needs_reconciliation);
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_list_repos() {
    let dir1 = TempDir::new().unwrap();
    let dir2 = TempDir::new().unwrap();
    let _repo1 = create_test_repo(dir1.path());
    let _repo2 = create_test_repo(dir2.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register both repos
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir1.path()),
        })
        .await
        .expect("register 1");
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir2.path()),
        })
        .await
        .expect("register 2");

    // List repos
    let response = service
        .execute(DaemonCommand::ListRepos)
        .await
        .expect("list");

    match response {
        DaemonResponse::RepoList(list) => {
            assert_eq!(list.len(), 2);
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

#[tokio::test]
async fn test_daemon_unregister_repo() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Register then unregister
    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    let response = service
        .execute(DaemonCommand::UnregisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("unregister");

    assert!(matches!(response, DaemonResponse::Ack(_)));

    // Verify removed
    let response = service
        .execute(DaemonCommand::ListRepos)
        .await
        .expect("list");

    match response {
        DaemonResponse::RepoList(list) => {
            assert!(list.is_empty());
        }
        other => panic!("unexpected response: {:?}", other),
    }
}

// =============================================================================
// Client-Server Integration Tests
// =============================================================================

#[tokio::test]
async fn test_nng_client_server_with_real_repo() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let shutdown = runtime.shutdown_signal();
    let shared = runtime.shared();

    // Use random port based on process id
    let port = 19000 + (std::process::id() % 1000) as u16;
    let address = format!("tcp://127.0.0.1:{}", port);

    let server = NngServer::new(address.clone(), shared, shutdown.clone());

    // Start server in background
    let server_handle = tokio::spawn(async move {
        let _ = server.run().await;
    });

    // Give server time to start
    sleep(Duration::from_millis(100)).await;

    // Create client and test
    let client = NngClient::new(address);

    let response = client
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register via client");

    assert!(matches!(response, DaemonResponse::Ack(_)));

    // Test status query
    let response = client
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status via client");

    assert!(matches!(response, DaemonResponse::RepoStatus(_)));

    // Shutdown
    shutdown.shutdown();
    let _ = server_handle.await;
}

// =============================================================================
// Generation Counter Tests
// =============================================================================

#[tokio::test]
async fn test_generation_increments_on_changes() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");

    // First status
    let response1 = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status 1");

    let gen1 = match response1 {
        DaemonResponse::RepoStatus(detail) => detail.generation,
        other => panic!("unexpected: {:?}", other),
    };

    // Modify file and query again WITHOUT known_generation
    // (This forces a fresh status check that will detect the change)
    modify_file(dir.path(), "README.md", "# Changed again\n");

    let response2 = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None, // Don't pass known generation to force full check
        })
        .await
        .expect("status 2");

    let gen2 = match response2 {
        DaemonResponse::RepoStatus(detail) => detail.generation,
        DaemonResponse::RepoStatusUnchanged { generation, .. } => generation,
        other => panic!("unexpected: {:?}", other),
    };

    // Generation should increment because we got dirty paths from git status
    assert!(gen2 >= gen1, "Generation should be at least the same");
}

// =============================================================================
// End-to-End Workflow Test
// =============================================================================

#[tokio::test]
async fn test_full_workflow_register_modify_status() {
    // This test simulates the complete user workflow:
    // 1. User registers a repo
    // 2. User makes changes to files
    // 3. User queries status
    // 4. Gity correctly reports the dirty files

    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();
    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Step 1: Register repo
    let response = service
        .execute(DaemonCommand::RegisterRepo {
            repo_path: validated_path(dir.path()),
        })
        .await
        .expect("register");
    assert!(matches!(response, DaemonResponse::Ack(_)));

    // Step 2: Make changes
    modify_file(dir.path(), "README.md", "# New content\n");
    create_untracked_file(dir.path(), "src/lib.rs", "pub fn hello() {}");
    create_untracked_file(dir.path(), "tests/test.rs", "#[test] fn it_works() {}");

    // Step 3: Query status
    let response = service
        .execute(DaemonCommand::Status {
            repo_path: validated_path(dir.path()),
            known_generation: None,
        })
        .await
        .expect("status");

    // Step 4: Verify dirty paths
    match response {
        DaemonResponse::RepoStatus(detail) => {
            assert_eq!(detail.repo_path, dir.path());
            assert!(!detail.dirty_paths.is_empty(), "Should have dirty paths");

            // Check specific files are detected
            let has_readme = detail.dirty_paths.iter().any(|p| p.ends_with("README.md"));
            assert!(has_readme, "Should detect modified README.md");
        }
        other => panic!("unexpected response: {:?}", other),
    }

    // Verify health is good
    let response = service
        .execute(DaemonCommand::HealthCheck)
        .await
        .expect("health");

    match response {
        DaemonResponse::Health(health) => {
            assert_eq!(health.repo_count, 1);
        }
        other => panic!("unexpected: {:?}", other),
    }
}

// =============================================================================
// FSMonitor Protocol Tests
// =============================================================================

/// Test that fsmonitor snapshot produces correctly formatted output
#[test]
fn test_fsmonitor_protocol_output_format() {
    // The fsmonitor protocol v2 expects:
    // - A token (generation number) followed by NUL
    // - Each dirty path followed by NUL
    let snapshot = FsMonitorSnapshot {
        repo_path: PathBuf::from("/test/repo"),
        generation: 42,
        dirty_paths: vec![PathBuf::from("src/main.rs"), PathBuf::from("Cargo.toml")],
    };

    // Simulate the output format
    let mut output = Vec::new();
    output.extend_from_slice(snapshot.generation.to_string().as_bytes());
    output.push(0); // NUL separator
    for path in &snapshot.dirty_paths {
        if let Some(s) = path.to_str() {
            output.extend_from_slice(s.as_bytes());
            output.push(0); // NUL separator
        }
    }

    // Verify format
    let output_str = String::from_utf8_lossy(&output);
    assert!(output_str.starts_with("42\0"));
    assert!(output_str.contains("src/main.rs\0"));
    assert!(output_str.contains("Cargo.toml\0"));
}

// =============================================================================
// Git Command Execution Tests
// =============================================================================

/// Test that git maintenance command is available and can run
#[test]
fn test_git_maintenance_command_exists() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Verify git maintenance run works (dry-run would be ideal but not all git versions support it)
    let output = Command::new("git")
        .args(["maintenance", "run", "--task=prefetch"])
        .current_dir(dir.path())
        .output();

    // We just verify the command executes - it may fail due to no remote, but that's ok
    assert!(
        output.is_ok(),
        "git maintenance command should be available"
    );
}

/// Test that git status works in test repo
#[test]
fn test_git_status_command_works() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Modify a file
    modify_file(dir.path(), "README.md", "# Changed\n");

    // Run git status
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(dir.path())
        .output()
        .expect("git status should work");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("README.md"),
        "git status should show modified file"
    );
}

/// Test that our working_tree_status matches git status output
#[test]
fn test_working_tree_status_matches_git_status() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Create changes (avoid nested directories as git status shows them differently)
    modify_file(dir.path(), "README.md", "# Changed\n");
    create_untracked_file(dir.path(), "new_file.txt", "new");

    // Get our status
    let our_status = working_tree_status(dir.path(), &[]).expect("our status");

    // Get git's status (with -uall to show individual files)
    let output = Command::new("git")
        .args(["status", "--porcelain", "-uall"])
        .current_dir(dir.path())
        .output()
        .expect("git status");
    let git_output = String::from_utf8_lossy(&output.stdout);

    // Verify our status contains the same files as git status
    for path in &our_status {
        let path_str = path.to_string_lossy();
        assert!(
            git_output.contains(&*path_str),
            "Our status path '{}' should be in git status output: {}",
            path_str,
            git_output
        );
    }

    // Count should match
    let git_lines: Vec<_> = git_output.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        our_status.len(),
        git_lines.len(),
        "Status count should match: ours={:?}, git={:?}",
        our_status,
        git_lines
    );
}

/// Test that git config changes persist correctly
#[test]
fn test_git_config_fsmonitor_setting() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    // Apply fsmonitor setting
    let configurator = RepoConfigurator::open(dir.path()).expect("open");
    configurator
        .apply_performance_settings(Some("gity fsmonitor-helper 2"))
        .expect("apply");

    // Verify via git config command
    let output = Command::new("git")
        .args(["config", "--get", "core.fsmonitor"])
        .current_dir(dir.path())
        .output()
        .expect("git config");

    let value = String::from_utf8_lossy(&output.stdout);
    assert!(
        value.contains("gity fsmonitor-helper"),
        "fsmonitor should be set: {}",
        value
    );

    // Clear and verify
    configurator.clear_performance_settings().expect("clear");

    let output = Command::new("git")
        .args(["config", "--get", "core.fsmonitor"])
        .current_dir(dir.path())
        .output()
        .expect("git config after clear");

    // Should return error (exit code 1) when key doesn't exist
    assert!(
        !output.status.success(),
        "fsmonitor config should be removed"
    );
}

// =============================================================================
// Branch Switch and .git Path Filtering Tests
// =============================================================================

/// Test that .git internal paths are filtered from fsmonitor output
#[tokio::test]
async fn test_fsmonitor_filters_git_internal_paths() {
    let dir = TempDir::new().unwrap();
    let _repo = create_test_repo(dir.path());

    let store = InMemoryMetadataStore::new();

    // Manually mark some paths as dirty, including .git internal paths
    store
        .register_repo(dir.path().to_path_buf())
        .expect("register");
    store
        .mark_dirty_path(dir.path(), PathBuf::from("README.md"))
        .expect("mark");
    store
        .mark_dirty_path(dir.path(), PathBuf::from("src/lib.rs"))
        .expect("mark");
    store
        .mark_dirty_path(dir.path(), PathBuf::from(".git/HEAD"))
        .expect("mark");
    store
        .mark_dirty_path(dir.path(), PathBuf::from(".git/index"))
        .expect("mark");
    store
        .mark_dirty_path(dir.path(), PathBuf::from(".git/refs/heads/main"))
        .expect("mark");

    let runtime = Runtime::new(store, None);
    let service = runtime.service_handle();

    // Query fsmonitor snapshot
    let response = service
        .execute(DaemonCommand::FsMonitorSnapshot {
            repo_path: validated_path(dir.path()),
            last_seen_generation: None,
        })
        .await
        .expect("fsmonitor");

    match response {
        DaemonResponse::FsMonitorSnapshot(snapshot) => {
            // Should contain working tree paths
            let has_readme = snapshot
                .dirty_paths
                .iter()
                .any(|p| p.ends_with("README.md"));
            let has_lib = snapshot
                .dirty_paths
                .iter()
                .any(|p| p.ends_with("src/lib.rs"));
            assert!(has_readme, "Should contain README.md");
            assert!(has_lib, "Should contain src/lib.rs");

            // Should NOT contain .git internal paths
            let has_git_head = snapshot
                .dirty_paths
                .iter()
                .any(|p| p.to_string_lossy().contains(".git"));
            assert!(
                !has_git_head,
                "Should NOT contain .git paths, but got: {:?}",
                snapshot.dirty_paths
            );
        }
        other => panic!("unexpected: {:?}", other),
    }
}

/// Test that branch switch is detected via file changes
#[test]
fn test_branch_switch_detected_via_file_changes() {
    let dir = TempDir::new().unwrap();
    let repo = create_test_repo(dir.path());

    // Create a new branch with different content
    let head = repo.head().expect("head");
    let commit = head.peel_to_commit().expect("commit");

    repo.branch("feature", &commit, false)
        .expect("create branch");

    // Switch to feature branch
    repo.set_head("refs/heads/feature").expect("set head");
    repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))
        .expect("checkout");

    // Modify file on feature branch
    modify_file(dir.path(), "README.md", "# Feature branch content\n");

    {
        let mut index = repo.index().expect("index");
        index.add_path(Path::new("README.md")).expect("add");
        index.write().expect("write");
        let tree_id = index.write_tree().expect("tree");
        let tree = repo.find_tree(tree_id).expect("find tree");
        let parent = repo.head().expect("head").peel_to_commit().expect("commit");
        let sig = Signature::now("Test", "test@example.com").expect("sig");
        repo.commit(
            Some("HEAD"),
            &sig,
            &sig,
            "Feature commit",
            &tree,
            &[&parent],
        )
        .expect("commit");
    }

    // Switch back to main/master
    let default_branch = if repo.find_branch("main", git2::BranchType::Local).is_ok() {
        "refs/heads/main"
    } else {
        "refs/heads/master"
    };
    repo.set_head(default_branch).expect("set head back");
    repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))
        .expect("checkout back");

    // After switching, README.md should have original content
    let content = fs::read_to_string(dir.path().join("README.md")).expect("read");
    assert!(
        content.contains("# Test Repo"),
        "Should have original content after branch switch"
    );

    // Git status should show clean
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(dir.path())
        .output()
        .expect("git status");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.trim().is_empty(),
        "Working tree should be clean after checkout: {}",
        stdout
    );
}