gitflow-cli 0.8.0

Cross-platform Git engineering workflow orchestration tool
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
//! `gitflow skills` 子命令实现。
//!
//! 管理 gitflow Skills 的安装、列出和卸载。
//! Skills 可以从仓库的 `skills/` 目录复制,也可以从编译时嵌入的
//! 数据中提取(release 场景,binary 发布包不带 skills/ 目录)。
//!
//! 支持多 Agent 平台(Claude Code / Gemini CLI / Codex / Copilot CLI),
//! 支持用户级 / 项目级 / 自定义路径安装。
//!
//! Note: the install/uninstall helpers use `std::fs` for synchronous
//! file operations. This module is invoked before the `tokio` runtime is
//! constructed (see `main()`), so `tokio::fs` is not available here.
//! This is intentional — these operations are short-lived I/O that do
//! not benefit from async.

#![allow(
    clippy::disallowed_methods,
    clippy::disallowed_types,
    reason = "Skills command runs synchronously before the tokio runtime is constructed"
)]

use std::path::PathBuf;

// 编译时由 build.rs 生成的 skills 清单(release binary 内嵌)
include!(concat!(env!("OUT_DIR"), "/skills_manifest.rs"));

use clap::{ArgAction, Args, Subcommand, ValueEnum};
use gitflow_cli_core::AuthChecker;
use is_terminal::IsTerminal;

// ---------------------------------------------------------------------------
// Agent platform
// ---------------------------------------------------------------------------

/// 支持的 AI Agent 平台。
///
/// 每种平台有不同的 Skills 安装目录约定(依据 Superpowers 和各平台官方文档)。
/// 路径统一使用 `~/<.agent>/skills/` 形式,不与 `~/.agents/skills/` 混用。
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AgentPlatform {
    /// Claude Code / Superpowers — `~/.claude/skills/`
    Claude,
    /// Codex (`OpenAI`) — `~/.codex/skills/`
    Codex,
    /// `OpenCode` — `~/.opencode/skills/`
    OpenCode,
    /// Gemini CLI — `~/.gemini/skills/`
    Gemini,
    /// GitHub Copilot CLI — `~/.copilot/skills/`
    Copilot,
}

impl AgentPlatform {
    /// 返回该 Agent 的用户级 skills 子目录名(相对于 home)。
    #[must_use]
    pub fn skills_dir_name(self) -> &'static str {
        match self {
            AgentPlatform::Claude => ".claude/skills",
            AgentPlatform::Codex => ".codex/skills",
            AgentPlatform::OpenCode => ".opencode/skills",
            AgentPlatform::Gemini => ".gemini/skills",
            AgentPlatform::Copilot => ".copilot/skills",
        }
    }

    /// 返回该 Agent 的 hook 子目录名(相对于项目根或 home)。
    #[must_use]
    pub fn hooks_dir_name(self) -> &'static str {
        match self {
            AgentPlatform::Claude => ".claude/hooks",
            AgentPlatform::Codex => ".codex/hooks",
            AgentPlatform::OpenCode => ".opencode/hooks",
            AgentPlatform::Gemini => ".gemini/hooks",
            AgentPlatform::Copilot => ".copilot/hooks",
        }
    }

    /// 返回该 Agent 的 settings.json 路径(相对于项目根或 home)。
    #[must_use]
    pub fn settings_file_path(self) -> &'static str {
        match self {
            AgentPlatform::Claude => ".claude/settings.json",
            AgentPlatform::Codex => ".codex/settings.json",
            AgentPlatform::OpenCode => ".opencode/settings.json",
            AgentPlatform::Gemini => ".gemini/settings.json",
            AgentPlatform::Copilot => ".copilot/settings.json",
        }
    }

    /// 该 Agent 是否支持 Stop hook 配置(写入 `settings.json` 的 `hooks.Stop`)。
    ///
    /// 当前仅 Claude Code 与 Codex 识别此 schema;
    /// `OpenCode` / Gemini / Copilot 不支持,安装时应跳过 hook 以避免污染其配置。
    #[must_use]
    pub const fn supports_hooks(self) -> bool {
        matches!(self, AgentPlatform::Claude | AgentPlatform::Codex)
    }

    /// 返回默认 Agent 平台。
    ///
    /// 默认固定为 `Claude`;其他平台需通过 `--agent` 参数显式指定。
    /// 不扫描 `$HOME` 下各平台目录的存在性,避免隐式探测导致目标漂移。
    #[must_use]
    pub fn detect() -> Self {
        AgentPlatform::Claude
    }
}

// ---------------------------------------------------------------------------
// Install target
// ---------------------------------------------------------------------------

// (不再需要 InstallTarget enum — 用 bool global flag 表达)

// ---------------------------------------------------------------------------
// CLI args
// ---------------------------------------------------------------------------

/// Skills 管理命令集合。
#[derive(Debug, Subcommand)]
pub enum SkillsCommand {
    /// 安装 skills(默认项目级 `.claude/skills/`,-g 切换全局)
    Install(InstallArgs),
    /// 列出已安装的 skills
    List(ListArgs),
    /// 卸载已安装的 skills
    Uninstall(UninstallArgs),
}

/// `skills install` 参数。
#[derive(Debug, Args)]
pub struct InstallArgs {
    /// 安装到全局用户目录(~/.claude/skills/ 或其他 Agent 目录)
    #[arg(short = 'g', long, action = ArgAction::SetTrue)]
    pub global: bool,

    /// 目标 Agent 平台(默认 `claude`)
    #[arg(long, value_enum)]
    pub agent: Option<AgentPlatform>,

    /// 自定义安装路径(最高优先级)
    #[arg(long = "path")]
    pub custom_path: Option<String>,

    /// 强制覆盖已存在的 skills
    #[arg(short = 'f', long, action = ArgAction::SetTrue)]
    pub force: bool,

    /// 启用自动 bug 上报(Stop Hook),默认开启
    #[arg(long = "report-bug", default_value_t = true, action = ArgAction::Set)]
    pub report_bug: bool,
}

/// `skills list` 参数。
#[derive(Debug, Args)]
pub struct ListArgs {
    /// 列出全局用户目录下的 skills
    #[arg(short = 'g', long, action = ArgAction::SetTrue)]
    pub global: bool,

    /// 目标 Agent 平台(默认 `claude`)
    #[arg(long, value_enum)]
    pub agent: Option<AgentPlatform>,

    /// 自定义查找路径
    #[arg(long = "path")]
    pub custom_path: Option<String>,
}

/// `skills uninstall` 参数。
#[derive(Debug, Args)]
pub struct UninstallArgs {
    /// 从全局用户目录卸载
    #[arg(short = 'g', long, action = ArgAction::SetTrue)]
    pub global: bool,

    /// 目标 Agent 平台(默认 `claude`)
    #[arg(long, value_enum)]
    pub agent: Option<AgentPlatform>,

    /// 自定义卸载路径
    #[arg(long = "path")]
    pub custom_path: Option<String>,
}

// ---------------------------------------------------------------------------
// Path resolution
// ---------------------------------------------------------------------------

/// 解析目标目录。
///
/// 优先级:`custom_path` > `-g` 全局(按 agent)> 项目级(按 agent,默认 `Claude`)
fn resolve_target_dir(
    global: bool,
    agent: Option<AgentPlatform>,
    custom_path: Option<&str>,
) -> miette::Result<PathBuf> {
    // 自定义路径优先
    if let Some(p) = custom_path {
        return Ok(PathBuf::from(p));
    }

    let platform = agent.unwrap_or_else(AgentPlatform::detect);

    if global {
        let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
        Ok(home.join(platform.skills_dir_name()))
    } else {
        let repo_root = git_repo_root()?;
        Ok(resolve_project_target(&repo_root, platform))
    }
}

/// 解析项目级 skills 安装目录(尊重 agent 参数)。
///
/// 独立函数便于单测覆盖,避免在 `resolve_target_dir` 内部隐式调用
/// `git rev-parse`。参数 `repo_root` 已由调用方通过 `git_repo_root()` 解析,
/// 此函数仅做路径拼接(无失败分支),因此直接返回 `PathBuf`。
///
/// 注意:`agent` 接受 `AgentPlatform` 而非 `Option<AgentPlatform>`,
/// 因为调用方在调用前已确定目标平台(避免 `detect()` 重复触发)。
fn resolve_project_target(repo_root: &std::path::Path, agent: AgentPlatform) -> PathBuf {
    // `skills_dir_name` 返回 `.claude/skills` 这类相对路径,直接拼到 repo 根
    repo_root.join(agent.skills_dir_name())
}

/// Skills 源目录(仓库内的 skills/)。
fn skills_source_dir() -> PathBuf {
    // 1. 优先:binary 所在目录的上级目录(release 安装场景:binary 在 ./,skills 在 ./skills/)
    if let Ok(exe) = std::env::current_exe()
        && let Some(exe_dir) = exe.parent()
    {
        let candidate = exe_dir.join("skills");
        if candidate.exists() {
            return candidate;
        }
        // binary 在子目录(如 bin/)的场景
        if let Some(parent) = exe_dir.parent() {
            let candidate = parent.join("skills");
            if candidate.exists() {
                return candidate;
            }
        }
    }

    // 2. 回退:当前工作目录(开发场景:cargo run 在项目根目录)
    PathBuf::from("skills")
}

// ---------------------------------------------------------------------------
// Command handlers
// ---------------------------------------------------------------------------

/// 处理 `gitflow skills` 命令。
pub fn handle(command: &SkillsCommand) -> miette::Result<()> {
    match command {
        SkillsCommand::Install(args) => install_skills(args),
        SkillsCommand::List(args) => list_skills(args),
        SkillsCommand::Uninstall(args) => uninstall_skills(args),
    }
}

/// 安装 skills。
fn install_skills(args: &InstallArgs) -> miette::Result<()> {
    // 一次性解析目标平台;避免 `AgentPlatform::detect()` 在 resolve_target_dir
    // 与 install_hook 分支被重复调用。
    let platform = args.agent.unwrap_or_else(AgentPlatform::detect);

    let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;
    let source = skills_source_dir();

    let has_source = source.exists();
    let has_bundled = !SKILLS.is_empty();

    if has_source {
        // 从文件系统目录安装(开发场景或 cargo install --path)
        std::fs::create_dir_all(&target)
            .map_err(|e| miette::miette!("无法创建目标目录 {}: {e}", target.display()))?;

        let level = if args.global { "全局" } else { "项目级" };
        println!("目标: {} ({level})", target.display());

        let mut installed = 0u32;
        let mut skipped = 0u32;
        let mut overwritten = 0u32;

        for entry in std::fs::read_dir(&source)
            .map_err(|e| miette::miette!("无法读取 skills 源目录 {}: {e}", source.display()))?
        {
            let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            if !name_str.starts_with("gitflow-") {
                continue;
            }

            let dest = target.join(&name);
            if dest.exists() {
                if args.force {
                    std::fs::remove_dir_all(&dest)
                        .map_err(|e| miette::miette!("无法删除旧版本 {}: {e}", dest.display()))?;
                    copy_dir_all(&entry.path(), &dest)
                        .map_err(|e| miette::miette!("复制 {} 失败: {e}", name_str))?;
                    println!("♻ 已覆盖: {name_str}");
                    overwritten += 1;
                } else {
                    eprintln!("⚠ 跳过已存在: {name_str}");
                    skipped += 1;
                }
                continue;
            }

            copy_dir_all(&entry.path(), &dest)
                .map_err(|e| miette::miette!("复制 {} 失败: {e}", name_str))?;
            println!("✅ 已安装: {name_str}");
            installed += 1;
        }

        println!();
        println!("安装完成: 新增 {installed} 个,覆盖 {overwritten} 个,跳过 {skipped} 个");
    } else if has_bundled {
        install_skills_bundled(&target, args)?;
    } else {
        println!("⚠ Skills 源目录未找到,且 binary 未内嵌 skills 数据");
        println!("  请从源码目录运行,或手动指定 --source <skills 目录路径>");
    }

    // 安装 auto-report-bug hook(可通过 --report-bug=false 跳过)
    // 仅当目标 Agent 支持 Stop hook 时才写入;其他平台只装 skills。
    if args.report_bug {
        if platform.supports_hooks() {
            install_hook(args.global, args.force, platform)?;
        } else {
            // `AgentPlatform` 是 derived `ValueEnum`,`to_possible_value()` 对
            // 所有 variant 都返回 `Some`;保留 fallback 以满足 `-D clippy::expect_used`
            // 与 `-D clippy::unwrap_used`,避免 panic 路径。
            let name = platform.to_possible_value().map_or_else(
                || format!("{platform:?}").to_lowercase(),
                |pv| pv.get_name().to_owned(),
            );
            println!("⚠ Agent {name} 不支持 Stop hook,已跳过 hook 安装");
        }
    }

    // Co-contribution plan — interactive opt-in
    try_enable_co_contribution(platform)?;

    Ok(())
}

/// 从编译时嵌入的 SKILLS 数据安装 skills。
fn install_skills_bundled(target: &std::path::Path, args: &InstallArgs) -> miette::Result<()> {
    std::fs::create_dir_all(target).map_err(|e| miette::miette!("无法创建目标目录: {e}"))?;

    println!(
        "目标: {} ({})",
        target.display(),
        if args.global { "全局" } else { "项目级" }
    );
    println!("使用内嵌 skills 数据({} 个文件)", SKILLS.len());

    // 按 skill 目录分组
    let mut skill_dirs: std::collections::HashMap<&str, Vec<(&str, &[u8])>> =
        std::collections::HashMap::new();
    for (path, data) in SKILLS {
        let parts: Vec<&str> = path.split('/').collect();
        if parts.len() >= 2
            && parts.first().is_some_and(|f| f.starts_with("gitflow-"))
            && let Some(&first) = parts.first()
        {
            let relative = &path[first.len() + 1..];
            skill_dirs.entry(first).or_default().push((relative, *data));
        }
    }

    let mut installed = 0u32;
    let mut skipped = 0u32;
    let mut overwritten = 0u32;

    for (skill_name, files) in &skill_dirs {
        let dest = target.join(skill_name);
        install_single_skill_bundled(
            &dest,
            files,
            args,
            &mut installed,
            &mut skipped,
            &mut overwritten,
        )?;
    }

    println!();
    println!("安装完成: 新增 {installed} 个,覆盖 {overwritten} 个,跳过 {skipped} 个");
    Ok(())
}

fn install_single_skill_bundled(
    dest: &std::path::Path,
    files: &[(&str, &[u8])],
    args: &InstallArgs,
    installed: &mut u32,
    skipped: &mut u32,
    overwritten: &mut u32,
) -> miette::Result<()> {
    let is_overwrite = dest.exists();

    if is_overwrite {
        if args.force {
            std::fs::remove_dir_all(dest).map_err(|e| miette::miette!("无法删除: {e}"))?;
        } else {
            eprintln!("⚠ 跳过已存在: {}", dest.display());
            *skipped += 1;
            return Ok(());
        }
    }

    for (rel_path, data) in files {
        let file_path = dest.join(rel_path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| miette::miette!("创建目录失败: {e}"))?;
        }
        std::fs::write(&file_path, data).map_err(|e| miette::miette!("写入失败: {e}"))?;
    }

    if is_overwrite && args.force {
        println!("♻ 已覆盖: {}", dest.display());
        *overwritten += 1;
    } else {
        println!("✅ 已安装: {}", dest.display());
        *installed += 1;
    }
    Ok(())
}

/// Resolve hook directory, settings path, and command for a given install scope.
///
/// 拆成 global / project 两个私有 helper:
/// - `resolve_global_hook_paths`:基于 HOME,命令用 `~/` 简写
/// - `resolve_project_hook_paths`:基于 repo,命令用 `$(git rev-parse ...)` 解析
///
/// 两个 helper 都接受路径参数,便于单测覆盖。
fn resolve_hook_paths(
    global: bool,
    platform: AgentPlatform,
) -> miette::Result<(PathBuf, PathBuf, String)> {
    if global {
        let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
        Ok(resolve_global_hook_paths(&home, platform))
    } else {
        let repo = git_repo_root()?;
        Ok(resolve_project_hook_paths(&repo, platform))
    }
}

fn resolve_global_hook_paths(
    home: &std::path::Path,
    platform: AgentPlatform,
) -> (PathBuf, PathBuf, String) {
    let hooks_dir = platform.hooks_dir_name();
    let settings_file = platform.settings_file_path();
    let cmd = format!("bash ~/{hooks_dir}/auto-report-bug.sh");
    (home.join(hooks_dir), home.join(settings_file), cmd)
}

fn resolve_project_hook_paths(
    repo: &std::path::Path,
    platform: AgentPlatform,
) -> (PathBuf, PathBuf, String) {
    let hooks_dir = platform.hooks_dir_name();
    let settings_file = platform.settings_file_path();
    let cmd = format!(
        "bash \"$(git rev-parse --show-toplevel 2>/dev/null || \
         pwd)/{hooks_dir}/auto-report-bug.sh\""
    );
    (repo.join(hooks_dir), repo.join(settings_file), cmd)
}

/// 从文件系统目录安装 skills(开发场景)。
///
/// hook 脚本安装到平台对应的 hooks 目录(Claude 下为 `.claude/hooks/`),
/// 配置写入平台对应的 settings 文件(Claude 下为 `.claude/settings.json`)。
fn install_hook(global: bool, force: bool, platform: AgentPlatform) -> miette::Result<()> {
    let hook_script = include_bytes!("../../hooks/auto-report-bug.sh");

    let (hook_dir, settings_path, cmd) = resolve_hook_paths(global, platform)?;

    // 写 hook 脚本
    std::fs::create_dir_all(&hook_dir).map_err(|e| miette::miette!("无法创建 hook 目录: {e}"))?;
    let hook_path = hook_dir.join("auto-report-bug.sh");
    if !hook_path.exists() || force {
        std::fs::write(&hook_path, hook_script)
            .map_err(|e| miette::miette!("无法写入 hook 脚本: {e}"))?;
    }

    // 合并 Hook 配置到 settings.json
    let settings_json = if settings_path.exists() {
        let content = std::fs::read_to_string(&settings_path)
            .map_err(|e| miette::miette!("无法读取配置: {e}"))?;
        serde_json::from_str::<serde_json::Value>(&content)
            .map_err(|e| miette::miette!("无法解析配置: {e}"))?
    } else {
        serde_json::json!({})
    };

    let new_settings = merge_stop_hook(settings_json, &cmd);
    let formatted =
        serde_json::to_string_pretty(&new_settings).map_err(|e| miette::miette!("JSON: {e}"))?;
    std::fs::write(&settings_path, formatted).map_err(|e| miette::miette!("写入配置: {e}"))?;

    println!(
        "✅ Hook 已安装 ({})",
        if global { "全局" } else { "项目级" }
    );
    Ok(())
}

/// 合并 Stop Hook 配置到 JSON 对象中。
fn merge_stop_hook(mut json: serde_json::Value, cmd: &str) -> serde_json::Value {
    let hook = serde_json::json!({
        "matcher": "gitflow",
        "hooks": [
            {
                "type": "command",
                "command": cmd
            }
        ]
    });

    if let serde_json::Value::Object(obj) = &mut json {
        let hooks = obj
            .entry("hooks")
            .or_insert(serde_json::json!({"Stop": []}));
        if let serde_json::Value::Object(h) = hooks {
            let stops = h.entry("Stop").or_insert(serde_json::json!([]));
            if let serde_json::Value::Array(arr) = stops {
                // 替换已存在的 gitflow hook 或追加
                if let Some(existing) = arr
                    .iter_mut()
                    .find(|v| v.get("matcher").and_then(|m| m.as_str()) == Some("gitflow"))
                {
                    *existing = hook;
                } else {
                    arr.push(hook);
                }
            }
        }
    } else {
        json = serde_json::json!({
            "hooks": {
                "Stop": [hook]
            }
        });
    }

    json
}

/// 获取当前仓库根目录(不在 git 仓库中则回退到当前目录)。
fn git_repo_root() -> miette::Result<std::path::PathBuf> {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output();
    match output {
        Ok(out) if out.status.success() => Ok(std::path::PathBuf::from(
            String::from_utf8_lossy(&out.stdout).trim(),
        )),
        _ => std::env::current_dir().map_err(|e| miette::miette!("无法获取当前目录: {e}")),
    }
}

/// 列出已安装的 skills。
fn list_skills(args: &ListArgs) -> miette::Result<()> {
    let target = resolve_target_dir(args.global, args.agent, args.custom_path.as_deref())?;

    if !target.exists() {
        println!("(未安装任何 skills)");
        println!("目录: {}", target.display());
        return Ok(());
    }

    println!("目录: {}", target.display());
    println!();

    let mut found = 0u32;
    for entry in std::fs::read_dir(&target)
        .map_err(|e| miette::miette!("读取目录失败 {}: {e}", target.display()))?
    {
        let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
        let name_str = entry.file_name().to_string_lossy().into_owned();
        if name_str.starts_with("gitflow-") {
            println!("  {name_str}");
            found += 1;
        }
    }

    if found == 0 {
        println!("(未安装任何 gitflow skills)");
    } else {
        println!();
        println!("共 {found} 个 skills");
    }
    Ok(())
}

/// 卸载 skills。
fn uninstall_skills(args: &UninstallArgs) -> miette::Result<()> {
    // 一次性解析目标平台;与 `install_skills` 对称,避免重复 detect()。
    let platform = args.agent.unwrap_or_else(AgentPlatform::detect);

    let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;

    if !target.exists() {
        println!("(未安装任何 skills)");
        println!("目录: {}", target.display());
        return Ok(());
    }

    println!("目录: {}", target.display());
    println!();

    let mut removed = 0u32;
    for entry in std::fs::read_dir(&target)
        .map_err(|e| miette::miette!("读取目录失败 {}: {e}", target.display()))?
    {
        let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
        let name_str = entry.file_name().to_string_lossy().into_owned();
        if name_str.starts_with("gitflow-") {
            let path = entry.path();
            if path.is_dir() {
                std::fs::remove_dir_all(&path)
                    .map_err(|e| miette::miette!("删除 {} 失败: {e}", path.display()))?;
            } else {
                std::fs::remove_file(&path)
                    .map_err(|e| miette::miette!("删除 {} 失败: {e}", path.display()))?;
            }
            println!("✅ 已卸载: {name_str}");
            removed += 1;
        }
    }

    if removed == 0 {
        println!("(未安装任何 gitflow skills)");
    } else {
        println!();
        println!("已卸载 {removed} 个 skills");
    }

    // 移除 Hook 配置(幂等操作,对所有平台都尝试;未安装时静默退出)
    uninstall_hook(args.global, platform)?;

    Ok(())
}

/// 从配置中移除 Stop Hook,并清理 hook 脚本文件。
fn uninstall_hook(global: bool, platform: AgentPlatform) -> miette::Result<()> {
    let (hook_dir, settings_path) = if global {
        let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
        (
            home.join(platform.hooks_dir_name()),
            home.join(platform.settings_file_path()),
        )
    } else {
        let repo = git_repo_root()?;
        (
            repo.join(platform.hooks_dir_name()),
            repo.join(platform.settings_file_path()),
        )
    };

    // 删除 hook 脚本文件
    let hook_script = hook_dir.join("auto-report-bug.sh");
    if hook_script.exists() {
        std::fs::remove_file(&hook_script)
            .map_err(|e| miette::miette!("无法删除 hook 脚本 {}: {e}", hook_script.display()))?;
        // 如果 hook 目录为空,也删除目录
        if hook_dir.exists()
            && std::fs::read_dir(&hook_dir).map_or(true, |mut d| d.next().is_none())
        {
            std::fs::remove_dir(&hook_dir).ok();
        }
    }

    if !settings_path.exists() {
        return Ok(());
    }

    let content = std::fs::read_to_string(&settings_path)
        .map_err(|e| miette::miette!("无法读取配置: {e}"))?;
    let mut json: serde_json::Value =
        serde_json::from_str(&content).map_err(|e| miette::miette!("无法解析: {e}"))?;

    if let Some(obj) = json.as_object_mut()
        && let Some(hooks) = obj.get_mut("hooks")
        && let Some(stop) = hooks.get_mut("Stop")
        && let Some(arr) = stop.as_array_mut()
    {
        arr.retain(|v| v.get("matcher").and_then(|m| m.as_str()) != Some("gitflow"));
    }

    let formatted =
        serde_json::to_string_pretty(&json).map_err(|e| miette::miette!("JSON: {e}"))?;
    std::fs::write(&settings_path, formatted).map_err(|e| miette::miette!("写入: {e}"))?;
    println!("✅ Hook 已卸载");

    Ok(())
}

// ---------------------------------------------------------------------------
// Co-contribution opt-in
// ---------------------------------------------------------------------------

/// Prompt the user to join the co-contribution plan and verify GitHub auth.
///
/// In non-interactive mode, silently skips. In interactive mode, asks the user
/// whether to join, checks `gh auth status`, and writes the settings.json marker
/// on success.
fn try_enable_co_contribution(platform: AgentPlatform) -> miette::Result<()> {
    if !std::io::stderr().is_terminal() {
        println!("ℹ️ 非交互模式,已跳过共建计划");
        return Ok(());
    }

    println!();
    println!("🤝 共建计划:加入后,CLI 错误将自动上报为 GitHub Issue,帮助改进 gitflow-cli。");
    println!("   用户级设置,加入一次即所有项目生效。");
    println!();

    if !confirm("是否加入共建计划?", true)? {
        println!("已跳过共建计划。你可以稍后运行 `skills install --force` 重新加入。");
        return Ok(());
    }

    // Check GitHub auth
    let auth_provider = gitflow_cli_github::GitHubAuthProvider::new();
    if auth_provider.is_authenticated() {
        merge_co_contribution(platform)?;
        println!("✅ 共建计划已激活");
    } else {
        println!("⚠️ 未检测到 GitHub 登录。");
        if confirm("是否现在执行 `gh auth login`?", true)? {
            let status = std::process::Command::new("gh")
                .args(["auth", "login"])
                .stdin(std::process::Stdio::inherit())
                .stdout(std::process::Stdio::inherit())
                .stderr(std::process::Stdio::inherit())
                .status();
            match status {
                Ok(s) if s.success() => {
                    merge_co_contribution(platform)?;
                    println!("✅ 共建计划已激活");
                }
                _ => {
                    println!(
                        "登录失败。请手动运行 `gh auth login`,然后重新 `skills install --force`。"
                    );
                }
            }
        } else {
            println!(
                "请手动运行 `gh auth login`,然后重新 `skills install --force` 激活共建计划。"
            );
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Co-contribution marker
// ---------------------------------------------------------------------------

/// Merge the co-contribution marker into a settings JSON object.
///
/// Sets `gitflow.co_contribution = true` and `gitflow.joined_at` to the given
/// ISO 8601 timestamp. Preserves all existing fields.
fn merge_co_contribution_json(mut json: serde_json::Value, joined_at: &str) -> serde_json::Value {
    if let serde_json::Value::Object(ref mut obj) = json {
        let gitflow = obj.entry("gitflow").or_insert(serde_json::json!({}));
        if let serde_json::Value::Object(gf) = gitflow {
            gf.insert("co_contribution".into(), serde_json::json!(true));
            gf.insert("joined_at".into(), serde_json::json!(joined_at));
        }
    } else {
        json = serde_json::json!({
            "gitflow": {
                "co_contribution": true,
                "joined_at": joined_at
            }
        });
    }
    json
}

/// Write the co-contribution marker to the platform's settings.json.
///
/// Reads the existing settings file (or creates an empty JSON object),
/// merges the `gitflow.co_contribution` field, and writes back.
fn merge_co_contribution(platform: AgentPlatform) -> miette::Result<()> {
    let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
    let (_hook_dir, settings_path, _cmd) = resolve_global_hook_paths(&home, platform);

    let existing = if settings_path.exists() {
        let content = std::fs::read_to_string(&settings_path)
            .map_err(|e| miette::miette!("无法读取配置 {}: {e}", settings_path.display()))?;
        serde_json::from_str::<serde_json::Value>(&content)
            .map_err(|e| miette::miette!("无法解析配置 {}: {e}", settings_path.display()))?
    } else {
        serde_json::json!({})
    };

    let joined_at = iso8601_utc_now_co_contribution();
    let new_settings = merge_co_contribution_json(existing, &joined_at);
    let formatted = serde_json::to_string_pretty(&new_settings)
        .map_err(|e| miette::miette!("JSON 序列化失败: {e}"))?;

    // 确保目录存在
    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| miette::miette!("无法创建目录 {}: {e}", parent.display()))?;
    }

    std::fs::write(&settings_path, formatted)
        .map_err(|e| miette::miette!("写入配置失败 {}: {e}", settings_path.display()))?;

    Ok(())
}

/// Format the current UTC time as ISO 8601 for the co-contribution marker.
#[allow(
    dead_code,
    reason = "called by `merge_co_contribution`; direct calls from tests for isolation"
)]
#[allow(
    clippy::cast_possible_wrap,
    clippy::cast_lossless,
    clippy::cast_sign_loss,
    reason = "Howard Hinnant's algorithm operates on mixed-sign integer ranges within known bounds"
)]
fn iso8601_utc_now_co_contribution() -> String {
    // Reuse the same algorithm as error_reporter::iso8601_utc_now
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    // Inline Howard Hinnant's algorithm (same as error_reporter)
    let day_secs = secs % 86_400;
    let hours = day_secs / 3_600;
    let minutes = (day_secs % 3_600) / 60;
    let seconds = day_secs % 60;
    let days = (secs / 86_400) as i64;
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe as i64 + era * 400;
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// 递归复制目录。
fn copy_dir_all(src: &PathBuf, dst: &PathBuf) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        let dest_path = dst.join(entry.file_name());
        if ty.is_dir() {
            copy_dir_all(&entry.path(), &dest_path)?;
        } else {
            std::fs::copy(entry.path(), &dest_path)?;
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Interactive prompts
// ---------------------------------------------------------------------------

/// Read a Y/n confirmation from stdin.
///
/// Displays `prompt` and reads one line. Accepts `y/yes` (case-insensitive) as true,
/// `n/no` as false, and empty input as `default`. On EOF or invalid input after 3
/// retries, returns `default`.
fn confirm(prompt: &str, default: bool) -> miette::Result<bool> {
    let stdin = std::io::stdin();
    let mut reader = stdin.lock();
    confirm_with_reader(prompt, default, &mut reader)
}

/// Testable core of [`confirm`] — reads from any `BufRead` source.
#[allow(
    dead_code,
    reason = "called by `confirm`; direct calls from tests for isolation"
)]
fn confirm_with_reader(
    prompt: &str,
    default: bool,
    reader: &mut impl std::io::BufRead,
) -> miette::Result<bool> {
    use std::io::Write;
    let hint = if default { "[Y/n]" } else { "[y/N]" };
    print!("{prompt} {hint} ");
    let _ = std::io::stdout().flush();

    for _ in 0..3 {
        let mut line = String::new();
        let bytes_read = reader
            .read_line(&mut line)
            .map_err(|e| miette::miette!("读取输入失败: {e}"))?;

        if bytes_read == 0 {
            // EOF
            return Ok(default);
        }

        match line.trim().to_lowercase().as_str() {
            "" => return Ok(default),
            "y" | "yes" => return Ok(true),
            "n" | "no" => return Ok(false),
            _ => {
                print!("请输入 y 或 n: ");
                let _ = std::io::stdout().flush();
            }
        }
    }

    Ok(default)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    reason = "允许在测试中使用 expect/unwrap/panic"
)]
mod tests {
    use super::*;

    #[test]
    fn test_agent_platform_claude_dir() {
        assert_eq!(AgentPlatform::Claude.skills_dir_name(), ".claude/skills");
    }

    #[test]
    fn test_agent_platform_codex_dir() {
        assert_eq!(AgentPlatform::Codex.skills_dir_name(), ".codex/skills");
    }

    #[test]
    fn test_agent_platform_opencode_dir() {
        assert_eq!(
            AgentPlatform::OpenCode.skills_dir_name(),
            ".opencode/skills"
        );
    }

    #[test]
    fn test_agent_detect_always_returns_claude() {
        // 契约:detect() 默认固定返回 Claude,不扫描 $HOME 下其他平台目录。
        // 其他平台必须通过 `--agent` 显式指定。
        assert_eq!(AgentPlatform::detect(), AgentPlatform::Claude);
    }

    #[test]
    fn test_agent_platform_claude_hooks_dir() {
        assert_eq!(AgentPlatform::Claude.hooks_dir_name(), ".claude/hooks");
    }

    #[test]
    fn test_agent_platform_codex_hooks_dir() {
        assert_eq!(AgentPlatform::Codex.hooks_dir_name(), ".codex/hooks");
    }

    #[test]
    fn test_agent_platform_opencode_hooks_dir() {
        assert_eq!(AgentPlatform::OpenCode.hooks_dir_name(), ".opencode/hooks");
    }

    #[test]
    fn test_agent_platform_gemini_hooks_dir() {
        assert_eq!(AgentPlatform::Gemini.hooks_dir_name(), ".gemini/hooks");
    }

    #[test]
    fn test_agent_platform_copilot_hooks_dir() {
        assert_eq!(AgentPlatform::Copilot.hooks_dir_name(), ".copilot/hooks");
    }

    #[test]
    fn test_agent_platform_claude_settings_path() {
        assert_eq!(
            AgentPlatform::Claude.settings_file_path(),
            ".claude/settings.json"
        );
    }

    #[test]
    fn test_agent_platform_codex_settings_path() {
        assert_eq!(
            AgentPlatform::Codex.settings_file_path(),
            ".codex/settings.json"
        );
    }

    #[test]
    fn test_agent_platform_opencode_settings_path() {
        assert_eq!(
            AgentPlatform::OpenCode.settings_file_path(),
            ".opencode/settings.json"
        );
    }

    #[test]
    fn test_agent_platform_gemini_settings_path() {
        assert_eq!(
            AgentPlatform::Gemini.settings_file_path(),
            ".gemini/settings.json"
        );
    }

    #[test]
    fn test_agent_platform_copilot_settings_path() {
        assert_eq!(
            AgentPlatform::Copilot.settings_file_path(),
            ".copilot/settings.json"
        );
    }

    #[test]
    fn test_resolve_global_target_claude() {
        let dir = resolve_target_dir(true, Some(AgentPlatform::Claude), None).expect("resolve");
        assert!(dir.ends_with(".claude/skills"));
    }

    #[test]
    fn test_resolve_global_target_codex() {
        let dir = resolve_target_dir(true, Some(AgentPlatform::Codex), None).expect("resolve");
        assert!(dir.ends_with(".codex/skills"));
    }

    #[test]
    fn test_resolve_global_target_gemini() {
        let dir = resolve_target_dir(true, Some(AgentPlatform::Gemini), None).expect("resolve");
        assert!(dir.ends_with(".gemini/skills"));
    }

    #[test]
    fn test_resolve_project_target_respects_agent() {
        // 项目级必须遵循 --agent;不能硬编码到 .claude/skills
        let repo = PathBuf::from("/tmp/test-repo-skills");
        let dir = resolve_project_target(&repo, AgentPlatform::Codex);
        assert!(
            dir.ends_with(".codex/skills"),
            "project-level install must respect --agent, got {}",
            dir.display()
        );

        let dir_gemini = resolve_project_target(&repo, AgentPlatform::Gemini);
        assert!(dir_gemini.ends_with(".gemini/skills"));
    }

    #[test]
    fn test_agent_supports_hooks_matrix() {
        assert!(AgentPlatform::Claude.supports_hooks());
        assert!(AgentPlatform::Codex.supports_hooks());
        assert!(!AgentPlatform::OpenCode.supports_hooks());
        assert!(!AgentPlatform::Gemini.supports_hooks());
        assert!(!AgentPlatform::Copilot.supports_hooks());
    }

    #[test]
    fn test_resolve_custom_path_overrides_all() {
        let dir = resolve_target_dir(false, Some(AgentPlatform::Claude), Some("/tmp/my-skills"))
            .expect("resolve");
        assert_eq!(dir, PathBuf::from("/tmp/my-skills"));
    }

    #[test]
    fn test_skills_source_dir_is_valid_path() {
        let dir = skills_source_dir();
        assert!(dir.ends_with("skills"));
    }

    #[test]
    fn test_merge_stop_hook_creates_nested_format() {
        let input = serde_json::json!({});
        let result = merge_stop_hook(input, "bash hooks/auto-report-bug.sh");

        let hooks = result
            .pointer("/hooks/Stop/0/hooks")
            .and_then(serde_json::Value::as_array)
            .expect("should create nested hooks array");
        assert_eq!(hooks.len(), 1);
        assert_eq!(
            hooks[0].get("type").and_then(serde_json::Value::as_str),
            Some("command")
        );
        assert_eq!(
            hooks[0].get("command").and_then(serde_json::Value::as_str),
            Some("bash hooks/auto-report-bug.sh")
        );
        assert_eq!(
            result
                .pointer("/hooks/Stop/0/matcher")
                .and_then(serde_json::Value::as_str),
            Some("gitflow")
        );
    }

    #[test]
    fn test_merge_stop_hook_replaces_existing_gitflow() {
        let input = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "gitflow",
                        "command": "old-command.sh"
                    }
                ]
            }
        });
        let result = merge_stop_hook(input, "bash hooks/auto-report-bug.sh");

        let stop = result
            .pointer("/hooks/Stop")
            .and_then(serde_json::Value::as_array)
            .expect("Stop array should exist");
        assert_eq!(stop.len(), 1, "should replace, not duplicate");
        assert!(
            stop[0].get("hooks").is_some(),
            "should use nested hooks format"
        );
        assert!(
            stop[0].get("command").is_none(),
            "flat command field should be gone"
        );
    }

    #[test]
    fn test_merge_stop_hook_preserves_other_hooks() {
        let input = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "other-agent",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "other-command.sh"
                            }
                        ]
                    }
                ]
            }
        });
        let result = merge_stop_hook(input, "bash hooks/auto-report-bug.sh");

        let stop = result
            .pointer("/hooks/Stop")
            .and_then(serde_json::Value::as_array)
            .expect("Stop array should exist");
        assert_eq!(stop.len(), 2, "should keep other matcher and add gitflow");
    }

    /// Test is Unix-only: uses `dirs::home_dir()` which on Windows ignores HOME env var.
    #[cfg(unix)]
    #[test]
    fn test_uninstall_hook_removes_gitflow() {
        // 用临时目录隔离,避免污染真实 HOME
        let tmp = tempfile::tempdir().expect("create temp dir");

        // 准备一个含 gitflow hook 的 settings.json(新嵌套格式)
        let settings_path = tmp.path().join(".claude/settings.json");
        std::fs::create_dir_all(tmp.path().join(".claude")).expect("create .claude dir");
        let content = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "gitflow",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "bash hooks/auto-report-bug.sh"
                            }
                        ]
                    }
                ]
            }
        });
        std::fs::write(
            &settings_path,
            serde_json::to_string_pretty(&content).expect("serialize"),
        )
        .expect("write settings");

        // 调用 uninstall_hook(全局模式),用 temp_env 隔离 HOME
        temp_env::with_var("HOME", Some(tmp.path()), || {
            super::uninstall_hook(true, AgentPlatform::Claude).expect("uninstall should succeed");
        });

        // 验证 gitflow hook 已被删除
        let after = std::fs::read_to_string(&settings_path).expect("read after");
        let parsed: serde_json::Value = serde_json::from_str(&after).expect("parse after");
        let stop = parsed
            .pointer("/hooks/Stop")
            .and_then(serde_json::Value::as_array)
            .expect("Stop should exist");
        assert!(
            stop.iter()
                .all(|v| v.get("matcher").and_then(serde_json::Value::as_str) != Some("gitflow")),
            "gitflow hook should be removed"
        );
    }

    /// Test is Unix-only: uses `dirs::home_dir()` which on Windows ignores HOME env var.
    #[cfg(unix)]
    #[test]
    fn test_uninstall_hook_preserves_others() {
        let tmp = tempfile::tempdir().expect("create temp dir");

        let settings_path = tmp.path().join(".claude/settings.json");
        std::fs::create_dir_all(tmp.path().join(".claude")).expect("create .claude dir");
        let content = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "gitflow",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "bash hooks/auto-report-bug.sh"
                            }
                        ]
                    },
                    {
                        "matcher": "other-agent",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "other.sh"
                            }
                        ]
                    }
                ]
            }
        });
        std::fs::write(
            &settings_path,
            serde_json::to_string_pretty(&content).expect("serialize"),
        )
        .expect("write settings");

        temp_env::with_var("HOME", Some(tmp.path()), || {
            super::uninstall_hook(true, AgentPlatform::Claude).expect("uninstall should succeed");
        });

        let after = std::fs::read_to_string(&settings_path).expect("read after");
        let parsed: serde_json::Value = serde_json::from_str(&after).expect("parse after");
        let stop = parsed
            .pointer("/hooks/Stop")
            .and_then(serde_json::Value::as_array)
            .expect("Stop should exist");
        assert_eq!(stop.len(), 1, "other-agent hook should remain");
        assert_eq!(
            stop[0].get("matcher").and_then(serde_json::Value::as_str),
            Some("other-agent")
        );
    }

    /// Test is Unix-only: uses `dirs::home_dir()` which on Windows ignores HOME env var.
    #[cfg(unix)]
    #[test]
    fn test_uninstall_hook_deletes_script_file_and_empty_dir() {
        let tmp = tempfile::tempdir().expect("create temp dir");

        // Create .claude/hooks/ directory with a fake hook script
        let hooks_dir = tmp.path().join(".claude/hooks");
        std::fs::create_dir_all(&hooks_dir).expect("create hooks dir");
        let hook_script = hooks_dir.join("auto-report-bug.sh");
        std::fs::write(&hook_script, b"#!/bin/bash\necho test\n").expect("write hook script");

        // Create settings.json with gitflow hook
        let settings_path = tmp.path().join(".claude/settings.json");
        let content = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "gitflow",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "bash .claude/hooks/auto-report-bug.sh"
                            }
                        ]
                    }
                ]
            }
        });
        std::fs::write(
            &settings_path,
            serde_json::to_string_pretty(&content).expect("serialize"),
        )
        .expect("write settings");

        temp_env::with_var("HOME", Some(tmp.path()), || {
            super::uninstall_hook(true, AgentPlatform::Claude).expect("uninstall should succeed");
        });

        // Verify script file was deleted
        assert!(
            !hook_script.exists(),
            "hook script should be deleted by uninstall"
        );
        // Verify empty hooks dir was removed
        assert!(
            !hooks_dir.exists(),
            "empty hooks directory should be removed"
        );
    }

    #[test]
    fn test_resolve_project_hook_paths_uses_hooks_dir() {
        let repo = PathBuf::from("/tmp/test-repo");
        let (hook_dir, settings_path, cmd) =
            resolve_project_hook_paths(&repo, AgentPlatform::Claude);
        assert_eq!(
            hook_dir,
            repo.join(".claude/hooks"),
            "hook should be in .claude/hooks/"
        );
        assert_eq!(settings_path, repo.join(".claude/settings.json"));
        assert!(
            cmd.contains(".claude/hooks/auto-report-bug.sh"),
            "command should reference .claude/hooks/ path"
        );
    }

    #[test]
    fn test_resolve_global_hook_paths_uses_claude_hooks_dir() {
        let home = PathBuf::from("/home/user");
        let (hook_dir, settings_path, cmd) =
            resolve_global_hook_paths(&home, AgentPlatform::Claude);
        assert_eq!(hook_dir, home.join(".claude/hooks"));
        assert_eq!(settings_path, home.join(".claude/settings.json"));
        assert!(cmd.contains("~/.claude/hooks/auto-report-bug.sh"));
    }

    #[test]
    fn test_should_parse_report_bug_false() {
        use clap::Parser;

        #[derive(Debug, Parser)]
        struct TestCli {
            #[command(subcommand)]
            cmd: TestCmd,
        }

        #[derive(Debug, Subcommand)]
        enum TestCmd {
            Install(InstallArgs),
        }

        let cli = TestCli::parse_from(["test", "install", "--report-bug=false"]);
        let TestCmd::Install(args) = cli.cmd;
        assert!(
            !args.report_bug,
            "--report-bug=false must set report_bug to false"
        );
    }

    #[test]
    fn test_should_default_report_bug_to_true() {
        use clap::Parser;

        #[derive(Debug, Parser)]
        struct TestCli {
            #[command(subcommand)]
            cmd: TestCmd,
        }

        #[derive(Debug, Subcommand)]
        enum TestCmd {
            Install(InstallArgs),
        }

        let cli = TestCli::parse_from(["test", "install"]);
        let TestCmd::Install(args) = cli.cmd;
        assert!(args.report_bug, "report_bug must default to true");
    }

    #[test]
    fn test_should_count_overwritten_in_bundled_path() {
        // Verify that install_single_skill_bundled correctly increments `overwritten`
        // ONLY when force=true AND dest already existed before the call.
        // This catches the dead-code bug where `args.force && dest.exists()` was
        // checked AFTER files were written (so dest.exists() was always true),
        // causing fresh installs with force=true to falsely increment overwritten.
        let tmp = tempfile::tempdir().expect("create temp dir");

        // Case 1: fresh install (dest does NOT exist), force=true
        // Expected: overwritten=0, installed=1
        let dest_fresh = tmp.path().join("fresh-skill");
        let args = InstallArgs {
            agent: Some(AgentPlatform::Claude),
            global: false,
            force: true,
            report_bug: false,
            custom_path: None,
        };
        let files: &[(&str, &[u8])] = &[("test.md", b"# Test Skill")];

        let mut installed = 0u32;
        let mut skipped = 0u32;
        let mut overwritten = 0u32;

        install_single_skill_bundled(
            &dest_fresh,
            files,
            &args,
            &mut installed,
            &mut skipped,
            &mut overwritten,
        )
        .expect("install should succeed");

        assert_eq!(
            overwritten, 0,
            "fresh install with force=true should NOT count as overwritten"
        );
        assert_eq!(installed, 1, "fresh install should count as installed");
        assert_eq!(skipped, 0, "fresh install should not count as skipped");

        // Case 2: overwrite (dest already exists), force=true
        // Expected: overwritten=1, installed stays at 1
        let mut installed = 0u32;
        let mut skipped = 0u32;
        let mut overwritten = 0u32;

        // Pre-create the destination directory so it counts as an overwrite
        let dest_existing = tmp.path().join("existing-skill");
        std::fs::create_dir_all(&dest_existing).expect("create dest dir");
        std::fs::write(dest_existing.join("old.txt"), b"old data").expect("write old file");

        install_single_skill_bundled(
            &dest_existing,
            files,
            &args,
            &mut installed,
            &mut skipped,
            &mut overwritten,
        )
        .expect("install should succeed");

        assert_eq!(
            overwritten, 1,
            "overwrite of existing dir with force=true should increment overwritten"
        );
        assert_eq!(installed, 0, "overwrite should not count as fresh install");
        assert_eq!(
            skipped, 0,
            "overwrite with force should not count as skipped"
        );
    }

    // -----------------------------------------------------------------------
    // confirm / confirm_with_reader tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_return_default_on_empty_input() {
        // Simulate empty input by providing a reader with just a newline
        let input = b"\n";
        let result = confirm_with_reader("Continue?", true, &mut &input[..]).expect("confirm");
        assert!(result, "empty input should return default=true");

        let result = confirm_with_reader("Continue?", false, &mut &input[..]).expect("confirm");
        assert!(!result, "empty input should return default=false");
    }

    #[test]
    fn test_should_accept_yes_variants() {
        for answer in &[b"y\n" as &[u8], b"Y\n", b"yes\n", b"YES\n"] {
            let result = confirm_with_reader("Continue?", false, &mut &**answer).expect("confirm");
            assert!(result, "input {answer:?} should be accepted as yes");
        }
    }

    #[test]
    fn test_should_accept_no_variants() {
        for answer in &[b"n\n" as &[u8], b"N\n", b"no\n", b"NO\n"] {
            let result = confirm_with_reader("Continue?", true, &mut &**answer).expect("confirm");
            assert!(!result, "input {answer:?} should be accepted as no");
        }
    }

    #[test]
    fn test_should_return_default_on_eof() {
        let input: &[u8] = b"";
        let result = confirm_with_reader("Continue?", true, &mut &input[..]).expect("confirm");
        assert!(result, "EOF should return default=true");
    }

    // -----------------------------------------------------------------------
    // merge_co_contribution_json tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_merge_co_contribution_into_empty_settings() {
        let input = serde_json::json!({});
        let result = merge_co_contribution_json(input, "2026-07-09T08:30:00Z");

        assert_eq!(
            result
                .pointer("/gitflow/co_contribution")
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
        assert_eq!(
            result
                .pointer("/gitflow/joined_at")
                .and_then(serde_json::Value::as_str),
            Some("2026-07-09T08:30:00Z")
        );
    }

    #[test]
    fn test_should_preserve_existing_hooks_when_merging_co_contribution() {
        let input = serde_json::json!({
            "hooks": {
                "Stop": [
                    {
                        "matcher": "gitflow",
                        "hooks": [{"type": "command", "command": "bash hook.sh"}]
                    }
                ]
            }
        });
        let result = merge_co_contribution_json(input, "2026-07-09T08:30:00Z");

        // hooks must be preserved
        let stop = result
            .pointer("/hooks/Stop")
            .and_then(serde_json::Value::as_array);
        assert!(stop.is_some(), "existing hooks must be preserved");
        assert_eq!(stop.expect("stop array").len(), 1);

        // co_contribution must be added
        assert_eq!(
            result
                .pointer("/gitflow/co_contribution")
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
    }

    #[test]
    fn test_should_update_existing_gitflow_section() {
        let input = serde_json::json!({
            "gitflow": {
                "co_contribution": false,
                "joined_at": "2020-01-01T00:00:00Z"
            }
        });
        let result = merge_co_contribution_json(input, "2026-07-09T08:30:00Z");

        assert_eq!(
            result
                .pointer("/gitflow/co_contribution")
                .and_then(serde_json::Value::as_bool),
            Some(true),
            "co_contribution must be updated to true"
        );
        assert_eq!(
            result
                .pointer("/gitflow/joined_at")
                .and_then(serde_json::Value::as_str),
            Some("2026-07-09T08:30:00Z"),
            "joined_at must be updated"
        );
    }

    /// Test is Unix-only: uses `dirs::home_dir()` which on Windows ignores HOME env var.
    #[cfg(unix)]
    #[test]
    fn test_should_write_co_contribution_to_global_path() {
        let temp = tempfile::tempdir().expect("tempdir");
        let home = temp.path();

        // 使用 temp_env 安全地设置 HOME 环境变量
        temp_env::with_var("HOME", Some(home), || {
            // 验证始终写入全局路径(不依赖 --global 标志)
            let result = merge_co_contribution(AgentPlatform::Claude);

            assert!(
                result.is_ok(),
                "merge_co_contribution should succeed: {:?}",
                result.err()
            );

            // 验证写入全局路径
            let global_settings = home.join(".claude/settings.json");
            assert!(
                global_settings.exists(),
                "global settings.json must be created"
            );

            let content = std::fs::read_to_string(&global_settings).expect("read");
            let json: serde_json::Value = serde_json::from_str(&content).expect("parse");

            assert_eq!(
                json.pointer("/gitflow/co_contribution")
                    .and_then(serde_json::Value::as_bool),
                Some(true),
                "co_contribution must be true in global settings"
            );
            assert!(
                json.pointer("/gitflow/joined_at")
                    .and_then(serde_json::Value::as_str)
                    .is_some(),
                "joined_at must be set in global settings"
            );
        });
    }
}