skill-manager 0.9.0

Manage AI coding tool skills for Claude, OpenCode, Cursor, and Codex
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
mod bundle;
mod config;
mod discover;
mod install;
mod install_manifest;
mod manifest;
mod setup;
mod source;
mod target;

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
use colored::Colorize;
use std::io;
use std::path::PathBuf;

use crate::bundle::SkillType;
use crate::config::{Config, SourceConfig};
use crate::install::{install_bundle, install_bundle_from_source, install_from_source};
use crate::setup::run_setup_wizard;
use crate::target::Tool;

#[derive(Parser)]
#[command(name = "skm")]
#[command(about = "Manage AI coding tool skills for Claude, OpenCode, Cursor, and Codex")]
#[command(version)]
#[command(args_conflicts_with_subcommands = true)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Bundle name to install (when no subcommand given)
    #[arg(value_name = "BUNDLE")]
    bundle: Option<String>,

    /// Install to OpenCode instead of Claude
    #[arg(short = 'o', long = "opencode", global = true)]
    opencode: bool,

    /// Install to Cursor instead of Claude
    #[arg(short = 'c', long = "cursor", global = true)]
    cursor: bool,

    /// Install to Codex instead of Claude
    #[arg(short = 'x', long = "codex", global = true)]
    codex: bool,

    /// Install globally (tool-specific location)
    #[arg(short = 'g', long = "global", global = true)]
    global: bool,

    /// Target directory (default: current directory)
    #[arg(short = 't', long = "to", global = true)]
    target: Option<PathBuf>,

    /// Filter: only install skills
    #[arg(long = "skills")]
    skills_only: bool,

    /// Filter: only install agents
    #[arg(long = "agents")]
    agents_only: bool,

    /// Filter: only install commands
    #[arg(long = "commands")]
    commands_only: bool,

    /// Filter: only install rules
    #[arg(long = "rules")]
    rules_only: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Install a bundle (alias for `skm <bundle>`)
    Add {
        /// Bundle name to install
        bundle: String,
    },
    /// Browse available bundles interactively
    List,
    /// Manage skill sources (interactive if no subcommand)
    Sources {
        #[command(subcommand)]
        action: Option<SourcesAction>,
    },
    /// Show installed skills in current directory
    Here {
        /// Filter by tool (claude, opencode, cursor)
        #[arg(long)]
        tool: Option<String>,

        /// Interactively remove skills
        #[arg(long)]
        remove: bool,

        /// Remove all installed skills
        #[arg(long)]
        clean: bool,

        /// Skip confirmation prompts
        #[arg(short = 'y', long)]
        yes: bool,
    },
    /// Update git sources and refresh installed skills
    Update {
        /// Only update git sources, don't refresh skills
        #[arg(long)]
        sources_only: bool,
    },
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Convert between rule and command formats
    Convert {
        /// Source file to convert
        source: PathBuf,
        /// Convert to rule format (default: convert to command format)
        #[arg(long)]
        to_rule: bool,
        /// Output file (default: stdout)
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Remove an installed bundle
    Rm {
        /// Bundle name to remove
        bundle: String,

        /// Skip confirmation prompt
        #[arg(short = 'y', long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum SourcesAction {
    /// List configured sources
    List,
    /// Add a source (local path or git URL)
    Add {
        /// Path or URL to add
        path: String,
        /// Optional name for the source (e.g., "fg")
        #[arg(short = 'n', long = "name")]
        name: Option<String>,
    },
    /// Remove a source
    Remove {
        /// Path, URL, or name to remove
        path: String,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Check if this is first run (no config file) and we're not doing a specific subcommand
    let config = if !Config::exists()? && cli.command.is_none() && cli.bundle.is_none() {
        // First run - show setup wizard
        run_setup_wizard()?
    } else {
        // Load existing config or use defaults
        Config::load_or_default()?
    };

    // Determine target tool
    let tool = if cli.cursor {
        Tool::Cursor
    } else if cli.opencode {
        Tool::OpenCode
    } else if cli.codex {
        Tool::Codex
    } else {
        Tool::Claude
    };

    // Determine target directory
    let target_dir = if cli.global {
        tool.global_target()
    } else if let Some(t) = cli.target {
        t
    } else {
        std::env::current_dir()?
    };

    // Determine which types to install
    let types = if cli.skills_only || cli.agents_only || cli.commands_only || cli.rules_only {
        let mut t = vec![];
        if cli.skills_only {
            t.push(SkillType::Skill);
        }
        if cli.agents_only {
            t.push(SkillType::Agent);
        }
        if cli.commands_only {
            t.push(SkillType::Command);
        }
        if cli.rules_only {
            t.push(SkillType::Rule);
        }
        t
    } else {
        vec![
            SkillType::Skill,
            SkillType::Agent,
            SkillType::Command,
            SkillType::Rule,
        ]
    };

    match cli.command {
        Some(Commands::Add {
            bundle: bundle_name,
        }) => {
            // `skm add <bundle>` is an alias for `skm <bundle>`
            do_install(&config, &bundle_name, &tool, &target_dir, &types)?;
        }
        Some(Commands::List) => {
            browse_bundles(&config)?;
        }
        Some(Commands::Sources { action }) => match action {
            Some(SourcesAction::List) => {
                sources_list(&config)?;
            }
            Some(SourcesAction::Add { path, name }) => {
                sources_add(name, path)?;
            }
            Some(SourcesAction::Remove { path }) => {
                sources_remove(path)?;
            }
            None => {
                // Interactive sources management
                sources_interactive()?;
            }
        },
        Some(Commands::Here {
            tool: filter_tool,
            remove,
            clean,
            yes,
        }) => {
            if remove {
                interactive_remove(&target_dir, filter_tool.as_deref())?;
            } else if clean {
                clean_all_skills(&target_dir, filter_tool.as_deref(), yes)?;
            } else {
                show_installed_skills(&target_dir, filter_tool.as_deref())?;
            }
        }
        Some(Commands::Update { sources_only }) => {
            update_sources(&config)?;
            if !sources_only {
                refresh_installed_skills(&config, &tool, &target_dir, &types)?;
            }
        }
        Some(Commands::Completions { shell }) => {
            generate_completions(shell);
        }
        Some(Commands::Convert {
            source,
            to_rule,
            output,
        }) => {
            convert_format(&source, to_rule, output.as_ref())?;
        }
        Some(Commands::Rm { bundle, yes }) => {
            let filter_tool = if cli.cursor {
                Some("cursor")
            } else if cli.opencode {
                Some("opencode")
            } else {
                None
            };
            remove_bundle(&bundle, &target_dir, filter_tool, yes)?;
        }
        None => {
            // No subcommand - either list bundles or install a bundle
            if let Some(bundle_name) = cli.bundle {
                // Install the specified bundle
                do_install(&config, &bundle_name, &tool, &target_dir, &types)?;
            } else {
                // List available bundles
                list_bundles(&config)?;
            }
        }
    }

    Ok(())
}

fn browse_bundles(config: &Config) -> Result<()> {
    use crate::bundle::Bundle;
    use dialoguer::{theme::ColorfulTheme, FuzzySelect};

    let sources = config.sources();

    if sources.is_empty() {
        println!("{}", "No sources configured.".yellow());
        println!("Add a source with: skm sources add <path>");
        return Ok(());
    }

    // Collect all bundles with their source info
    let mut all_bundles: Vec<(String, Bundle)> = Vec::new();

    for source in &sources {
        match source.list_bundles() {
            Ok(bundles) => {
                for bundle in bundles {
                    all_bundles.push((source.display_path(), bundle));
                }
            }
            Err(e) => {
                eprintln!(
                    "  {} {} - {}",
                    "Warning:".yellow(),
                    source.display_path(),
                    e
                );
            }
        }
    }

    if all_bundles.is_empty() {
        println!("{}", "No bundles found in configured sources.".yellow());
        return Ok(());
    }

    loop {
        println!();
        println!("{}", "Available Bundles (type to search)".bold());
        println!();

        // Build display items with searchable content
        // Format: "name | description | author | counts | source"
        let items: Vec<String> = all_bundles
            .iter()
            .map(|(source, bundle)| {
                let desc = bundle
                    .meta
                    .description
                    .as_ref()
                    .map(|d| {
                        // Truncate long descriptions
                        if d.len() > 40 {
                            format!("{}...", &d[..37])
                        } else {
                            d.clone()
                        }
                    })
                    .unwrap_or_default();
                let author = bundle
                    .meta
                    .author
                    .as_ref()
                    .map(|a| format!("by {}", a))
                    .unwrap_or_default();
                let counts = format!(
                    "{}s {}a {}c",
                    bundle.skills.len(),
                    bundle.agents.len(),
                    bundle.commands.len()
                );
                // Include searchable content (name, author, description, skill names)
                let search_hint = bundle.search_string();
                if desc.is_empty() {
                    format!(
                        "{:<20} {:<15} {} {} [{}]",
                        bundle.name,
                        author.dimmed(),
                        counts.dimmed(),
                        format!("({})", source).dimmed(),
                        search_hint.dimmed()
                    )
                } else {
                    format!(
                        "{:<20} {} {:<15} {} {} [{}]",
                        bundle.name,
                        desc.dimmed(),
                        author.dimmed(),
                        counts.dimmed(),
                        format!("({})", source).dimmed(),
                        search_hint.dimmed()
                    )
                }
            })
            .collect();

        let sel = FuzzySelect::with_theme(&ColorfulTheme::default())
            .with_prompt("Select a bundle (type to filter, Esc to quit)")
            .items(&items)
            .default(0)
            .highlight_matches(true)
            .interact_opt()?;

        match sel {
            Some(idx) if idx < all_bundles.len() => {
                let (_, bundle) = &all_bundles[idx];
                show_bundle_details(bundle)?;
            }
            _ => break,
        }
    }

    Ok(())
}

fn show_bundle_details(bundle: &crate::bundle::Bundle) -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Select};

    loop {
        println!();
        println!("{} {}", "Bundle:".bold(), bundle.name.cyan());
        println!();

        let mut items: Vec<String> = Vec::new();
        let mut file_paths: Vec<Option<std::path::PathBuf>> = Vec::new();

        for (section, files) in [
            ("skills", &bundle.skills),
            ("agents", &bundle.agents),
            ("commands", &bundle.commands),
        ] {
            if !files.is_empty() {
                items.push(format!(
                    "── {}/{} ──",
                    section,
                    format!(" ({} files)", files.len()).dimmed()
                ));
                file_paths.push(None); // section header

                for file in files {
                    let preview = get_file_preview(&file.path);
                    items.push(format!("  {} {}", file.name, preview.dimmed()));
                    file_paths.push(Some(file.path.clone()));
                }
            }
        }

        items.push("← Back".to_string());
        file_paths.push(None);

        let sel = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("Select to view contents")
            .items(&items)
            .default(0)
            .interact()?;

        if sel >= items.len() - 1 {
            break;
        }

        let path = match &file_paths[sel] {
            Some(p) => p,
            None => continue, // section header
        };

        // Show file contents
        println!();
        println!("{}", "".repeat(60).dimmed());
        if let Ok(content) = std::fs::read_to_string(path) {
            for line in content.lines().take(40) {
                println!("{}", line);
            }
            let line_count = content.lines().count();
            if line_count > 40 {
                println!(
                    "{}",
                    format!("... ({} more lines)", line_count - 40).dimmed()
                );
            }
        }
        println!("{}", "".repeat(60).dimmed());
        println!();
    }

    Ok(())
}

fn get_file_preview(path: &std::path::PathBuf) -> String {
    if let Ok(content) = std::fs::read_to_string(path) {
        content
            .lines()
            .filter(|line| !line.trim().is_empty())
            .filter(|line| !line.starts_with("---"))
            .filter(|line| !line.contains(':') || line.starts_with('#'))
            .take(1)
            .map(|line| {
                let trimmed = line.trim_start_matches('#').trim();
                if trimmed.len() > 50 {
                    format!("- {}...", &trimmed[..47])
                } else {
                    format!("- {}", trimmed)
                }
            })
            .next()
            .unwrap_or_default()
    } else {
        String::new()
    }
}

fn sources_interactive() -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Input, Select};

    loop {
        let config = Config::load_or_default()?;
        let sources = config.source_configs();

        println!();
        println!("{}", "Skill Sources".bold());
        println!();

        if sources.is_empty() {
            println!("  {}", "(no sources configured)".dimmed());
        } else {
            for (i, source) in sources.iter().enumerate() {
                let type_label = match source {
                    SourceConfig::Local { .. } => "local",
                    SourceConfig::Git { .. } => "git",
                };
                let priority = format!("[{}]", i + 1).dimmed();
                let name_display = source
                    .name()
                    .map(|n| format!(" ({})", n.yellow()))
                    .unwrap_or_default();
                println!(
                    "  {} {}{} {}",
                    priority,
                    source.display().cyan(),
                    name_display,
                    format!("({})", type_label).dimmed()
                );
            }
        }
        println!();

        let mut options = vec!["Add source", "Remove source"];
        if sources.len() > 1 {
            options.push("Change priority");
        }
        options.push("Done");

        let selection = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(options.len() - 1)
            .interact()?;

        match options[selection] {
            "Add source" => {
                let path: String = Input::with_theme(&ColorfulTheme::default())
                    .with_prompt("Enter path or git URL")
                    .interact_text()?;
                sources_add(None, path)?;
            }
            "Remove source" => {
                if sources.is_empty() {
                    println!("{}", "No sources to remove.".yellow());
                    continue;
                }
                let source_names: Vec<&str> = sources.iter().map(|s| s.display()).collect();
                let sel = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Select source to remove")
                    .items(&source_names)
                    .interact()?;
                sources_remove(source_names[sel].to_string())?;
            }
            "Change priority" => {
                if sources.len() < 2 {
                    continue;
                }
                let source_names: Vec<String> = sources
                    .iter()
                    .enumerate()
                    .map(|(i, s)| format!("[{}] {}", i + 1, s.display()))
                    .collect();
                let sel = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Select source to move")
                    .items(&source_names)
                    .interact()?;

                let positions: Vec<String> = (1..=sources.len())
                    .map(|i| format!("Position {}", i))
                    .collect();
                let new_pos = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Move to position")
                    .items(&positions)
                    .default(sel)
                    .interact()?;

                if sel != new_pos {
                    let mut config = Config::load_or_default()?;
                    config.move_source(sel, new_pos)?;
                    config.save()?;
                    println!("{}", "Priority updated.".green());
                }
            }
            "Done" => break,
            _ => break,
        }
    }

    // Auto-update git sources on exit
    let config = Config::load_or_default()?;
    let git_sources = config.git_sources();
    if !git_sources.is_empty() {
        println!();
        println!("{}", "Updating git sources...".dimmed());
        for source in git_sources {
            match source.pull() {
                Ok(true) => {
                    println!("  {} {}", "Updated:".green(), source.url());
                }
                Ok(false) => {} // Already up to date, stay quiet
                Err(e) => {
                    println!("  {} {}: {}", "Error:".red(), source.url(), e);
                }
            }
        }
    }

    Ok(())
}

fn sources_list(config: &Config) -> Result<()> {
    println!("{}", "Configured sources:".bold());
    println!();

    let sources = config.source_configs();
    if sources.is_empty() {
        println!("  {}", "(none)".dimmed());
        println!();
        println!("Add a source with: skm sources add <path>");
    } else {
        for (i, source) in sources.iter().enumerate() {
            let type_label = match source {
                SourceConfig::Local { .. } => "local",
                SourceConfig::Git { .. } => "git",
            };
            let name_display = source
                .name()
                .map(|n| format!("[{}] ", n.cyan()))
                .unwrap_or_default();
            println!(
                "  {}. {}{} {}",
                i + 1,
                name_display,
                source.display(),
                format!("({})", type_label).dimmed()
            );
        }
    }
    println!();

    Ok(())
}

fn sources_add(name: Option<String>, path: String) -> Result<()> {
    let mut config = Config::load_or_default()?;

    // Determine if this is a git URL or local path
    let source =
        if path.starts_with("https://") || path.starts_with("git@") || path.ends_with(".git") {
            SourceConfig::Git {
                url: path.clone(),
                name,
            }
        } else {
            // Normalize local path
            let normalized = if path.starts_with("~/") || path.starts_with('/') {
                path.clone()
            } else {
                // Make relative path absolute
                let cwd = std::env::current_dir()?;
                cwd.join(&path).to_string_lossy().to_string()
            };
            SourceConfig::Local {
                path: normalized,
                name,
            }
        };

    // Check if path exists for local sources
    if let SourceConfig::Local { ref path, .. } = source {
        let expanded = if path.starts_with("~/") {
            let home = std::env::var("HOME")?;
            PathBuf::from(format!("{}/{}", home, &path[2..]))
        } else {
            PathBuf::from(path)
        };

        if !expanded.exists() {
            println!("{} Path does not exist: {}", "Warning:".yellow(), path);
        }
    }

    config.add_source(source);
    config.save()?;

    println!("{} {}", "Added source:".green(), path);

    Ok(())
}

fn sources_remove(path: String) -> Result<()> {
    let mut config = Config::load_or_default()?;

    if config.remove_source(&path) {
        config.save()?;
        println!("{} {}", "Removed source:".green(), path);
    } else {
        println!("{} Source not found: {}", "Error:".red(), path);
    }

    Ok(())
}

fn update_sources(config: &Config) -> Result<()> {
    let git_sources = config.git_sources();

    if git_sources.is_empty() {
        println!("{}", "No git sources configured.".yellow());
        println!("Add a git source with: skm sources add <git-url>");
        return Ok(());
    }

    println!("{}", "Updating git sources...".bold());
    println!();

    let mut updated = 0;
    let mut already_current = 0;
    let mut errors = 0;

    for source in git_sources {
        print!("  {} {}... ", "Updating".cyan(), source.url());

        match source.pull() {
            Ok(true) => {
                println!("{}", "updated".green());
                updated += 1;
            }
            Ok(false) => {
                println!("{}", "already up to date".dimmed());
                already_current += 1;
            }
            Err(e) => {
                println!("{}: {}", "error".red(), e);
                errors += 1;
            }
        }
    }

    println!();
    if updated > 0 {
        println!("  {} {} source(s) updated", "".green(), updated);
    }
    if already_current > 0 {
        println!(
            "  {} {} source(s) already up to date",
            "".dimmed(),
            already_current
        );
    }
    if errors > 0 {
        println!("  {} {} source(s) failed", "".red(), errors);
    }

    Ok(())
}

fn refresh_installed_skills(
    config: &Config,
    tool: &Tool,
    target_dir: &PathBuf,
    types: &[SkillType],
) -> Result<()> {
    use crate::discover::{discover_installed, filter_by_tool};
    use std::collections::HashSet;

    // Try manifest first as primary source of bundle names
    let mut manifest = install_manifest::InstallManifest::load(tool, target_dir);
    let use_manifest = !manifest.is_empty();

    // Build the set of bundle names to refresh
    let bundles_to_refresh: HashSet<String> = if use_manifest {
        manifest.bundle_names().into_iter().map(|s| s.to_string()).collect()
    } else {
        // Legacy fallback: discover from filesystem
        let tool_name = match tool {
            Tool::Claude => "claude",
            Tool::OpenCode => "opencode",
            Tool::Cursor => "cursor",
            Tool::Codex => "codex",
        };
        let skills = filter_by_tool(discover_installed(target_dir)?, tool_name);

        if skills.is_empty() {
            println!();
            println!("{}", "No installed skills to refresh.".yellow());
            return Ok(());
        }

        let mut names: HashSet<String> = HashSet::new();
        for skill in &skills {
            if let Some(ref bundle) = skill.bundle {
                names.insert(bundle.clone());
            } else {
                names.insert(skill.name.clone());
            }
        }
        names
    };

    if bundles_to_refresh.is_empty() {
        println!();
        println!("{}", "No bundles to refresh.".yellow());
        return Ok(());
    }

    println!();
    println!("{}", "Refreshing installed skills...".bold());
    println!();

    let mut refreshed = 0;
    let mut not_found = 0;
    let mut errors = 0;
    // Track which actual bundle names have been refreshed to avoid duplicates
    // (e.g., "cl" from commands and "cl-setup" from skills should both resolve to "cl")
    let mut already_refreshed: HashSet<String> = HashSet::new();

    for bundle_name in &bundles_to_refresh {
        print!("  {} {}... ", "Refreshing".cyan(), bundle_name);

        // Try to find this bundle in sources (exact match first, then prefix match)
        let found = match config.find_bundle(bundle_name) {
            Ok(Some((source, bundle))) => Some((source.display_path(), bundle)),
            Ok(None) => {
                // Legacy fallback: skills/rules use {bundle}-{name} folder format,
                // so the discovered "bundle name" may actually be a combined name.
                match config.find_bundle_by_prefix(bundle_name) {
                    Ok(Some(bundle)) => {
                        // We don't have the source display path from prefix match,
                        // but we can look it up
                        let source_display = config
                            .find_bundle(&bundle.name)
                            .ok()
                            .flatten()
                            .map(|(s, _)| s.display_path())
                            .unwrap_or_default();
                        Some((source_display, bundle))
                    }
                    Ok(None) => None,
                    Err(_) => None,
                }
            }
            Err(e) => {
                println!("{}: {}", "error".red(), e);
                errors += 1;
                continue;
            }
        };

        match found {
            Some((source_display, bundle)) => {
                // Skip if we already refreshed this actual bundle
                if already_refreshed.contains(&bundle.name) {
                    println!("{} (via {})", "already refreshed".dimmed(), bundle.name);
                    continue;
                }
                already_refreshed.insert(bundle.name.clone());

                // Re-install this bundle
                let mut count = 0;
                for skill_type in types {
                    let files = bundle.files_of_type(*skill_type);
                    for file in files {
                        match tool.write_file(target_dir, &bundle.name, file) {
                            Ok(_) => count += 1,
                            Err(e) => {
                                println!("{}: {}", "error".red(), e);
                                errors += 1;
                            }
                        }
                    }
                }
                if count > 0 {
                    println!("{} ({} files)", "done".green(), count);
                    refreshed += 1;
                    // Record in manifest (migrates legacy installs)
                    manifest.record_install(&bundle.name, &source_display);
                } else {
                    println!("{}", "no files".dimmed());
                }
            }
            None => {
                println!("{}", "not found in sources".yellow());
                not_found += 1;
            }
        }
    }

    // Save manifest (persists migration or updates)
    if let Err(e) = manifest.save(tool, target_dir) {
        eprintln!("Warning: could not save install manifest: {}", e);
    }

    println!();
    if refreshed > 0 {
        println!("  {} {} bundle(s) refreshed", "".green(), refreshed);
    }
    if not_found > 0 {
        println!(
            "  {} {} bundle(s) not found in sources",
            "".yellow(),
            not_found
        );
    }
    if errors > 0 {
        println!("  {} {} error(s)", "".red(), errors);
    }

    Ok(())
}

fn list_bundles(config: &Config) -> Result<()> {
    let sources = config.sources();

    if sources.is_empty() {
        println!("{}", "No sources configured.".yellow());
        println!("Add a source with: skm sources add <path>");
        return Ok(());
    }

    println!("{}", "Available bundles:".bold());
    println!();

    let mut found_any = false;
    let mut had_errors = false;

    for source in sources {
        // Handle source errors gracefully - warn and continue
        let bundles = match source.list_bundles() {
            Ok(b) => b,
            Err(e) => {
                eprintln!(
                    "  {} {} - {}",
                    "Warning:".yellow(),
                    source.display_path(),
                    e
                );
                had_errors = true;
                continue;
            }
        };

        if bundles.is_empty() {
            continue;
        }

        found_any = true;
        println!("  {} {}", "Source:".dimmed(), source.display_path());

        for bundle in bundles {
            // Show description on same line if available
            if let Some(desc) = &bundle.meta.description {
                println!("    {}/ - {}", bundle.name.cyan(), desc.dimmed());
            } else {
                println!("    {}/", bundle.name.cyan());
            }

            let skill_count = bundle.skills.len();
            let agent_count = bundle.agents.len();
            let command_count = bundle.commands.len();
            let rule_count = bundle.rules.len();

            if skill_count > 0 {
                println!("      {:<10} {} files", "skills/", skill_count);
            }
            if agent_count > 0 {
                println!("      {:<10} {} files", "agents/", agent_count);
            }
            if command_count > 0 {
                println!("      {:<10} {} files", "commands/", command_count);
            }
            if rule_count > 0 {
                println!("      {:<10} {} files", "rules/", rule_count);
            }
        }
        println!();
    }

    if !found_any {
        if had_errors {
            println!("  {}", "(no accessible bundles found)".dimmed());
        } else {
            println!("  {}", "(no bundles found in configured sources)".dimmed());
        }
        println!();
    }

    Ok(())
}

fn show_installed_skills(base: &PathBuf, filter_tool: Option<&str>) -> Result<()> {
    use crate::discover::{
        discover_installed, filter_by_tool, group_by_tool, InstalledTool, SkillType,
    };

    let mut skills = discover_installed(base)?;

    // Apply filter if provided
    if let Some(tool_filter) = filter_tool {
        skills = filter_by_tool(skills, tool_filter);
    }

    if skills.is_empty() {
        if filter_tool.is_some() {
            println!(
                "{}",
                "No installed skills found for the specified tool.".yellow()
            );
        } else {
            println!("{}", "No installed skills found.".yellow());
        }
        println!();
        println!("Install skills with: skm <bundle>");
        return Ok(());
    }

    println!("{}", "Installed skills:".bold());
    println!();

    let grouped = group_by_tool(&skills);

    // Define tool order
    let tool_order = [
        InstalledTool::Claude,
        InstalledTool::OpenCode,
        InstalledTool::Cursor,
        InstalledTool::Codex,
    ];

    for tool in &tool_order {
        if let Some(type_map) = grouped.get(tool) {
            println!("  {}", tool.display_name().cyan().bold());

            // Define type order
            let type_order = [SkillType::Skill, SkillType::Agent, SkillType::Command];

            for skill_type in &type_order {
                if let Some(skill_list) = type_map.get(skill_type) {
                    if !skill_list.is_empty() {
                        println!("    {}/", skill_type.plural().dimmed());

                        for skill in skill_list {
                            let display_name = if let Some(ref bundle) = skill.bundle {
                                format!("{}/{}", bundle, skill.name)
                            } else {
                                skill.name.clone()
                            };
                            println!("      {}", display_name);
                        }
                    }
                }
            }
            println!();
        }
    }

    // Show summary
    let total = skills.len();
    let by_tool: std::collections::HashMap<_, usize> =
        skills
            .iter()
            .fold(std::collections::HashMap::new(), |mut acc, s| {
                *acc.entry(s.tool).or_insert(0) += 1;
                acc
            });

    let summary_parts: Vec<String> = tool_order
        .iter()
        .filter_map(|t| {
            by_tool
                .get(t)
                .map(|count| format!("{} {}", count, t.display_name()))
        })
        .collect();

    println!(
        "  {} {} total ({})",
        "".dimmed(),
        total,
        summary_parts.join(", ")
    );
    println!();

    Ok(())
}

fn generate_completions(shell: Shell) {
    let mut cmd = Cli::command();
    generate(shell, &mut cmd, "skm", &mut io::stdout());
}

fn interactive_remove(base: &PathBuf, filter_tool: Option<&str>) -> Result<()> {
    use crate::discover::{discover_installed, filter_by_tool, group_same_skills, remove_skill};
    use dialoguer::{theme::ColorfulTheme, Confirm, MultiSelect};

    let mut skills = discover_installed(base)?;

    if let Some(tool_filter) = filter_tool {
        skills = filter_by_tool(skills, tool_filter);
    }

    if skills.is_empty() {
        println!("{}", "No installed skills found.".yellow());
        return Ok(());
    }

    // Group skills by unique ID (same skill across multiple tools)
    let grouped = group_same_skills(&skills);
    let mut skill_ids: Vec<_> = grouped.keys().cloned().collect();
    skill_ids.sort();

    // Build display items for multi-select
    let display_items: Vec<String> = skill_ids
        .iter()
        .map(|id| {
            let instances = grouped.get(id).unwrap();
            let tools: Vec<&str> = instances.iter().map(|s| s.tool.display_name()).collect();
            format!("{} ({})", id, tools.join(", "))
        })
        .collect();

    // Show multi-select
    println!("{}", "Select skills to remove:".bold());
    println!("{}", "(space to toggle, enter to confirm)".dimmed());
    println!();

    let selections = MultiSelect::with_theme(&ColorfulTheme::default())
        .items(&display_items)
        .interact()?;

    if selections.is_empty() {
        println!("{}", "No skills selected.".yellow());
        return Ok(());
    }

    // Collect skills to remove
    let mut to_remove: Vec<&crate::discover::InstalledSkill> = Vec::new();
    for idx in &selections {
        let id = &skill_ids[*idx];
        if let Some(instances) = grouped.get(id) {
            to_remove.extend(instances.iter().copied());
        }
    }

    // Build summary
    let summary: Vec<String> = selections
        .iter()
        .map(|idx| {
            let id = &skill_ids[*idx];
            let instances = grouped.get(id).unwrap();
            let tools: Vec<&str> = instances.iter().map(|s| s.tool.display_name()).collect();
            format!("  {} from {}", id.cyan(), tools.join(", "))
        })
        .collect();

    println!();
    println!("{}", "Will remove:".bold());
    for line in &summary {
        println!("{}", line);
    }
    println!();

    // Confirm
    let confirm = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt(format!("Remove {} skill(s)?", to_remove.len()))
        .default(false)
        .interact()?;

    if !confirm {
        println!("{}", "Cancelled.".yellow());
        return Ok(());
    }

    // Remove the skills
    let mut removed = 0;
    let mut errors = 0;

    for skill in to_remove {
        match remove_skill(skill) {
            Ok(()) => {
                removed += 1;
            }
            Err(e) => {
                eprintln!(
                    "{}: Failed to remove {}: {}",
                    "Error".red(),
                    skill.path.display(),
                    e
                );
                errors += 1;
            }
        }
    }

    println!();
    if removed > 0 {
        println!("{} Removed {} skill(s)", "".green(), removed);
    }
    if errors > 0 {
        println!("{} Failed to remove {} skill(s)", "".red(), errors);
    }

    Ok(())
}

fn clean_all_skills(base: &PathBuf, filter_tool: Option<&str>, skip_confirm: bool) -> Result<()> {
    use crate::discover::{discover_installed, filter_by_tool, remove_skill};
    use dialoguer::{theme::ColorfulTheme, Confirm};

    let mut skills = discover_installed(base)?;

    if let Some(tool_filter) = filter_tool {
        skills = filter_by_tool(skills, tool_filter);
    }

    if skills.is_empty() {
        println!("{}", "No installed skills found.".yellow());
        return Ok(());
    }

    let count = skills.len();
    let tool_desc = filter_tool
        .map(|t| format!(" for {}", t))
        .unwrap_or_default();

    println!("{} {} skill(s){}", "Found".bold(), count, tool_desc);
    println!();

    // Confirm unless --yes flag
    let confirmed = if skip_confirm {
        true
    } else {
        Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(format!("Remove all {} skill(s)?", count))
            .default(false)
            .interact()?
    };

    if !confirmed {
        println!("{}", "Cancelled.".yellow());
        return Ok(());
    }

    // Remove all skills
    let mut removed = 0;
    let mut errors = 0;

    for skill in &skills {
        match remove_skill(skill) {
            Ok(()) => {
                removed += 1;
            }
            Err(e) => {
                eprintln!(
                    "{}: Failed to remove {}: {}",
                    "Error".red(),
                    skill.path.display(),
                    e
                );
                errors += 1;
            }
        }
    }

    println!();
    if removed > 0 {
        println!("{} Removed {} skill(s)", "".green(), removed);

        // Delete manifest files
        for tool_enum in [Tool::Claude, Tool::OpenCode, Tool::Cursor, Tool::Codex] {
            let path = install_manifest::InstallManifest::path_for(&tool_enum, base);
            let _ = std::fs::remove_file(&path);
        }
    }
    if errors > 0 {
        println!("{} Failed to remove {} skill(s)", "".red(), errors);
    }

    Ok(())
}

fn skill_matches_bundle(skill: &crate::discover::InstalledSkill, bundle_name: &str) -> bool {
    // Claude: bundle field is the actual bundle name
    if skill.bundle.as_deref() == Some(bundle_name) {
        return true;
    }
    // OpenCode/Cursor: combined name is "{bundle}-{name}"
    if skill.name.starts_with(&format!("{}-", bundle_name)) {
        return true;
    }
    // Exact name match (single-skill bundles where name == bundle)
    if skill.name == bundle_name {
        return true;
    }
    false
}

fn remove_bundle(
    bundle_name: &str,
    base: &PathBuf,
    filter_tool: Option<&str>,
    skip_confirm: bool,
) -> Result<()> {
    use crate::discover::{
        discover_installed, filter_by_tool, group_by_tool, remove_skill, InstalledTool, SkillType,
    };
    use dialoguer::{theme::ColorfulTheme, Confirm};

    let mut skills = discover_installed(base)?;

    if let Some(tool_filter) = filter_tool {
        skills = filter_by_tool(skills, tool_filter);
    }

    // Filter to skills belonging to this bundle
    skills.retain(|s| skill_matches_bundle(s, bundle_name));

    if skills.is_empty() {
        println!(
            "No installed skills found for bundle '{}'.",
            bundle_name.cyan()
        );
        return Ok(());
    }

    // Print what will be removed, grouped by tool
    println!("{}", "Will remove:".bold());
    println!();

    let grouped = group_by_tool(&skills);
    let tool_order = [
        InstalledTool::Claude,
        InstalledTool::OpenCode,
        InstalledTool::Cursor,
        InstalledTool::Codex,
    ];
    let type_order = [SkillType::Skill, SkillType::Agent, SkillType::Command, SkillType::Rule];

    for tool in &tool_order {
        if let Some(type_map) = grouped.get(tool) {
            println!("  {}", tool.display_name().cyan().bold());
            for skill_type in &type_order {
                if let Some(skill_list) = type_map.get(skill_type) {
                    for skill in skill_list {
                        println!(
                            "    {}/{} {}",
                            skill_type.plural().dimmed(),
                            skill.name,
                            format!("({})", skill.path.display()).dimmed()
                        );
                    }
                }
            }
        }
    }
    println!();

    // Confirm unless --yes
    let confirmed = if skip_confirm {
        true
    } else {
        Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(format!(
                "Remove {} file(s) from bundle '{}'?",
                skills.len(),
                bundle_name
            ))
            .default(false)
            .interact()?
    };

    if !confirmed {
        println!("{}", "Cancelled.".yellow());
        return Ok(());
    }

    // Remove the skills
    let mut removed = 0;
    let mut errors = 0;

    for skill in &skills {
        match remove_skill(skill) {
            Ok(()) => {
                removed += 1;
            }
            Err(e) => {
                eprintln!(
                    "{}: Failed to remove {}: {}",
                    "Error".red(),
                    skill.path.display(),
                    e
                );
                errors += 1;
            }
        }
    }

    if removed > 0 {
        println!("{} Removed {} file(s)", "".green(), removed);

        // Remove from manifest for all tools
        for tool_enum in [Tool::Claude, Tool::OpenCode, Tool::Cursor, Tool::Codex] {
            let mut manifest = install_manifest::InstallManifest::load(&tool_enum, base);
            if manifest.remove_bundle(bundle_name) {
                if let Err(e) = manifest.save(&tool_enum, base) {
                    eprintln!("Warning: could not save install manifest: {}", e);
                }
            }
        }
    }
    if errors > 0 {
        println!("{} Failed to remove {} file(s)", "".red(), errors);
    }

    Ok(())
}

fn convert_format(source: &PathBuf, to_rule: bool, output: Option<&PathBuf>) -> Result<()> {
    use std::fs;
    use std::io::Write;

    if !source.exists() {
        println!(
            "{} Source file does not exist: {}",
            "Error:".red(),
            source.display()
        );
        return Ok(());
    }

    let content = fs::read_to_string(source)?;
    let converted = if to_rule {
        convert_to_rule(&content, source)
    } else {
        convert_to_command(&content)
    };

    match output {
        Some(output_path) => {
            let mut file = fs::File::create(output_path)?;
            file.write_all(converted.as_bytes())?;
            println!(
                "{} Converted to {}",
                "Success:".green(),
                output_path.display()
            );
        }
        None => {
            println!("{}", converted);
        }
    }

    Ok(())
}

fn convert_to_rule(content: &str, source_path: &PathBuf) -> String {
    let lines: Vec<&str> = content.lines().collect();

    // Check if already has frontmatter
    if lines.first() == Some(&"---") {
        // Already has frontmatter, assume it is already in rule format
        return content.to_string();
    }

    // Extract title from filename or first heading
    let name = source_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("converted-rule");

    let title = if let Some(first_line) = lines.first() {
        if first_line.starts_with("#") {
            first_line.trim_start_matches("#").trim().to_string()
        } else {
            name.to_string()
        }
    } else {
        name.to_string()
    };

    // Create rule frontmatter
    let mut result = String::new();
    result.push_str("---\n");
    result.push_str(&format!("description: \"{}\"\n", title));
    result.push_str("alwaysApply: false\n");
    result.push_str("---\n");
    result.push('\n');
    result.push_str(content);

    result
}

fn convert_to_command(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();

    // Check if it has frontmatter
    if lines.first() == Some(&"---") {
        // Find the end of frontmatter
        let mut in_frontmatter = false;
        let mut end_idx = 0;

        for (i, line) in lines.iter().enumerate() {
            if *line == "---" {
                if in_frontmatter {
                    end_idx = i + 1;
                    break;
                }
                in_frontmatter = true;
            }
        }

        // Skip frontmatter and return the rest
        if end_idx > 0 && end_idx < lines.len() {
            lines[end_idx..].join("\n").trim_start().to_string()
        } else {
            content.to_string()
        }
    } else {
        // No frontmatter, return as-is
        content.to_string()
    }
}

/// Parse a bundle reference that may be source-scoped.
/// "fg/synapse-docs" → (Some("fg"), Some("synapse-docs"))
/// "fg" → (None, Some("fg")) - could be source name OR bundle name
fn parse_bundle_ref(input: &str) -> (Option<&str>, Option<&str>) {
    if let Some((source, bundle)) = input.split_once('/') {
        (Some(source), Some(bundle))
    } else {
        (None, Some(input))
    }
}

/// Dispatch install command with support for source-scoped references
fn do_install(
    config: &Config,
    bundle_ref: &str,
    tool: &Tool,
    target_dir: &PathBuf,
    types: &[SkillType],
) -> Result<()> {
    let (source_name, bundle_name) = parse_bundle_ref(bundle_ref);

    let records = match (source_name, bundle_name) {
        (Some(source_name), Some(bundle_name)) => {
            // Explicit source/bundle: "fg/synapse-docs"
            match config.find_source_by_name(source_name) {
                Some((source, _)) => {
                    install_bundle_from_source(source.as_ref(), bundle_name, tool, target_dir, types)?
                }
                None => {
                    anyhow::bail!("Source '{}' not found. Add it with: skm sources add {} <path>", source_name, source_name);
                }
            }
        }
        (None, Some(name)) => {
            // Just a name - could be a source name or bundle name
            // First check if it's a named source
            if let Some((source, _)) = config.find_source_by_name(name) {
                // Install all bundles from this source
                install_from_source(source.as_ref(), tool, target_dir, types)?
            } else {
                // Otherwise, search all sources for a bundle with this name
                install_bundle(config, name, tool, target_dir, types)?
            }
        }
        (None, None) => {
            anyhow::bail!("No bundle specified");
        }
        (Some(_), None) => {
            anyhow::bail!("Invalid bundle reference");
        }
    };

    // Record installed bundles in manifest
    if !records.is_empty() {
        let mut manifest = install_manifest::InstallManifest::load(tool, target_dir);
        for rec in &records {
            manifest.record_install(&rec.bundle_name, &rec.source_display);
        }
        if let Err(e) = manifest.save(tool, target_dir) {
            eprintln!("Warning: could not save install manifest: {}", e);
        }
    }

    Ok(())
}

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

    #[test]
    fn test_convert_to_rule_no_frontmatter() {
        let content = "# Test Rule\n\nSome content here";
        let path = PathBuf::from("test-rule.md");
        let result = convert_to_rule(content, &path);

        assert!(result.starts_with("---\n"));
        assert!(result.contains("description: \"Test Rule\""));
        assert!(result.contains("alwaysApply: false"));
        assert!(result.contains("# Test Rule"));
    }

    #[test]
    fn test_convert_to_rule_with_existing_frontmatter() {
        let content = "---\ndescription: existing\n---\n# Content";
        let path = PathBuf::from("test.md");
        let result = convert_to_rule(content, &path);

        // Should return unchanged since it already has frontmatter
        assert_eq!(result, content);
    }

    #[test]
    fn test_convert_to_rule_uses_filename_when_no_heading() {
        let content = "Some content without a heading";
        let path = PathBuf::from("my-custom-rule.md");
        let result = convert_to_rule(content, &path);

        assert!(result.contains("description: \"my-custom-rule\""));
    }

    #[test]
    fn test_convert_to_command_strips_frontmatter() {
        let content =
            "---\ndescription: test\nalwaysApply: false\n---\n# Rule Content\n\nBody here";
        let result = convert_to_command(content);

        assert!(!result.contains("---"));
        assert!(!result.contains("description:"));
        assert!(result.starts_with("# Rule Content"));
        assert!(result.contains("Body here"));
    }

    #[test]
    fn test_convert_to_command_no_frontmatter() {
        let content = "# Simple Content\n\nNo frontmatter here";
        let result = convert_to_command(content);

        // Should return unchanged
        assert_eq!(result, content);
    }

    #[test]
    fn test_convert_to_command_only_frontmatter() {
        let content = "---\ndescription: test\n---";
        let result = convert_to_command(content);

        // Edge case: only frontmatter, no content after
        assert_eq!(result, content);
    }
}