gitgrip 0.18.0

Multi-repo workflow tool - manage multiple git repositories as one
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
//! Init command implementation
//!
//! Initializes a new gitgrip workspace.
//! Supports initialization from:
//! - A manifest URL (default)
//! - Existing local directories (--from-dirs)

use crate::cli::output::Output;
use crate::core::detect::{detect_toolchain, DetectedToolchain};
use crate::core::gripspace::{ensure_gripspace, resolve_all_gripspaces};
use crate::core::manifest::{
    AgentContextTarget, HookCommand, Manifest, ManifestSettings, PlatformType, RepoAgentConfig,
    RepoConfig, ScriptStep, WorkspaceAgentConfig, WorkspaceConfig, WorkspaceHooks, WorkspaceScript,
};
use crate::core::manifest_paths;
use crate::git::clone_repo;
use crate::platform;
use crate::util::log_cmd;
use dialoguer::{theme::ColorfulTheme, Confirm, Editor, MultiSelect, Select};
use git2::Repository;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

/// A discovered repository from local directories
#[derive(Debug, Clone)]
pub struct DiscoveredRepo {
    /// Repository name (directory name by default)
    pub name: String,
    /// Path relative to workspace root
    pub path: String,
    /// Absolute path on disk
    pub absolute_path: PathBuf,
    /// Remote URL if configured
    pub url: Option<String>,
    /// Default branch (main, master, etc.)
    pub default_branch: String,
    /// Detected language and toolchain
    pub toolchain: Option<DetectedToolchain>,
}

/// Options for the init command
pub struct InitOptions<'a> {
    pub url: Option<&'a str>,
    pub path: Option<&'a str>,
    pub from_dirs: bool,
    pub dirs: &'a [String],
    pub interactive: bool,
    pub create_manifest: bool,
    pub manifest_name: Option<&'a str>,
    pub private: bool,
    pub from_repo: bool,
}

/// Run the init command
pub async fn run_init(opts: InitOptions<'_>) -> anyhow::Result<()> {
    if opts.from_repo {
        run_init_from_repo(opts.path)
    } else if opts.from_dirs {
        run_init_from_dirs(
            opts.path,
            opts.dirs,
            opts.interactive,
            opts.create_manifest,
            opts.manifest_name,
            opts.private,
        )
        .await
    } else {
        run_init_from_url(opts.url, opts.path)
    }
}

/// Initialize from an existing .repo/ directory (git-repo coexistence)
fn run_init_from_repo(path: Option<&str>) -> anyhow::Result<()> {
    use crate::core::repo_manifest::XmlManifest;

    let workspace_root = match path {
        Some(p) => PathBuf::from(p),
        None => std::env::current_dir()?,
    };

    // Find .repo directory
    let repo_dir = workspace_root.join(".repo");
    if !repo_dir.exists() {
        anyhow::bail!(
            "No .repo/ directory found in {:?}. Run 'repo init' and 'repo sync' first.",
            workspace_root
        );
    }

    // Find manifest.xml (typically a symlink to manifests/default.xml)
    let manifest_xml = repo_dir.join("manifest.xml");
    if !manifest_xml.exists() {
        anyhow::bail!("No .repo/manifest.xml found. Ensure 'repo init' has been run.");
    }

    Output::header("Initializing gitgrip from .repo/ workspace...");
    println!();

    // Parse the XML manifest
    let xml_manifest = XmlManifest::parse_file(&manifest_xml)?;
    let result = xml_manifest.to_manifest()?;

    // Print summary
    let mut platform_parts: Vec<String> = result
        .platform_counts
        .iter()
        .map(|(p, c)| format!("{}: {}", p, c))
        .collect();
    platform_parts.sort();

    Output::info(&format!(
        "Imported {} non-Gerrit repos ({})",
        result.non_gerrit_imported,
        platform_parts.join(", ")
    ));
    if result.gerrit_skipped > 0 {
        Output::info(&format!(
            "Skipped {} Gerrit repos (managed by repo upload)",
            result.gerrit_skipped
        ));
    }

    // Write manifest.yaml inside .repo/manifests/
    let manifests_dir = repo_dir.join("manifests");
    if !manifests_dir.exists() {
        anyhow::bail!(".repo/manifests/ directory not found");
    }

    let yaml = serde_yaml::to_string(&result.manifest)?;
    let yaml_path = manifests_dir.join("manifest.yaml");
    std::fs::write(&yaml_path, &yaml)?;

    // Create .gitgrip/ for state (ci results, etc.)
    let gitgrip_dir = workspace_root.join(".gitgrip");
    std::fs::create_dir_all(&gitgrip_dir)?;
    let state_path = gitgrip_dir.join("state.json");
    if !state_path.exists() {
        std::fs::write(&state_path, "{}")?;
    }

    println!();
    Output::success(&format!("Written: {}", yaml_path.display()));
    println!();
    println!("Now use: gr pr create, gr pr status, gr pr merge");

    Ok(())
}

/// Initialize workspace from a manifest URL (original behavior)
fn run_init_from_url(url: Option<&str>, path: Option<&str>) -> anyhow::Result<()> {
    let manifest_url = match url {
        Some(u) => u.to_string(),
        None => {
            anyhow::bail!("Manifest URL required. Usage: gr init <manifest-url>");
        }
    };

    // Determine target directory
    let target_dir = match path {
        Some(p) => PathBuf::from(p),
        None => {
            // Extract repo name from URL for directory name
            let name = extract_repo_name(&manifest_url).unwrap_or_else(|| "workspace".to_string());
            std::env::current_dir()?.join(name)
        }
    };

    Output::header(&format!("Initializing workspace in {:?}", target_dir));
    println!();

    // Create workspace directory
    if target_dir.exists() {
        anyhow::bail!(
            "Directory already exists: {:?}. Use a different path or remove the existing directory.",
            target_dir
        );
    }
    std::fs::create_dir_all(&target_dir)?;

    // Create .gitgrip directory structure
    let gitgrip_dir = target_dir.join(".gitgrip");
    let manifests_dir = manifest_paths::main_space_dir(&target_dir);
    let local_space_dir = manifest_paths::local_space_dir(&target_dir);
    std::fs::create_dir_all(&manifests_dir)?;
    std::fs::create_dir_all(&local_space_dir)?;

    // Clone manifest repository
    let spinner = Output::spinner("Cloning manifest repository...");
    match clone_repo(&manifest_url, &manifests_dir, None) {
        Ok(_) => {
            spinner.finish_with_message("Manifest cloned successfully");
        }
        Err(e) => {
            spinner.finish_with_message(format!("Failed to clone manifest: {}", e));
            // Clean up on failure
            let _ = std::fs::remove_dir_all(&target_dir);
            return Err(e.into());
        }
    }

    // Verify a supported manifest filename exists in the space repo.
    let manifest_path =
        if let Some(path) = manifest_paths::resolve_manifest_file_in_dir(&manifests_dir) {
            path
        } else {
            let _ = std::fs::remove_dir_all(&target_dir);
            anyhow::bail!(
                "No workspace manifest found in repository. \
             Expected gripspace.yml (preferred) or manifest.yaml/manifest.yml at repo root."
            );
        };

    // Create state file
    let state_path = gitgrip_dir.join("state.json");
    std::fs::write(&state_path, "{}")?;

    // Clone gripspaces if manifest includes them
    let manifest_content = std::fs::read_to_string(&manifest_path)?;
    let mut manifest = Manifest::parse_raw(&manifest_content)?;

    if let Some(ref gripspaces) = manifest.gripspaces {
        if !gripspaces.is_empty() {
            let spaces_dir = manifest_paths::spaces_dir(&target_dir);
            let spinner = Output::spinner(&format!("Cloning {} gripspace(s)...", gripspaces.len()));

            for gs_config in gripspaces {
                if let Err(e) = ensure_gripspace(&spaces_dir, gs_config) {
                    Output::warning(&format!(
                        "Gripspace '{}' clone failed: {}",
                        gs_config.url, e
                    ));
                    // Continue with remaining gripspaces
                    continue;
                }
            }

            spinner.finish_with_message("Gripspaces cloned");

            // Resolve gripspace includes
            if let Err(e) = resolve_all_gripspaces(&mut manifest, &spaces_dir) {
                Output::warning(&format!("Gripspace resolution failed: {}", e));
            }
        }
    }

    // Validate the (possibly merged) manifest
    if let Err(e) = manifest.validate() {
        Output::warning(&format!("Manifest validation: {}", e));
    }

    // Clone all repos from the manifest
    let repo_count = manifest.repos.len();
    if repo_count > 0 {
        println!();
        let spinner = Output::spinner(&format!("Cloning {} repositories...", repo_count));
        let mut cloned = 0;
        let mut failed = Vec::new();

        for (name, config) in &manifest.repos {
            let repo_path = target_dir.join(&config.path);
            if repo_path.exists() {
                continue;
            }

            // Resolve URL from config or remotes
            let url = config.url.clone().or_else(|| {
                config.remote.as_ref().and_then(|remote_name| {
                    manifest.remotes.as_ref()?.get(remote_name).map(|rc| {
                        let base = rc.fetch.trim_end_matches('/');
                        format!("{}/{}.git", base, name)
                    })
                })
            });

            let url = match url {
                Some(u) if !u.is_empty() => u,
                _ => {
                    failed.push((name.clone(), "no URL configured".to_string()));
                    continue;
                }
            };

            let revision = config
                .revision
                .as_deref()
                .or(manifest.settings.revision.as_deref());

            match clone_repo(&url, &repo_path, revision) {
                Ok(_) => {
                    cloned += 1;
                    spinner.set_message(format!("Cloned {}/{}: {}", cloned, repo_count, name));
                }
                Err(e) => {
                    failed.push((name.clone(), format!("{}", e)));
                }
            }
        }

        if failed.is_empty() {
            spinner.finish_with_message(format!("All {} repositories cloned", cloned));
        } else {
            spinner.finish_with_message(format!("{} cloned, {} failed", cloned, failed.len()));
            for (name, err) in &failed {
                Output::warning(&format!("  {} - {}", name, err));
            }
        }
    }

    // Apply linkfiles and copyfiles using the same cross-platform logic as gr sync
    if let Err(e) = super::link::apply_links(&target_dir, &manifest, false) {
        Output::warning(&format!("Link application: {}", e));
    }

    println!();
    Output::success("Workspace initialized and synced!");
    println!();
    println!("Next steps:");
    println!("  cd {:?}", target_dir);
    println!("  gr status   # Verify workspace state");

    Ok(())
}

/// Initialize workspace from existing local directories
async fn run_init_from_dirs(
    path: Option<&str>,
    dirs: &[String],
    interactive: bool,
    create_manifest: bool,
    manifest_name: Option<&str>,
    private: bool,
) -> anyhow::Result<()> {
    // Determine workspace root
    let workspace_root = match path {
        Some(p) => PathBuf::from(p),
        None => std::env::current_dir()?,
    };

    // Check for existing workspace
    let gitgrip_dir = workspace_root.join(".gitgrip");
    if gitgrip_dir.exists() {
        anyhow::bail!(
            "A gitgrip workspace already exists at {:?}. \
             Remove .gitgrip directory to reinitialize.",
            workspace_root
        );
    }

    Output::header(&format!("Discovering repositories in {:?}", workspace_root));
    println!();

    // Discover repos
    let specific_dirs: Option<&[String]> = if dirs.is_empty() { None } else { Some(dirs) };
    let mut discovered = discover_repos(&workspace_root, specific_dirs)?;

    if discovered.is_empty() {
        anyhow::bail!(
            "No git repositories found. Make sure directories contain .git folders.\n\
             Tip: Use --dirs to specify directories explicitly."
        );
    }

    // Ensure unique names
    ensure_unique_names(&mut discovered);

    // Display discovered repos
    println!("Found {} repositories:", discovered.len());
    println!();
    for repo in &discovered {
        let url_display = repo.url.as_deref().unwrap_or("(no remote)");
        let lang_display = repo
            .toolchain
            .as_ref()
            .map(|t| {
                let pm = t
                    .package_manager
                    .as_deref()
                    .map(|p| format!(" ({p})"))
                    .unwrap_or_default();
                format!(" [{}{}]", t.language, pm)
            })
            .unwrap_or_default();
        Output::list_item(&format!(
            "{}{}{} ({})",
            repo.name, lang_display, repo.path, url_display
        ));
    }
    println!();

    // Interactive mode
    let manifest = if interactive {
        match run_interactive_init(&workspace_root, &mut discovered)? {
            Some(m) => m,
            None => {
                Output::info("Initialization cancelled.");
                return Ok(());
            }
        }
    } else {
        generate_manifest(&discovered, &ManifestGenerationOptions::default())
    };

    // Create .gitgrip directory structure
    let manifests_dir = manifest_paths::main_space_dir(&workspace_root);
    let local_space_dir = manifest_paths::local_space_dir(&workspace_root);
    std::fs::create_dir_all(&manifests_dir)?;
    std::fs::create_dir_all(&local_space_dir)?;

    // Write manifest
    let manifest_path = manifests_dir.join(manifest_paths::PRIMARY_FILE_NAME);
    let yaml_content = manifest_to_yaml(&manifest)?;
    std::fs::write(&manifest_path, &yaml_content)?;

    // Compatibility mirror for legacy tooling/scripts.
    let legacy_manifest_path = manifest_paths::legacy_manifest_dir(&workspace_root)
        .join(manifest_paths::LEGACY_FILE_NAMES[0]);
    if let Some(parent) = legacy_manifest_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&legacy_manifest_path, &yaml_content)?;

    // Create state file
    let state_path = gitgrip_dir.join("state.json");
    std::fs::write(&state_path, "{}")?;

    // Initialize manifest as git repo
    init_manifest_repo(&manifests_dir)?;

    // Handle manifest repo creation on detected platform
    let mut manifest_remote_url = None;
    if create_manifest {
        if let Some(detected) = detect_common_platform(&discovered) {
            let repo_name = manifest_name.unwrap_or("workspace-manifest");

            println!();
            Output::info(&format!(
                "Detected platform: {} (owner: {}, confidence: {:.0}%)",
                detected.platform,
                detected.owner,
                detected.confidence * 100.0
            ));

            let suggested_url = suggest_manifest_url(detected.platform, &detected.owner, repo_name);
            Output::info(&format!("Creating manifest repo: {}", suggested_url));

            // Create the repository
            let adapter = platform::get_platform_adapter(detected.platform, None);
            match adapter
                .create_repository(
                    &detected.owner,
                    repo_name,
                    Some("Workspace manifest repository for gitgrip"),
                    private,
                )
                .await
            {
                Ok(clone_url) => {
                    Output::success(&format!("Created repository: {}", clone_url));

                    // Add remote to manifest repo
                    let mut cmd = Command::new("git");
                    cmd.args(["remote", "add", "origin", &clone_url])
                        .current_dir(&manifests_dir);
                    log_cmd(&cmd);
                    let output = cmd.output()?;

                    if output.status.success() {
                        Output::success("Added remote 'origin' to manifest repo");
                        manifest_remote_url = Some(clone_url);

                        // Push initial commit
                        let mut cmd = Command::new("git");
                        cmd.args(["push", "-u", "origin", "main"])
                            .current_dir(&manifests_dir);
                        log_cmd(&cmd);
                        let push_output = cmd.output()?;

                        if push_output.status.success() {
                            Output::success("Pushed initial commit to remote");
                        } else {
                            // Try with master branch
                            let mut cmd = Command::new("git");
                            cmd.args(["push", "-u", "origin", "master"])
                                .current_dir(&manifests_dir);
                            log_cmd(&cmd);
                            let push_output = cmd.output()?;

                            if push_output.status.success() {
                                Output::success("Pushed initial commit to remote");
                            } else {
                                let stderr = String::from_utf8_lossy(&push_output.stderr);
                                Output::warning(&format!(
                                    "Could not push: {}. You may need to push manually.",
                                    stderr.trim()
                                ));
                            }
                        }
                    } else {
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        Output::warning(&format!(
                            "Could not add remote: {}. You may need to add it manually.",
                            stderr.trim()
                        ));
                    }
                }
                Err(e) => {
                    Output::warning(&format!(
                        "Could not create repository on {}: {}",
                        detected.platform, e
                    ));
                    Output::info("You can create the repository manually and add it as a remote.");
                }
            }
        } else {
            Output::warning("Could not detect platform from repositories. No remote URLs found.");
            Output::info("You can create the manifest repository manually and add it as a remote.");
        }
    }

    println!();
    Output::success("Workspace initialized successfully!");
    println!();
    println!("Manifest created at: {}", manifest_path.display());
    println!();

    if let Some(url) = manifest_remote_url {
        println!("Manifest remote: {}", url);
        println!();
        println!("Next steps:");
        println!("  1. Review the manifest: cat .gitgrip/spaces/main/gripspace.yml");
        println!("     (legacy mirror at .gitgrip/manifests/manifest.yaml for compatibility)");
        println!("  2. Run 'gr status' to verify your workspace");
    } else {
        println!("Next steps:");
        println!("  1. Review the manifest: cat .gitgrip/spaces/main/gripspace.yml");
        println!("     (legacy mirror at .gitgrip/manifests/manifest.yaml for compatibility)");
        println!("  2. Add a remote to the manifest repo:");
        println!("     cd .gitgrip/spaces/main && git remote add origin <your-manifest-url>");
        println!("  3. Run 'gr status' to verify your workspace");
    }

    Ok(())
}

/// Discover git repositories in the given base directory
fn discover_repos(
    base_dir: &Path,
    specific_dirs: Option<&[String]>,
) -> anyhow::Result<Vec<DiscoveredRepo>> {
    let mut repos = Vec::new();

    let dirs_to_scan: Vec<PathBuf> = match specific_dirs {
        Some(dirs) => dirs
            .iter()
            .map(|d| {
                let p = PathBuf::from(d);
                if p.is_absolute() {
                    p
                } else {
                    base_dir.join(d)
                }
            })
            .collect(),
        None => {
            // Scan immediate children of base_dir
            std::fs::read_dir(base_dir)?
                .filter_map(|entry| entry.ok())
                .map(|entry| entry.path())
                .filter(|p| p.is_dir())
                .filter(|p| {
                    // Skip hidden directories
                    p.file_name()
                        .and_then(|n| n.to_str())
                        .map(|n| !n.starts_with('.'))
                        .unwrap_or(false)
                })
                .collect()
        }
    };

    for dir in dirs_to_scan {
        if let Some(repo) = try_discover_repo(base_dir, &dir)? {
            repos.push(repo);
        }
    }

    // Sort by name for consistent ordering
    repos.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(repos)
}

/// Try to discover a repository in the given directory
fn try_discover_repo(workspace_root: &Path, dir: &Path) -> anyhow::Result<Option<DiscoveredRepo>> {
    // Check if it's a git repository
    let git_dir = dir.join(".git");
    if !git_dir.exists() {
        return Ok(None);
    }

    // Open the repository
    let repo = match Repository::open(dir) {
        Ok(r) => r,
        Err(_) => return Ok(None),
    };

    // Get directory name for repo name
    let name = dir
        .file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| "repo".to_string());

    // Get relative path from workspace root
    let path = dir
        .strip_prefix(workspace_root)
        .map(|p| format!("./{}", p.display()))
        .unwrap_or_else(|_| dir.display().to_string());

    // Get remote URL (prefer origin)
    let url = get_remote_url(&repo);

    // Detect default branch
    let default_branch = detect_default_branch(&repo).unwrap_or_else(|_| "main".to_string());

    // Detect language and toolchain
    let toolchain = detect_toolchain(dir);

    Ok(Some(DiscoveredRepo {
        name,
        path,
        absolute_path: dir.to_path_buf(),
        url,
        default_branch,
        toolchain,
    }))
}

/// Get the remote URL from a repository (preferring origin)
fn get_remote_url(repo: &Repository) -> Option<String> {
    // Try origin first
    if let Ok(remote) = repo.find_remote("origin") {
        if let Some(url) = remote.url() {
            return Some(url.to_string());
        }
    }

    // Try any remote
    if let Ok(remotes) = repo.remotes() {
        for remote_name in remotes.iter().flatten() {
            if let Ok(remote) = repo.find_remote(remote_name) {
                if let Some(url) = remote.url() {
                    return Some(url.to_string());
                }
            }
        }
    }

    None
}

/// Detect the default branch of a repository by checking the remote first
fn detect_default_branch(repo: &Repository) -> anyhow::Result<String> {
    // 1. Try origin/HEAD symbolic ref (set by git clone or git remote set-head)
    if let Ok(reference) = repo.find_reference("refs/remotes/origin/HEAD") {
        if let Ok(resolved) = reference.resolve() {
            if let Some(name) = resolved.shorthand() {
                // name is "origin/main" — strip the remote prefix
                if let Some(branch) = name.strip_prefix("origin/") {
                    return Ok(branch.to_string());
                }
            }
        }
    }

    // 2. Try common remote tracking branches
    for branch_name in &["main", "master"] {
        if repo
            .find_branch(&format!("origin/{}", branch_name), git2::BranchType::Remote)
            .is_ok()
        {
            return Ok(branch_name.to_string());
        }
    }

    // 3. Fall back to common local branch names
    for branch_name in &["main", "master", "develop"] {
        if repo
            .find_branch(branch_name, git2::BranchType::Local)
            .is_ok()
        {
            return Ok(branch_name.to_string());
        }
    }

    // 4. Default to main
    Ok("main".to_string())
}

/// Ensure all repository names are unique by adding suffixes
fn ensure_unique_names(repos: &mut [DiscoveredRepo]) {
    let mut name_counts: HashMap<String, usize> = HashMap::new();

    // First pass: count occurrences
    for repo in repos.iter() {
        *name_counts.entry(repo.name.clone()).or_insert(0) += 1;
    }

    // Second pass: rename duplicates, avoiding collisions with existing names
    let all_names: HashSet<String> = repos.iter().map(|r| r.name.clone()).collect();
    let mut used_names: HashSet<String> = all_names;
    let mut name_indices: HashMap<String, usize> = HashMap::new();
    for repo in repos.iter_mut() {
        if name_counts[&repo.name] > 1 {
            let idx = name_indices.entry(repo.name.clone()).or_insert(1);
            if *idx > 1 {
                let base = repo.name.clone();
                let mut suffix = *idx;
                let mut candidate = format!("{}-{}", base, suffix);
                while used_names.contains(&candidate) {
                    suffix += 1;
                    candidate = format!("{}-{}", base, suffix);
                }
                repo.name = candidate.clone();
                used_names.insert(candidate);
            } else {
                // First occurrence keeps original name (already in used_names)
            }
            *idx += 1;
        }
    }
}

/// Generate a manifest from discovered repositories
/// Options controlling what gets generated in the manifest.
struct ManifestGenerationOptions {
    /// Include post-sync hooks for repos with detected install commands
    include_post_sync_hooks: bool,
    /// Agent context targets to include
    agent_targets: Vec<AgentContextTarget>,
    /// Repos selected for post-sync hooks (if None, include all with install commands)
    post_sync_repos: Option<Vec<String>>,
}

impl Default for ManifestGenerationOptions {
    fn default() -> Self {
        Self {
            include_post_sync_hooks: true,
            agent_targets: Vec::new(),
            post_sync_repos: None,
        }
    }
}

fn generate_manifest(repos: &[DiscoveredRepo], options: &ManifestGenerationOptions) -> Manifest {
    let mut repo_configs = HashMap::new();
    let mut scripts = HashMap::new();
    let mut build_steps = Vec::new();
    let mut test_steps = Vec::new();
    let mut post_sync_hooks = Vec::new();

    for repo in repos {
        let url = repo
            .url
            .clone()
            .unwrap_or_else(|| format!("git@github.com:OWNER/{}.git", repo.name));

        // Build agent config from detected toolchain
        let agent = repo.toolchain.as_ref().map(|t| RepoAgentConfig {
            description: None,
            language: Some(t.language.clone()),
            build: t.build.clone(),
            test: t.test.clone(),
            lint: t.lint.clone(),
            format: t.format.clone(),
        });

        // Generate per-repo scripts and aggregate steps
        if let Some(tc) = &repo.toolchain {
            if let Some(build) = &tc.build {
                scripts.insert(
                    format!("build-{}", repo.name),
                    WorkspaceScript {
                        description: Some(format!("Build {}", repo.name)),
                        command: Some(build.clone()),
                        cwd: Some(repo.path.clone()),
                        steps: None,
                    },
                );
                build_steps.push(ScriptStep {
                    name: format!("Build {}", repo.name),
                    command: build.clone(),
                    cwd: Some(repo.path.clone()),
                });
            }
            if let Some(test) = &tc.test {
                scripts.insert(
                    format!("test-{}", repo.name),
                    WorkspaceScript {
                        description: Some(format!("Test {}", repo.name)),
                        command: Some(test.clone()),
                        cwd: Some(repo.path.clone()),
                        steps: None,
                    },
                );
                test_steps.push(ScriptStep {
                    name: format!("Test {}", repo.name),
                    command: test.clone(),
                    cwd: Some(repo.path.clone()),
                });
            }

            // Collect post-sync hooks for repos with install commands
            if options.include_post_sync_hooks {
                if let Some(install) = &tc.install {
                    let include = match &options.post_sync_repos {
                        Some(selected) => selected.contains(&repo.name),
                        None => true,
                    };
                    if include {
                        post_sync_hooks.push(HookCommand {
                            command: install.clone(),
                            cwd: Some(repo.path.clone()),
                            name: Some(format!("Install {}", repo.name)),
                            repos: None,
                            condition: Default::default(),
                        });
                    }
                }
            }
        }

        repo_configs.insert(
            repo.name.clone(),
            RepoConfig {
                url: Some(url),
                remote: None,
                path: repo.path.clone(),
                revision: Some(repo.default_branch.clone()),
                target: None,
                sync_remote: None,
                push_remote: None,
                copyfile: None,
                linkfile: None,
                platform: None,
                reference: false,
                groups: Vec::new(),
                agent,
                clone_strategy: None,
            },
        );
    }

    // Add aggregated build-all / test-all scripts
    if build_steps.len() > 1 {
        scripts.insert(
            "build-all".to_string(),
            WorkspaceScript {
                description: Some("Build all repositories".to_string()),
                command: None,
                cwd: None,
                steps: Some(build_steps),
            },
        );
    }
    if test_steps.len() > 1 {
        scripts.insert(
            "test-all".to_string(),
            WorkspaceScript {
                description: Some("Test all repositories".to_string()),
                command: None,
                cwd: None,
                steps: Some(test_steps),
            },
        );
    }

    // Build workspace config
    let hooks = if post_sync_hooks.is_empty() {
        None
    } else {
        Some(WorkspaceHooks {
            post_sync: Some(post_sync_hooks),
            post_checkout: None,
        })
    };

    let workspace_agent = WorkspaceAgentConfig {
        description: Some(format!(
            "Multi-repo workspace with {} repositories",
            repos.len()
        )),
        conventions: vec![
            "Use `gr` for all git operations (not raw git/gh)".to_string(),
            "All development on feature branches — never push to main".to_string(),
        ],
        workflows: {
            let mut wf = HashMap::new();
            if scripts.contains_key("build-all") {
                wf.insert("build".to_string(), "gr run build-all".to_string());
            } else if let Some((name, _)) = scripts.iter().find(|(k, _)| k.starts_with("build-")) {
                wf.insert("build".to_string(), format!("gr run {name}"));
            }
            if scripts.contains_key("test-all") {
                wf.insert("test".to_string(), "gr run test-all".to_string());
            } else if let Some((name, _)) = scripts.iter().find(|(k, _)| k.starts_with("test-")) {
                wf.insert("test".to_string(), format!("gr run {name}"));
            }
            wf.insert("sync".to_string(), "gr sync".to_string());
            Some(wf)
        },
        context_source: None,
        targets: if options.agent_targets.is_empty() {
            None
        } else {
            Some(options.agent_targets.clone())
        },
    };

    let workspace = Some(WorkspaceConfig {
        env: None,
        scripts: if scripts.is_empty() {
            None
        } else {
            Some(scripts)
        },
        hooks,
        ci: None,
        agent: Some(workspace_agent),
        release: None,
    });

    Manifest {
        version: 2,
        remotes: None,
        gripspaces: None,
        manifest: None,
        repos: repo_configs,
        settings: ManifestSettings::default(),
        workspace,
    }
}

/// Convert a manifest to YAML string with section comments.
fn manifest_to_yaml(manifest: &Manifest) -> anyhow::Result<String> {
    let yaml = serde_yaml::to_string(manifest)?;
    Ok(add_yaml_section_comments(&yaml))
}

/// Post-process YAML to add section header comments.
fn add_yaml_section_comments(yaml: &str) -> String {
    let mut result = String::with_capacity(yaml.len() + 200);
    result.push_str("# Generated by gr init --from-dirs\n");

    for line in yaml.lines() {
        if line == "repos:" {
            result.push_str("\n# Repository definitions\n");
        } else if line == "workspace:" {
            result.push_str("\n# Workspace configuration (scripts, hooks, agent context)\n");
        } else if line == "settings:" {
            result.push_str("\n# Global settings\n");
        }
        result.push_str(line);
        result.push('\n');
    }
    result
}

/// Run interactive initialization
fn run_interactive_init(
    _workspace_root: &Path,
    discovered: &mut Vec<DiscoveredRepo>,
) -> anyhow::Result<Option<Manifest>> {
    let theme = ColorfulTheme::default();

    let all_discovered = discovered.clone();

    'wizard: loop {
        // Reset to full list on each iteration (in case "Start over" was selected)
        *discovered = all_discovered.clone();

        // Step 1: Review and select repositories
        let include_all = Confirm::with_theme(&theme)
            .with_prompt(format!("Include all {} repositories?", discovered.len()))
            .default(true)
            .interact()?;

        if !include_all {
            let items: Vec<String> = discovered
                .iter()
                .map(|r| {
                    let lang = r
                        .toolchain
                        .as_ref()
                        .map(|t| format!(" [{}]", t.language))
                        .unwrap_or_default();
                    format!("{}{} ({})", r.name, lang, r.path)
                })
                .collect();

            let defaults: Vec<bool> = discovered.iter().map(|_| true).collect();

            let selected = MultiSelect::with_theme(&theme)
                .with_prompt("Select repositories to include")
                .items(&items)
                .defaults(&defaults)
                .interact()?;

            if selected.is_empty() {
                Output::warning("No repositories selected. Please select at least one.");
                continue 'wizard;
            }

            // Keep only selected repos
            let mut kept = Vec::new();
            for (i, repo) in discovered.drain(..).enumerate() {
                if selected.contains(&i) {
                    kept.push(repo);
                }
            }
            *discovered = kept;
        }

        // Step 2: Post-sync hooks
        let installable: Vec<(usize, String, String)> = discovered
            .iter()
            .enumerate()
            .filter_map(|(i, r)| {
                r.toolchain.as_ref().and_then(|t| {
                    t.install
                        .as_ref()
                        .map(|cmd| (i, r.name.clone(), cmd.clone()))
                })
            })
            .collect();

        let mut post_sync_repos: Option<Vec<String>> = None;

        if !installable.is_empty() {
            let hook_items: Vec<String> = installable
                .iter()
                .map(|(_, name, cmd)| format!("{}{}", name, cmd))
                .collect();

            let hook_defaults: Vec<bool> = installable.iter().map(|_| true).collect();

            println!();
            let selected_hooks = MultiSelect::with_theme(&theme)
                .with_prompt("Configure post-sync hooks? (auto-install dependencies after gr sync)")
                .items(&hook_items)
                .defaults(&hook_defaults)
                .interact()?;

            let selected_names: Vec<String> = selected_hooks
                .iter()
                .map(|&i| installable[i].1.clone())
                .collect();
            post_sync_repos = Some(selected_names);
        }

        // Step 3: Agent context targets
        let agent_options = vec![
            "Yes, for Claude Code",
            "Yes, for all tools (Claude, OpenCode, Codex)",
            "Skip",
        ];

        println!();
        let agent_selection = Select::with_theme(&theme)
            .with_prompt("Generate agent context files?")
            .items(&agent_options)
            .default(0)
            .interact()?;

        let agent_targets = match agent_selection {
            0 => vec![AgentContextTarget {
                format: "claude".to_string(),
                dest: ".claude/skills/{repo}/SKILL.md".to_string(),
                compose_with: None,
            }],
            1 => vec![
                AgentContextTarget {
                    format: "claude".to_string(),
                    dest: ".claude/skills/{repo}/SKILL.md".to_string(),
                    compose_with: None,
                },
                AgentContextTarget {
                    format: "opencode".to_string(),
                    dest: ".opencode/skill/{repo}/SKILL.md".to_string(),
                    compose_with: None,
                },
                AgentContextTarget {
                    format: "codex".to_string(),
                    dest: ".codex/skills/{repo}/SKILL.md".to_string(),
                    compose_with: None,
                },
            ],
            _ => vec![],
        };

        // Step 4: Generate and review manifest
        let options = ManifestGenerationOptions {
            include_post_sync_hooks: true,
            agent_targets,
            post_sync_repos,
        };

        let manifest = generate_manifest(discovered, &options);
        let yaml = manifest_to_yaml(&manifest)?;

        println!();
        println!("Generated gripspace.yml:");
        println!("─────────────────────────────────────────");
        println!("{}", yaml);
        println!("─────────────────────────────────────────");
        println!();

        let review_options = vec!["Accept", "Edit in editor", "Start over"];

        let review_selection = Select::with_theme(&theme)
            .with_prompt("Review the manifest")
            .items(&review_options)
            .default(0)
            .interact()?;

        match review_selection {
            0 => return Ok(Some(manifest)),
            1 => {
                // Edit in external editor
                if let Some(edited_yaml) = Editor::new().extension(".yaml").edit(&yaml)? {
                    match Manifest::parse(&edited_yaml) {
                        Ok(edited_manifest) => {
                            println!();
                            Output::success("Manifest validated successfully.");
                            return Ok(Some(edited_manifest));
                        }
                        Err(e) => {
                            Output::error(&format!("Invalid YAML: {}", e));
                            println!("Please fix the errors and try again.");
                            continue 'wizard;
                        }
                    }
                } else {
                    Output::info("No changes made.");
                    continue 'wizard;
                }
            }
            2 => continue 'wizard,
            _ => unreachable!(),
        }
    }
}

/// Initialize the manifest directory as a git repository
fn init_manifest_repo(manifests_dir: &Path) -> anyhow::Result<()> {
    // Initialize git repo
    let mut cmd = Command::new("git");
    cmd.args(["init"]).current_dir(manifests_dir);
    log_cmd(&cmd);
    let output = cmd.output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Failed to initialize manifest git repo: {}", stderr);
    }

    let manifest_file = manifest_paths::resolve_manifest_file_in_dir(manifests_dir)
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
        .unwrap_or_else(|| manifest_paths::PRIMARY_FILE_NAME.to_string());

    // Stage manifest file
    let mut cmd = Command::new("git");
    cmd.args(["add", &manifest_file]).current_dir(manifests_dir);
    log_cmd(&cmd);
    let output = cmd.output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Failed to stage {}: {}", manifest_file, stderr);
    }

    // Create initial commit
    let mut cmd = Command::new("git");
    cmd.args([
        "commit",
        "-m",
        "Initial manifest\n\nGenerated by gr init --from-dirs",
    ])
    .current_dir(manifests_dir);
    log_cmd(&cmd);
    let output = cmd.output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Don't fail if commit fails (e.g., no git user configured)
        Output::warning(&format!(
            "Could not create initial commit: {}. You may need to commit manually.",
            stderr.trim()
        ));
    }

    Ok(())
}

/// Extract repository name from URL
fn extract_repo_name(url: &str) -> Option<String> {
    // Handle SSH URLs: git@github.com:owner/repo.git
    if url.starts_with("git@") {
        let parts: Vec<&str> = url.split('/').collect();
        if let Some(last) = parts.last() {
            return Some(last.trim_end_matches(".git").to_string());
        }
    }

    // Handle HTTPS URLs: https://github.com/owner/repo.git
    if url.starts_with("https://") || url.starts_with("http://") {
        let parts: Vec<&str> = url.split('/').collect();
        if let Some(last) = parts.last() {
            return Some(last.trim_end_matches(".git").to_string());
        }
    }

    None
}

/// Result of platform detection from discovered repos
#[derive(Debug, Clone)]
pub struct DetectedPlatform {
    /// The detected platform type
    pub platform: PlatformType,
    /// The owner/organization on that platform
    pub owner: String,
    /// Confidence level (number of repos with this platform / total repos with remotes)
    pub confidence: f32,
}

/// Analyze discovered repos and detect their common platform
///
/// Returns the most common platform among repos with remotes, along with
/// the detected owner/organization. Returns None if no repos have remotes
/// or if there's no clear majority platform.
pub fn detect_common_platform(repos: &[DiscoveredRepo]) -> Option<DetectedPlatform> {
    // Filter to repos with URLs
    let repos_with_urls: Vec<_> = repos.iter().filter_map(|r| r.url.as_ref()).collect();

    if repos_with_urls.is_empty() {
        return None;
    }

    // Count platforms and collect owners
    let mut platform_counts: HashMap<PlatformType, Vec<String>> = HashMap::new();

    for url in &repos_with_urls {
        let detected_platform = platform::detect_platform(url);
        let adapter = platform::get_platform_adapter(detected_platform, None);

        if let Some(info) = adapter.parse_repo_url(url) {
            platform_counts
                .entry(detected_platform)
                .or_default()
                .push(info.owner);
        } else {
            // URL matches platform but couldn't be parsed - still count it
            platform_counts.entry(detected_platform).or_default();
        }
    }

    // Find the platform with the most repos
    let (platform, owners) = platform_counts
        .into_iter()
        .max_by_key(|(_, owners)| owners.len())?;

    // Find the most common owner for this platform
    let mut owner_counts: HashMap<String, usize> = HashMap::new();
    for owner in &owners {
        *owner_counts.entry(owner.clone()).or_insert(0) += 1;
    }

    let (owner, _) = owner_counts.into_iter().max_by_key(|(_, count)| *count)?;

    let confidence = owners.len() as f32 / repos_with_urls.len() as f32;

    Some(DetectedPlatform {
        platform,
        owner,
        confidence,
    })
}

/// Generate a suggested manifest repo URL based on the detected platform
pub fn suggest_manifest_url(platform: PlatformType, owner: &str, name: &str) -> String {
    match platform {
        PlatformType::GitHub => format!("git@github.com:{}/{}.git", owner, name),
        PlatformType::GitLab => format!("git@gitlab.com:{}/{}.git", owner, name),
        PlatformType::AzureDevOps => {
            // Azure DevOps owner format: org/project
            // SSH URL format: git@ssh.dev.azure.com:v3/org/project/repo
            format!("git@ssh.dev.azure.com:v3/{}/{}.git", owner, name)
        }
        PlatformType::Bitbucket => format!("git@bitbucket.org:{}/{}.git", owner, name),
    }
}

/// Generate an HTTPS URL for the manifest repo based on the detected platform
pub fn suggest_manifest_https_url(platform: PlatformType, owner: &str, name: &str) -> String {
    match platform {
        PlatformType::GitHub => format!("https://github.com/{}/{}.git", owner, name),
        PlatformType::GitLab => format!("https://gitlab.com/{}/{}.git", owner, name),
        PlatformType::AzureDevOps => {
            // Azure DevOps owner format: org/project
            // HTTPS URL format: https://dev.azure.com/org/project/_git/repo
            let parts: Vec<&str> = owner.split('/').collect();
            if parts.len() >= 2 {
                format!(
                    "https://dev.azure.com/{}/{}/_git/{}",
                    parts[0], parts[1], name
                )
            } else {
                // Fallback: use owner as both org and project
                format!("https://dev.azure.com/{}/{}/_git/{}", owner, owner, name)
            }
        }
        PlatformType::Bitbucket => format!("https://bitbucket.org/{}/{}.git", owner, name),
    }
}

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

    #[test]
    fn test_extract_repo_name_ssh() {
        assert_eq!(
            extract_repo_name("git@github.com:user/my-workspace.git"),
            Some("my-workspace".to_string())
        );
    }

    #[test]
    fn test_extract_repo_name_https() {
        assert_eq!(
            extract_repo_name("https://github.com/user/my-workspace.git"),
            Some("my-workspace".to_string())
        );
    }

    #[test]
    fn test_extract_repo_name_no_extension() {
        assert_eq!(
            extract_repo_name("https://github.com/user/workspace"),
            Some("workspace".to_string())
        );
    }

    #[test]
    fn test_ensure_unique_names() {
        let mut repos = vec![
            DiscoveredRepo {
                name: "app".to_string(),
                path: "./app1".to_string(),
                absolute_path: PathBuf::from("/tmp/app1"),
                url: None,
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "app".to_string(),
                path: "./app2".to_string(),
                absolute_path: PathBuf::from("/tmp/app2"),
                url: None,
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "backend".to_string(),
                path: "./backend".to_string(),
                absolute_path: PathBuf::from("/tmp/backend"),
                url: None,
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        ensure_unique_names(&mut repos);

        // First "app" keeps its name, second gets "-2"
        assert_eq!(repos[0].name, "app");
        assert_eq!(repos[1].name, "app-2");
        assert_eq!(repos[2].name, "backend");
    }

    #[test]
    fn test_generate_manifest() {
        let repos = vec![
            DiscoveredRepo {
                name: "frontend".to_string(),
                path: "./frontend".to_string(),
                absolute_path: PathBuf::from("/tmp/frontend"),
                url: Some("git@github.com:org/frontend.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "backend".to_string(),
                path: "./backend".to_string(),
                absolute_path: PathBuf::from("/tmp/backend"),
                url: None,
                default_branch: "master".to_string(),
                toolchain: None,
            },
        ];

        let manifest = generate_manifest(&repos, &ManifestGenerationOptions::default());

        assert_eq!(manifest.repos.len(), 2);
        assert!(manifest.repos.contains_key("frontend"));
        assert!(manifest.repos.contains_key("backend"));
        assert_eq!(
            manifest.repos["frontend"].url,
            Some("git@github.com:org/frontend.git".to_string())
        );
        assert_eq!(
            manifest.repos["frontend"].revision,
            Some("main".to_string())
        );
        // Backend should have placeholder URL
        assert!(manifest.repos["backend"]
            .url
            .as_deref()
            .unwrap()
            .contains("OWNER"));
        assert_eq!(
            manifest.repos["backend"].revision,
            Some("master".to_string())
        );
    }

    #[test]
    fn test_discover_repos_empty() {
        let temp = TempDir::new().unwrap();
        let repos = discover_repos(temp.path(), None).unwrap();
        assert!(repos.is_empty());
    }

    #[test]
    fn test_discover_repos_with_git_dir() {
        let temp = TempDir::new().unwrap();

        // Create a subdirectory with a git repo
        let repo_dir = temp.path().join("my-repo");
        std::fs::create_dir_all(&repo_dir).unwrap();
        Repository::init(&repo_dir).unwrap();

        let repos = discover_repos(temp.path(), None).unwrap();
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "my-repo");
    }

    #[test]
    fn test_discover_repos_skips_hidden() {
        let temp = TempDir::new().unwrap();

        // Create a hidden directory with a git repo
        let hidden_dir = temp.path().join(".hidden-repo");
        std::fs::create_dir_all(&hidden_dir).unwrap();
        Repository::init(&hidden_dir).unwrap();

        // Create a normal directory with a git repo
        let repo_dir = temp.path().join("visible-repo");
        std::fs::create_dir_all(&repo_dir).unwrap();
        Repository::init(&repo_dir).unwrap();

        let repos = discover_repos(temp.path(), None).unwrap();
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "visible-repo");
    }

    #[test]
    fn test_manifest_to_yaml() {
        let repos = vec![DiscoveredRepo {
            name: "test".to_string(),
            path: "./test".to_string(),
            absolute_path: PathBuf::from("/tmp/test"),
            url: Some("git@github.com:org/test.git".to_string()),
            default_branch: "main".to_string(),
            toolchain: None,
        }];

        let manifest = generate_manifest(&repos, &ManifestGenerationOptions::default());
        let yaml = manifest_to_yaml(&manifest).unwrap();

        assert!(yaml.contains("repos:"));
        assert!(yaml.contains("test:"));
        assert!(yaml.contains("git@github.com:org/test.git"));
    }

    #[test]
    fn test_generate_manifest_with_toolchains() {
        use crate::core::detect::DetectedToolchain;

        let repos = vec![
            DiscoveredRepo {
                name: "api".to_string(),
                path: "./api".to_string(),
                absolute_path: PathBuf::from("/tmp/api"),
                url: Some("git@github.com:org/api.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: Some(DetectedToolchain {
                    language: "rust".to_string(),
                    package_manager: Some("cargo".to_string()),
                    build: Some("cargo build".to_string()),
                    test: Some("cargo test".to_string()),
                    lint: Some("cargo clippy".to_string()),
                    format: Some("cargo fmt".to_string()),
                    install: None,
                }),
            },
            DiscoveredRepo {
                name: "web".to_string(),
                path: "./web".to_string(),
                absolute_path: PathBuf::from("/tmp/web"),
                url: Some("git@github.com:org/web.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: Some(DetectedToolchain {
                    language: "typescript".to_string(),
                    package_manager: Some("pnpm".to_string()),
                    build: Some("pnpm run build".to_string()),
                    test: Some("pnpm test".to_string()),
                    lint: Some("pnpm run lint".to_string()),
                    format: Some("pnpm run format".to_string()),
                    install: Some("pnpm install".to_string()),
                }),
            },
        ];

        let manifest = generate_manifest(&repos, &ManifestGenerationOptions::default());

        // Version should be 2
        assert_eq!(manifest.version, 2);

        // Agent config should be populated
        let api = &manifest.repos["api"];
        let agent = api.agent.as_ref().unwrap();
        assert_eq!(agent.language.as_deref(), Some("rust"));
        assert_eq!(agent.build.as_deref(), Some("cargo build"));
        assert_eq!(agent.test.as_deref(), Some("cargo test"));

        let web = &manifest.repos["web"];
        let agent = web.agent.as_ref().unwrap();
        assert_eq!(agent.language.as_deref(), Some("typescript"));

        // Workspace scripts should exist
        let ws = manifest.workspace.as_ref().unwrap();
        let scripts = ws.scripts.as_ref().unwrap();
        assert!(scripts.contains_key("build-api"));
        assert!(scripts.contains_key("test-api"));
        assert!(scripts.contains_key("build-web"));
        assert!(scripts.contains_key("test-web"));
        assert!(scripts.contains_key("build-all"));
        assert!(scripts.contains_key("test-all"));

        // build-all should have steps
        let build_all = &scripts["build-all"];
        assert!(build_all.steps.is_some());
        assert_eq!(build_all.steps.as_ref().unwrap().len(), 2);

        // Post-sync hooks should include web (has install) but not api
        let hooks = ws.hooks.as_ref().unwrap();
        let post_sync = hooks.post_sync.as_ref().unwrap();
        assert_eq!(post_sync.len(), 1);
        assert_eq!(post_sync[0].command, "pnpm install");

        // Agent workflows should reference build-all/test-all
        let agent = ws.agent.as_ref().unwrap();
        let workflows = agent.workflows.as_ref().unwrap();
        assert_eq!(workflows["build"], "gr run build-all");
        assert_eq!(workflows["test"], "gr run test-all");
    }

    #[test]
    fn test_generate_manifest_single_repo_workflows() {
        use crate::core::detect::DetectedToolchain;

        let repos = vec![DiscoveredRepo {
            name: "app".to_string(),
            path: "./app".to_string(),
            absolute_path: PathBuf::from("/tmp/app"),
            url: Some("git@github.com:org/app.git".to_string()),
            default_branch: "main".to_string(),
            toolchain: Some(DetectedToolchain {
                language: "rust".to_string(),
                package_manager: Some("cargo".to_string()),
                build: Some("cargo build".to_string()),
                test: Some("cargo test".to_string()),
                lint: None,
                format: None,
                install: None,
            }),
        }];

        let manifest = generate_manifest(&repos, &ManifestGenerationOptions::default());

        let ws = manifest.workspace.as_ref().unwrap();
        let scripts = ws.scripts.as_ref().unwrap();

        // Single repo should NOT have build-all/test-all
        assert!(!scripts.contains_key("build-all"));
        assert!(!scripts.contains_key("test-all"));
        assert!(scripts.contains_key("build-app"));
        assert!(scripts.contains_key("test-app"));

        // Workflows should reference the single-repo script, not build-all
        let agent = ws.agent.as_ref().unwrap();
        let workflows = agent.workflows.as_ref().unwrap();
        assert_eq!(workflows["build"], "gr run build-app");
        assert_eq!(workflows["test"], "gr run test-app");
    }

    #[test]
    fn test_generate_manifest_roundtrip() {
        use crate::core::detect::DetectedToolchain;

        let repos = vec![DiscoveredRepo {
            name: "myrepo".to_string(),
            path: "./myrepo".to_string(),
            absolute_path: PathBuf::from("/tmp/myrepo"),
            url: Some("git@github.com:org/myrepo.git".to_string()),
            default_branch: "main".to_string(),
            toolchain: Some(DetectedToolchain {
                language: "python".to_string(),
                package_manager: Some("uv".to_string()),
                build: None,
                test: Some("pytest".to_string()),
                lint: Some("ruff check .".to_string()),
                format: Some("ruff format .".to_string()),
                install: Some("uv sync".to_string()),
            }),
        }];

        let manifest = generate_manifest(&repos, &ManifestGenerationOptions::default());
        let yaml = manifest_to_yaml(&manifest).unwrap();

        // Round-trip: serialize -> parse should succeed
        let parsed = Manifest::parse(&yaml).unwrap();
        assert_eq!(parsed.version, 2);
        assert_eq!(parsed.repos.len(), 1);
        assert!(parsed.repos.contains_key("myrepo"));
        let agent = parsed.repos["myrepo"].agent.as_ref().unwrap();
        assert_eq!(agent.language.as_deref(), Some("python"));
    }

    #[test]
    fn test_generate_manifest_post_sync_filtering() {
        use crate::core::detect::DetectedToolchain;

        let repos = vec![
            DiscoveredRepo {
                name: "a".to_string(),
                path: "./a".to_string(),
                absolute_path: PathBuf::from("/tmp/a"),
                url: Some("git@github.com:org/a.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: Some(DetectedToolchain {
                    language: "typescript".to_string(),
                    package_manager: Some("npm".to_string()),
                    build: Some("npm run build".to_string()),
                    test: Some("npm test".to_string()),
                    lint: None,
                    format: None,
                    install: Some("npm install".to_string()),
                }),
            },
            DiscoveredRepo {
                name: "b".to_string(),
                path: "./b".to_string(),
                absolute_path: PathBuf::from("/tmp/b"),
                url: Some("git@github.com:org/b.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: Some(DetectedToolchain {
                    language: "ruby".to_string(),
                    package_manager: Some("bundler".to_string()),
                    build: None,
                    test: Some("bundle exec rspec".to_string()),
                    lint: None,
                    format: None,
                    install: Some("bundle install".to_string()),
                }),
            },
        ];

        // Only include repo "a" in post-sync hooks
        let options = ManifestGenerationOptions {
            include_post_sync_hooks: true,
            agent_targets: vec![],
            post_sync_repos: Some(vec!["a".to_string()]),
        };

        let manifest = generate_manifest(&repos, &options);
        let hooks = manifest.workspace.as_ref().unwrap().hooks.as_ref().unwrap();
        let post_sync = hooks.post_sync.as_ref().unwrap();
        assert_eq!(post_sync.len(), 1);
        assert_eq!(post_sync[0].command, "npm install");
    }

    #[test]
    fn test_detect_github_platform() {
        let repos = vec![
            DiscoveredRepo {
                name: "frontend".to_string(),
                path: "./frontend".to_string(),
                absolute_path: PathBuf::from("/tmp/frontend"),
                url: Some("git@github.com:myorg/frontend.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "backend".to_string(),
                path: "./backend".to_string(),
                absolute_path: PathBuf::from("/tmp/backend"),
                url: Some("git@github.com:myorg/backend.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        let result = detect_common_platform(&repos);
        assert!(result.is_some());
        let detected = result.unwrap();
        assert_eq!(detected.platform, PlatformType::GitHub);
        assert_eq!(detected.owner, "myorg");
        assert_eq!(detected.confidence, 1.0);
    }

    #[test]
    fn test_detect_azure_platform() {
        let repos = vec![
            DiscoveredRepo {
                name: "app".to_string(),
                path: "./app".to_string(),
                absolute_path: PathBuf::from("/tmp/app"),
                url: Some("git@ssh.dev.azure.com:v3/myorg/myproject/app".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "lib".to_string(),
                path: "./lib".to_string(),
                absolute_path: PathBuf::from("/tmp/lib"),
                url: Some("https://dev.azure.com/myorg/myproject/_git/lib".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        let result = detect_common_platform(&repos);
        assert!(result.is_some());
        let detected = result.unwrap();
        assert_eq!(detected.platform, PlatformType::AzureDevOps);
        assert_eq!(detected.owner, "myorg/myproject");
    }

    #[test]
    fn test_detect_gitlab_platform() {
        let repos = vec![
            DiscoveredRepo {
                name: "frontend".to_string(),
                path: "./frontend".to_string(),
                absolute_path: PathBuf::from("/tmp/frontend"),
                url: Some("git@gitlab.com:mygroup/frontend.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "backend".to_string(),
                path: "./backend".to_string(),
                absolute_path: PathBuf::from("/tmp/backend"),
                url: Some("https://gitlab.com/mygroup/backend.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        let result = detect_common_platform(&repos);
        assert!(result.is_some());
        let detected = result.unwrap();
        assert_eq!(detected.platform, PlatformType::GitLab);
        assert_eq!(detected.owner, "mygroup");
    }

    #[test]
    fn test_detect_no_remotes() {
        let repos = vec![
            DiscoveredRepo {
                name: "local1".to_string(),
                path: "./local1".to_string(),
                absolute_path: PathBuf::from("/tmp/local1"),
                url: None,
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "local2".to_string(),
                path: "./local2".to_string(),
                absolute_path: PathBuf::from("/tmp/local2"),
                url: None,
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        let result = detect_common_platform(&repos);
        assert!(result.is_none());
    }

    #[test]
    fn test_detect_mixed_platforms() {
        let repos = vec![
            DiscoveredRepo {
                name: "gh1".to_string(),
                path: "./gh1".to_string(),
                absolute_path: PathBuf::from("/tmp/gh1"),
                url: Some("git@github.com:org1/gh1.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "gh2".to_string(),
                path: "./gh2".to_string(),
                absolute_path: PathBuf::from("/tmp/gh2"),
                url: Some("git@github.com:org1/gh2.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
            DiscoveredRepo {
                name: "gl1".to_string(),
                path: "./gl1".to_string(),
                absolute_path: PathBuf::from("/tmp/gl1"),
                url: Some("git@gitlab.com:org2/gl1.git".to_string()),
                default_branch: "main".to_string(),
                toolchain: None,
            },
        ];

        let result = detect_common_platform(&repos);
        assert!(result.is_some());
        let detected = result.unwrap();
        // GitHub should win (2 vs 1)
        assert_eq!(detected.platform, PlatformType::GitHub);
        assert_eq!(detected.owner, "org1");
        // Confidence should be 2/3
        assert!((detected.confidence - 0.666).abs() < 0.01);
    }

    #[test]
    fn test_suggest_manifest_url_github() {
        let url = suggest_manifest_url(PlatformType::GitHub, "myorg", "workspace-manifest");
        assert_eq!(url, "git@github.com:myorg/workspace-manifest.git");
    }

    #[test]
    fn test_suggest_manifest_url_gitlab() {
        let url = suggest_manifest_url(PlatformType::GitLab, "mygroup", "workspace-manifest");
        assert_eq!(url, "git@gitlab.com:mygroup/workspace-manifest.git");
    }

    #[test]
    fn test_suggest_manifest_url_azure() {
        let url = suggest_manifest_url(
            PlatformType::AzureDevOps,
            "myorg/myproject",
            "workspace-manifest",
        );
        assert_eq!(
            url,
            "git@ssh.dev.azure.com:v3/myorg/myproject/workspace-manifest.git"
        );
    }

    #[test]
    fn test_suggest_manifest_https_url_github() {
        let url = suggest_manifest_https_url(PlatformType::GitHub, "myorg", "workspace-manifest");
        assert_eq!(url, "https://github.com/myorg/workspace-manifest.git");
    }

    #[test]
    fn test_suggest_manifest_https_url_azure() {
        let url = suggest_manifest_https_url(
            PlatformType::AzureDevOps,
            "myorg/myproject",
            "workspace-manifest",
        );
        assert_eq!(
            url,
            "https://dev.azure.com/myorg/myproject/_git/workspace-manifest"
        );
    }

    // ── detect_default_branch tests ─────────────────────────────

    fn setup_git_repo(dir: &std::path::Path) -> Repository {
        let repo = Repository::init(dir).unwrap();
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        {
            let tree = repo.find_tree(tree_id).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        repo
    }

    #[test]
    fn test_detect_default_branch_with_origin_head() {
        let tmp = TempDir::new().unwrap();
        let origin_dir = tmp.path().join("origin");
        std::fs::create_dir_all(&origin_dir).unwrap();

        // Create a bare "remote" repo with main as default branch
        let origin = Repository::init_bare(&origin_dir).unwrap();
        origin.set_head("refs/heads/main").unwrap();
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = origin.treebuilder(None).unwrap().write().unwrap();
        {
            let tree = origin.find_tree(tree_id).unwrap();
            origin
                .commit(Some("refs/heads/main"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }

        // Clone it (sets origin/HEAD automatically)
        let clone_dir = tmp.path().join("clone");
        let repo = Repository::clone(origin_dir.to_str().unwrap(), &clone_dir).unwrap();

        // Create and checkout a feature branch
        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
        repo.branch("feat/something", &head_commit, false).unwrap();
        repo.set_head("refs/heads/feat/something").unwrap();

        // Should detect "main" from origin/HEAD, not "feat/something"
        let result = detect_default_branch(&repo).unwrap();
        assert_eq!(result, "main");
    }

    #[test]
    fn test_detect_default_branch_remote_tracking_main() {
        let tmp = TempDir::new().unwrap();

        // Create a local repo with a remote tracking branch but no origin/HEAD
        let repo = setup_git_repo(tmp.path());

        // Create origin/main as a remote tracking ref
        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
        repo.reference("refs/remotes/origin/main", head_commit.id(), true, "test")
            .unwrap();

        // Rename local branch to a feature branch
        let mut branch = repo
            .find_branch("master", git2::BranchType::Local)
            .or_else(|_| repo.find_branch("main", git2::BranchType::Local))
            .unwrap();
        branch.rename("feat/work", false).unwrap();

        let result = detect_default_branch(&repo).unwrap();
        assert_eq!(result, "main");
    }

    #[test]
    fn test_detect_default_branch_remote_tracking_master() {
        let tmp = TempDir::new().unwrap();
        let repo = setup_git_repo(tmp.path());

        // Create origin/master as remote tracking ref (no origin/main)
        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
        repo.reference("refs/remotes/origin/master", head_commit.id(), true, "test")
            .unwrap();

        // Rename local branch to feature branch
        let mut branch = repo
            .find_branch("master", git2::BranchType::Local)
            .or_else(|_| repo.find_branch("main", git2::BranchType::Local))
            .unwrap();
        branch.rename("feat/work", false).unwrap();

        let result = detect_default_branch(&repo).unwrap();
        assert_eq!(result, "master");
    }

    #[test]
    fn test_detect_default_branch_local_main_only() {
        let tmp = TempDir::new().unwrap();
        let repo = setup_git_repo(tmp.path());

        // Ensure there's a local "main" branch
        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
        // The initial branch could be "master" depending on git config
        if repo.find_branch("main", git2::BranchType::Local).is_err() {
            repo.branch("main", &head_commit, false).unwrap();
        }

        // Switch to a feature branch
        repo.branch("feat/test", &head_commit, false).unwrap();
        repo.set_head("refs/heads/feat/test").unwrap();

        let result = detect_default_branch(&repo).unwrap();
        // Should find local "main" or "master", not "feat/test"
        assert!(result == "main" || result == "master");
    }

    #[test]
    fn test_detect_default_branch_empty_repo() {
        let tmp = TempDir::new().unwrap();
        let _repo = Repository::init(tmp.path()).unwrap();

        // Empty repo with no commits — no branches exist
        let repo = Repository::open(tmp.path()).unwrap();
        let result = detect_default_branch(&repo).unwrap();
        assert_eq!(result, "main"); // Falls back to default
    }
}