uta 0.1.2

Command-line music search and downloader for QQ Music and NetEase Cloud Music, lossless first, shipped as a single static binary. For learning and research only; non-commercial use.
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
mod config;
mod doctor;
mod download;
mod lrc;
mod merge;
mod model;
mod net;
mod netease;
mod probe;
mod qq;
mod source;
mod tags;

use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
use comfy_table::{ContentArrangement, Table, presets::UTF8_FULL_CONDENSED};
use futures::{StreamExt, stream};
use inquire::{InquireError, MultiSelect, Select};
use tracing_subscriber::EnvFilter;

use config::{Config, Defaults, expand_home};
use download::{Item, Outcome, download_all, part_path, plan_paths};
use model::{Level, ResolveOptions, Song, SourceKind};

use model::{AlbumHit, AlbumKind, AlbumOrder, ArtistAlbum, SingerHit};
use source::Sources;

const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36";

#[derive(Parser)]
#[command(
    name = "uta",
    version,
    about = "音乐搜索 / 下载,支持 QQ 音乐、网易云音乐(仅供学习研究,禁止商业用途)"
)]
struct Cli {
    /// 配置文件路径(默认 ~/.config/uta/config.toml)
    #[arg(long, global = true, value_name = "PATH")]
    config: Option<PathBuf>,
    /// 输出调试日志(-vv 更详细)
    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
    verbose: u8,
    #[command(subcommand)]
    command: Command,
}

#[derive(Args, Clone)]
struct CommonArgs {
    /// 音源:qq | netease(或 163)[默认: qq];粘贴的链接会自动识别音源。
    /// search 可同时搜多个:-s qq,163
    #[arg(
        short = 's',
        long,
        value_enum,
        value_delimiter = ',',
        value_name = "SOURCE"
    )]
    source: Vec<SourceKind>,
    /// 只保留无损结果(第三方接口拿不到无损即丢弃)
    #[arg(long)]
    lossless: bool,
    /// 不从其他音源补链接(默认本音源拿不到时,到其他音源找同一首歌)
    #[arg(long)]
    no_fallback: bool,
    /// 最高音质档位 [默认: master,即臻品母带,单首常达 150–200MB]
    #[arg(short = 'q', long, value_enum)]
    max_quality: Option<Level>,
    /// 输出目录 [默认: 当前目录]
    #[arg(short = 'o', long, value_name = "DIR")]
    output: Option<PathBuf>,
    /// 解析并发数 [默认: 8]
    #[arg(short = 'j', long, value_parser = clap::value_parser!(u16).range(1..=64))]
    jobs: Option<u16>,
    /// 下载并发数 [默认: 4]
    #[arg(short = 'J', long, value_parser = clap::value_parser!(u16).range(1..=16))]
    download_jobs: Option<u16>,
}

/// 合并命令行、配置文件 `[defaults]`、内置默认值后的最终设置。
#[derive(Debug, Clone)]
struct Settings {
    /// 去重后的音源列表(至少一个);除 search 外只用第一个
    sources: Vec<SourceKind>,
    /// 本音源拿不到链接时到其他音源补
    fallback: bool,
    opts: ResolveOptions,
    output: PathBuf,
    jobs: usize,
    download_jobs: usize,
}

#[derive(Subcommand)]
enum Command {
    /// 搜索歌曲 → 表格 → 交互多选 → 下载
    Search {
        /// 搜索关键词
        keyword: String,
        /// 取多少条搜索结果(多音源时为每个音源各取 N 条)
        #[arg(short = 'n', long, default_value_t = 10, value_parser = clap::value_parser!(u16).range(1..=200))]
        num: u16,
        /// 只输出 JSON,不交互、不下载
        #[arg(long)]
        json: bool,
        /// 多音源时不合并重复歌曲(默认同一首歌只保留音质更好的一份)
        #[arg(long)]
        no_merge: bool,
        #[command(flatten)]
        common: CommonArgs,
    },
    /// 下载歌单(歌单链接或数字 ID)
    Playlist {
        /// 歌单链接或 ID,如 https://y.qq.com/n/ryqq/playlist/7039749142、https://music.163.com/#/playlist?id=3778678
        playlist: String,
        /// 只取前 N 首
        #[arg(short = 'n', long, value_parser = clap::value_parser!(u32).range(1..))]
        num: Option<u32>,
        /// 只输出 JSON,不交互、不下载
        #[arg(long)]
        json: bool,
        /// 不弹出选择,直接下载全部
        #[arg(short = 'y', long)]
        yes: bool,
        #[command(flatten)]
        common: CommonArgs,
    },
    /// 下载专辑(关键词、专辑链接,或 --mid)
    Album {
        /// 专辑关键词或专辑链接(如 https://y.qq.com/n/ryqq/albumDetail/0024bjiL2aocxT)
        #[arg(required_unless_present = "mid", conflicts_with = "mid")]
        query: Option<String>,
        /// 直接指定专辑:QQ 为 14 位 albummid 或数字 albumID,网易为数字 id
        #[arg(long, value_name = "MID")]
        mid: Option<String>,
        /// 只取前 N 首
        #[arg(short = 'n', long, value_parser = clap::value_parser!(u32).range(1..))]
        num: Option<u32>,
        /// 只输出 JSON,不交互、不下载(关键词时输出专辑搜索结果)
        #[arg(long)]
        json: bool,
        /// 不弹出选择:关键词时取第 1 个专辑,并下载全部曲目
        #[arg(short = 'y', long)]
        yes: bool,
        #[command(flatten)]
        common: CommonArgs,
    },
    /// 按歌手下载专辑:歌手名 / 歌手链接 / --mid → 专辑列表多选 → 逐张下载
    Artist {
        /// 歌手名或歌手链接(如 https://y.qq.com/n/ryqq/singer/0025NhlN2yWrP4)
        #[arg(required_unless_present = "mid", conflicts_with = "mid")]
        query: Option<String>,
        /// 直接指定歌手:QQ 为 14 位 singermid,网易为数字 id
        #[arg(long, value_name = "MID")]
        mid: Option<String>,
        /// 只列出这些类型的专辑(可多个,逗号分隔)
        #[arg(
            short = 't',
            long = "type",
            value_enum,
            value_delimiter = ',',
            value_name = "TYPE"
        )]
        kinds: Vec<AlbumKind>,
        /// 专辑排序
        #[arg(long, value_enum, default_value_t = AlbumOrder::New)]
        order: AlbumOrder,
        /// 只取前 N 张专辑(在类型过滤之后)
        #[arg(short = 'n', long, value_parser = clap::value_parser!(u32).range(1..))]
        num: Option<u32>,
        /// 只输出专辑列表 JSON,不交互、不下载
        #[arg(long)]
        json: bool,
        /// 不弹出选择,下载列表中的全部专辑
        #[arg(short = 'y', long)]
        yes: bool,
        #[command(flatten)]
        common: CommonArgs,
    },
    /// 检查各音源的搜索、歌词与每个取链接口是否可用
    Doctor {
        /// 要检查的音源(逗号分隔,如 -s qq,163)[默认: 与其他命令相同,即 [defaults] source,未配置为 qq]
        #[arg(
            short = 's',
            long,
            value_enum,
            value_delimiter = ',',
            value_name = "SOURCE"
        )]
        source: Vec<SourceKind>,
    },
    /// 输出 shell 补全脚本,如 `uta completions zsh > ~/.zfunc/_uta`
    Completions {
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// 配置文件相关
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// 按歌曲 id / 歌曲链接直接下载(非交互)
    Get {
        /// 一个或多个歌曲 id 或链接:QQ 为 songmid / 数字 songid,网易为数字 id(需 -s netease);
        /// QQ / 网易链接(含分享短链)自动识别音源
        #[arg(required = true, value_name = "SONG")]
        mids: Vec<String>,
        #[command(flatten)]
        common: CommonArgs,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// 显示配置文件路径
    Path,
    /// 用示例内容生成配置文件
    Init {
        /// 已存在时覆盖
        #[arg(long)]
        force: bool,
    },
}

fn client_builder() -> reqwest::ClientBuilder {
    reqwest::Client::builder()
        .user_agent(USER_AGENT)
        .connect_timeout(Duration::from_secs(5))
}

/// 接口请求:连接 5s、总计 15s。
fn build_api_client() -> Result<reqwest::Client> {
    client_builder()
        .timeout(Duration::from_secs(15))
        .build()
        .context("初始化 HTTP 客户端失败")
}

/// 下载:单首可达 200MB,总时长无法设上限;改为连接 5s + 读取空闲 15s,仍不会无限挂起。
fn build_download_client() -> Result<reqwest::Client> {
    client_builder()
        .read_timeout(Duration::from_secs(15))
        .build()
        .context("初始化下载客户端失败")
}

fn init_logging(verbose: u8) {
    let default = match verbose {
        // lofty 对部分 MP3 会打出无害的 "ID3v2 tag preceded by junk data" 警告
        0 => "warn,lofty=error",
        1 => "uta=debug",
        _ => "uta=trace,reqwest=debug",
    };
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_target(false)
        .init();
}

fn fmt_duration(secs: u64) -> String {
    format!("{}:{:02}", secs / 60, secs % 60)
}

fn fmt_size(bytes: u64) -> String {
    if bytes == 0 {
        "未知".into()
    } else {
        format!("{:.2} MB", bytes as f64 / 1024.0 / 1024.0)
    }
}

fn print_table(items: &[Item]) {
    let mut table = Table::new();
    table
        .load_style(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header([
            "#", "歌名", "歌手", "专辑", "时长", "格式", "大小", "品质", "来源",
        ]);
    for (i, it) in items.iter().enumerate() {
        table.add_row([
            (i + 1).to_string(),
            it.song.title.clone(),
            it.song.singer_text(),
            it.song.album.clone(),
            fmt_duration(it.song.interval),
            it.resolved.probe.ext.clone(),
            fmt_size(it.resolved.probe.size),
            it.resolved.quality.clone(),
            source_text(it),
        ]);
    }
    println!("{table}");
}

impl CommonArgs {
    /// 优先级:命令行 > 配置文件 `[defaults]` > 内置默认。
    fn settings(&self, d: &Defaults) -> Result<Settings> {
        let max_level = self.max_quality.or(d.max_quality).unwrap_or(Level::Master);
        if self.lossless && max_level < Level::Sq {
            anyhow::bail!(
                "--lossless 与最高音质 {max_level} 冲突:无损至少需要 sq(可用 -q sq 覆盖配置)"
            );
        }
        let output = match (&self.output, &d.output) {
            (Some(p), _) => p.clone(),
            (None, Some(p)) => expand_home(p),
            (None, None) => PathBuf::from("."),
        };
        Ok(Settings {
            sources: {
                let list = if self.source.is_empty() {
                    d.source.clone().unwrap_or_default()
                } else {
                    self.source.clone()
                };
                let mut seen = std::collections::HashSet::new();
                let list: Vec<SourceKind> = list.into_iter().filter(|k| seen.insert(*k)).collect();
                if list.is_empty() {
                    vec![SourceKind::default()]
                } else {
                    list
                }
            },
            fallback: !self.no_fallback,
            opts: ResolveOptions {
                lossless_only: self.lossless,
                max_level,
            },
            output,
            jobs: self.jobs.or(d.jobs).unwrap_or(8) as usize,
            download_jobs: self.download_jobs.or(d.download_jobs).unwrap_or(4) as usize,
        })
    }
}

impl Settings {
    /// 主音源(非 search 命令只用它)。
    fn source(&self) -> SourceKind {
        self.sources[0]
    }

    /// 只有 search 支持多个音源。
    fn single(self, command: &str) -> Result<Settings> {
        if self.sources.len() > 1 {
            anyhow::bail!("{command} 只支持一个音源,-s 只能给一个值(多音源仅用于 search)");
        }
        Ok(self)
    }
}

/// 并发解析,保持输入顺序;返回解析成功的条目。
async fn resolve_all(
    sources: &Sources,
    songs: Vec<Song>,
    opts: ResolveOptions,
    jobs: usize,
    fallback: bool,
) -> Vec<Item> {
    let found = songs.len();
    eprintln!("正在解析 {found} 首的直链(并发 {jobs})…");
    let mut resolved: Vec<(usize, Item)> = stream::iter(songs.into_iter().enumerate())
        .map(|(i, song)| async move {
            let r = match sources.resolve(&song, opts).await {
                None if fallback => sources.resolve_fallback(&song, opts).await,
                r => r,
            };
            r.map(|r| (i, Item::new(song, r)))
        })
        .buffer_unordered(jobs)
        .filter_map(|x| async move { x })
        .collect()
        .await;
    resolved.sort_by_key(|(i, _)| *i);
    let filled = resolved
        .iter()
        .filter(|(_, it)| it.resolved.fallback.is_some())
        .count();
    if filled > 0 {
        eprintln!(
            "{filled} 首在本音源拿不到,已从其他音源补上链接(来源列标「补」;--no-fallback 可关闭)"
        );
    }
    let dropped = found - resolved.len();
    if dropped > 0 {
        let why = if opts.lossless_only {
            "拿不到无损"
        } else {
            "无可用直链"
        };
        eprintln!("{dropped} 首{why},已忽略");
    }
    resolved.into_iter().map(|(_, it)| it).collect()
}

/// 来源列:音源·接口;从其他音源补的链接标「补」。
fn source_text(it: &Item) -> String {
    match it.resolved.fallback {
        Some(k) => format!("{}·{}(补)", k.label(), it.resolved.via),
        None => format!("{}·{}", it.song.source.label(), it.resolved.via),
    }
}

fn select_label(i: usize, it: &Item) -> String {
    format!(
        "{:>2}. {} - {} 《{}》 [{} {} {}]",
        i + 1,
        it.song.title,
        it.song.singer_text(),
        it.song.album,
        it.resolved.probe.ext,
        fmt_size(it.resolved.probe.size),
        it.resolved.quality,
    )
}

/// 交互多选;返回选中的下标。用户取消时返回空。
fn choose(items: &[Item], all_selected: bool) -> Result<Vec<usize>> {
    let labels: Vec<String> = items
        .iter()
        .enumerate()
        .map(|(i, it)| select_label(i, it))
        .collect();
    let mut prompt = MultiSelect::new("选择要下载的歌曲:", labels)
        .with_page_size(15)
        .with_help_message("↑↓ 移动,空格 选择,→ 全选,← 全不选,输入可过滤,回车 确认,Esc 取消");
    if all_selected {
        prompt = prompt.with_all_selected_by_default();
    }
    let picked = prompt.raw_prompt();
    match picked {
        Ok(opts) => Ok(opts.into_iter().map(|o| o.index).collect()),
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(vec![]),
        Err(e) => Err(e).context("交互选择失败"),
    }
}

/// 下载并打印汇总;有失败时返回 false。Ctrl-C 时保留未完成的 `.part`(可续传)并以 130 退出。
async fn download_and_report(
    sources: &Sources,
    items: &[Item],
    settings: &Settings,
) -> Result<bool> {
    let client = build_download_client()?;
    let download = download_all(
        &client,
        sources,
        items,
        &settings.output,
        settings.download_jobs,
    );
    let outcomes = tokio::select! {
        r = download => r?,
        _ = tokio::signal::ctrl_c() => {
            // select 结束时下载 future 已被丢弃,文件句柄随之关闭;.part 保留用于续传
            let kept = plan_paths(items, &settings.output)
                .iter()
                .filter(|p| part_path(p).exists())
                .count();
            if kept > 0 {
                eprintln!("\n已取消。{kept} 个未完成的文件已保留(.part),重新运行同一命令会自动续传");
            } else {
                eprintln!("\n已取消");
            }
            std::process::exit(130);
        }
    };
    let (mut ok, mut skipped, mut failed) = (0, 0, 0);
    for o in &outcomes {
        match o {
            Outcome::Downloaded { .. } => ok += 1,
            Outcome::Skipped => skipped += 1,
            Outcome::Failed(_) => failed += 1,
        }
    }
    eprintln!(
        "完成:成功 {ok},跳过 {skipped},失败 {failed}。保存位置:{}",
        display_dir(&settings.output)
    );
    Ok(failed == 0)
}

fn display_dir(p: &Path) -> String {
    let full = std::fs::canonicalize(p)
        .unwrap_or_else(|_| p.to_path_buf())
        .display()
        .to_string();
    // Windows 的 canonicalize 返回 `\\?\C:\...` 形式,展示时去掉前缀
    strip_verbatim(&full).to_string()
}

fn strip_verbatim(s: &str) -> &str {
    s.strip_prefix(r"\\?\UNC\")
        .map_or_else(|| s.strip_prefix(r"\\?\").unwrap_or(s), |_| s)
}

async fn cmd_search(
    sources: &Sources,
    keyword: &str,
    num: usize,
    json: bool,
    no_merge: bool,
    settings: &Settings,
) -> Result<bool> {
    let opts = settings.opts;
    let kinds = &settings.sources;
    // 多个音源并发搜索;某个音源失败只提示,不影响其他音源
    let results =
        futures::future::join_all(kinds.iter().map(|&k| sources.search(k, keyword, num))).await;
    let mut lists = Vec::new();
    let mut counts = Vec::new();
    let mut last_err = None;
    for (&k, r) in kinds.iter().zip(results) {
        match r {
            Ok(v) => {
                counts.push(format!("{} {}", k.label(), v.len()));
                lists.push(v);
            }
            Err(e) if kinds.len() > 1 => {
                eprintln!("✘ {}搜索失败:{e:#}", k.label());
                last_err = Some(e);
            }
            Err(e) => return Err(e),
        }
    }
    let songs = merge::interleave(lists);
    if songs.is_empty() {
        if let Some(e) = last_err {
            return Err(e);
        }
        anyhow::bail!("没有搜索到“{keyword}”相关的歌曲");
    }
    if kinds.len() > 1 {
        eprintln!("搜索到 {} 首({})", songs.len(), counts.join(","));
    } else {
        eprintln!("搜索到 {} 首", songs.len());
    }
    // 多音源搜索已经互补,不再额外补链
    let fallback = settings.fallback && kinds.len() == 1;
    let mut items = resolve_all(sources, songs, opts, settings.jobs, fallback).await;
    if kinds.len() > 1 && !no_merge {
        let (kept, merged) = merge::dedupe_across_sources(items);
        items = kept;
        if merged > 0 {
            eprintln!("{merged} 首在多个音源都有,已保留音质更好的一份(--no-merge 可全部列出)");
        }
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&items)?);
        return Ok(true);
    }
    if items.is_empty() {
        eprintln!(
            "没有可用的结果{}",
            if opts.lossless_only {
                "(--lossless)"
            } else {
                ""
            }
        );
        return Ok(true);
    }
    print_table(&items);
    if !interactive() {
        eprintln!("非交互环境,无法多选。可用 --json 输出结果,或用 `uta get <mid>...` 下载。");
        return Ok(true);
    }
    let picked = choose(&items, false)?;
    if picked.is_empty() {
        eprintln!("未选择任何歌曲");
        return Ok(true);
    }
    let selected: Vec<Item> = picked.into_iter().map(|i| items[i].clone()).collect();
    download_and_report(sources, &selected, settings).await
}

fn interactive() -> bool {
    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
}

/// 歌单 / 专辑共用:解析 → JSON 或表格 → 选择(默认全选)→ 下载到 `<输出目录>/<子目录>/`。
async fn download_collection(
    sources: &Sources,
    mut songs: Vec<Song>,
    subdir: &str,
    num: Option<u32>,
    json: bool,
    yes: bool,
    settings: &Settings,
) -> Result<bool> {
    if let Some(n) = num {
        songs.truncate(n as usize);
    }
    let items = resolve_all(
        sources,
        songs,
        settings.opts,
        settings.jobs,
        settings.fallback,
    )
    .await;
    if json {
        println!("{}", serde_json::to_string_pretty(&items)?);
        return Ok(true);
    }
    if items.is_empty() {
        eprintln!("没有可用的结果");
        return Ok(false);
    }
    print_table(&items);
    let selected: Vec<Item> = if yes || !interactive() {
        items
    } else {
        let picked = choose(&items, true)?;
        if picked.is_empty() {
            eprintln!("未选择任何歌曲");
            return Ok(true);
        }
        picked.into_iter().map(|i| items[i].clone()).collect()
    };
    let settings = Settings {
        output: settings.output.join(download::sanitize_filename(subdir)),
        ..settings.clone()
    };
    download_and_report(sources, &selected, &settings).await
}

async fn cmd_playlist(
    sources: &Sources,
    input: &str,
    num: Option<u32>,
    json: bool,
    yes: bool,
    settings: &Settings,
) -> Result<bool> {
    let kind = source::detect(input).unwrap_or(settings.source());
    let (id, name, songs) = sources.playlist(kind, input).await?;
    let total = songs.len();
    eprintln!("{}歌单《{name}》({id})共 {total} 首", kind.label());
    if total == 0 {
        anyhow::bail!("歌单为空");
    }
    // 与 Python 版一致:歌单下载到以歌单名命名的子目录
    download_collection(sources, songs, &name, num, json, yes, settings).await
}

fn print_album_table(hits: &[AlbumHit]) {
    let mut table = Table::new();
    table
        .load_style(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header(["#", "专辑", "歌手", "曲目数", "发行日期", "id"]);
    for (i, h) in hits.iter().enumerate() {
        table.add_row([
            (i + 1).to_string(),
            h.name.clone(),
            h.singer.clone(),
            h.song_num.to_string(),
            h.publish_date.clone(),
            h.id.clone(),
        ]);
    }
    println!("{table}");
}

/// 单选一张专辑;取消返回 None。
fn choose_album(hits: &[AlbumHit]) -> Result<Option<usize>> {
    let labels: Vec<String> = hits
        .iter()
        .enumerate()
        .map(|(i, h)| {
            format!(
                "{:>2}. {} - {}({} 首,{})",
                i + 1,
                h.name,
                h.singer,
                h.song_num,
                h.publish_date
            )
        })
        .collect();
    match Select::new("选择专辑:", labels)
        .with_page_size(15)
        .with_help_message("↑↓ 移动,输入可过滤,回车 确认,Esc 取消")
        .raw_prompt()
    {
        Ok(o) => Ok(Some(o.index)),
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(None),
        Err(e) => Err(e).context("交互选择失败"),
    }
}

async fn cmd_album(
    sources: &Sources,
    query: Option<&str>,
    mid: Option<&str>,
    num: Option<u32>,
    json: bool,
    yes: bool,
    settings: &Settings,
) -> Result<bool> {
    let kind = query.and_then(source::detect).unwrap_or(settings.source());
    let key = match (mid, query) {
        (Some(m), _) => source::parse_album(kind, m).with_context(|| match kind {
            SourceKind::Qq => format!("--mid 需要 14 位 albummid 或数字 albumID,收到:{m}"),
            SourceKind::Netease => format!("--mid 需要网易云数字专辑 id,收到:{m}"),
        })?,
        (None, Some(q)) => match source::parse_album(kind, q).filter(|_| q.contains("://")) {
            Some(k) => k,
            None => {
                let hits = sources.search_albums(kind, q, 10).await?;
                if hits.is_empty() {
                    anyhow::bail!("没有搜索到“{q}”相关的专辑");
                }
                if json {
                    println!("{}", serde_json::to_string_pretty(&hits)?);
                    return Ok(true);
                }
                print_album_table(&hits);
                let idx = if yes {
                    eprintln!("-y:选择第 1 个结果《{}》", hits[0].name);
                    0
                } else if !interactive() {
                    eprintln!(
                        "非交互环境,无法选择专辑。可用 `uta album{} --mid <id>`、专辑链接,或加 -y 选第 1 个结果。",
                        source_flag(kind)
                    );
                    return Ok(true);
                } else {
                    match choose_album(&hits)? {
                        Some(i) => i,
                        None => {
                            eprintln!("未选择专辑");
                            return Ok(true);
                        }
                    }
                };
                source::AlbumKey::from_id(kind, &hits[idx].id)
            }
        },
        (None, None) => unreachable!("clap 保证至少有一个"),
    };
    let album = sources.album(&key).await?;
    print_album_header(&album);
    let subdir = album.dir_name();
    download_collection(sources, album.songs, &subdir, num, json, yes, settings).await
}

/// 提示命令里的音源参数(默认音源 QQ 不需要写)。
fn source_flag(kind: SourceKind) -> String {
    match kind {
        SourceKind::Qq => String::new(),
        k => format!(" -s {k}"),
    }
}

fn print_album_header(album: &model::Album) {
    let date = if album.publish_date.is_empty() {
        String::new()
    } else {
        format!(",{}", album.publish_date)
    };
    eprintln!(
        "专辑《{}》 - {}({}{date})共 {} 首",
        album.name,
        album.singers.join(", "),
        album.id,
        album.songs.len()
    );
}

/// 关键词搜索歌手:名字完全一致则直接用;否则交互单选,-y / --json / 非交互时取第 1 个。
async fn pick_singer(
    sources: &Sources,
    kind: SourceKind,
    keyword: &str,
    auto: bool,
) -> Result<Option<SingerHit>> {
    let hits = sources.search_singers(kind, keyword, 10).await?;
    if hits.is_empty() {
        anyhow::bail!("没有搜索到“{keyword}”相关的歌手");
    }
    if let Some(h) = model::exact_match(&hits, keyword) {
        return Ok(Some(h.clone()));
    }
    if auto || !interactive() {
        eprintln!("没有同名歌手,选择第 1 个结果:{}", hits[0].name);
        return Ok(Some(hits[0].clone()));
    }
    let labels: Vec<String> = hits
        .iter()
        .map(|h| format!("{}(专辑 {},歌曲 {})", h.name, h.album_num, h.song_num))
        .collect();
    match Select::new("选择歌手:", labels)
        .with_page_size(15)
        .with_help_message("↑↓ 移动,输入可过滤,回车 确认,Esc 取消")
        .raw_prompt()
    {
        Ok(o) => Ok(Some(hits[o.index].clone())),
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(None),
        Err(e) => Err(e).context("交互选择失败"),
    }
}

fn print_artist_albums(albums: &[ArtistAlbum]) {
    let mut table = Table::new();
    table
        .load_style(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header(["#", "发行日期", "类型", "专辑", "歌手", "曲目数", "id"]);
    for (i, a) in albums.iter().enumerate() {
        table.add_row([
            (i + 1).to_string(),
            a.publish_date.clone(),
            a.album_type.clone(),
            a.name.clone(),
            a.singer.clone(),
            a.song_num.to_string(),
            a.id.clone(),
        ]);
    }
    println!("{table}");
}

/// 多选专辑(默认不选,避免误下整个歌手);取消返回空。
fn choose_albums(albums: &[ArtistAlbum]) -> Result<Vec<usize>> {
    let labels: Vec<String> = albums
        .iter()
        .enumerate()
        .map(|(i, a)| {
            format!(
                "{:>3}. {} 《{}》 [{},{} 首]",
                i + 1,
                a.year(),
                a.name,
                a.album_type,
                a.song_num
            )
        })
        .collect();
    match MultiSelect::new("选择要下载的专辑:", labels)
        .with_page_size(15)
        .with_help_message("↑↓ 移动,空格 选择,→ 全选,← 全不选,输入可过滤,回车 确认,Esc 取消")
        .raw_prompt()
    {
        Ok(opts) => Ok(opts.into_iter().map(|o| o.index).collect()),
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(vec![]),
        Err(e) => Err(e).context("交互选择失败"),
    }
}

/// 按类型过滤(空表示不过滤)后截取前 N 张。
fn filter_albums(
    mut albums: Vec<ArtistAlbum>,
    kinds: &[AlbumKind],
    num: Option<u32>,
) -> Vec<ArtistAlbum> {
    if !kinds.is_empty() {
        albums.retain(|a| kinds.contains(&a.kind));
    }
    if let Some(n) = num {
        albums.truncate(n as usize);
    }
    albums
}

struct ArtistArgs<'a> {
    query: Option<&'a str>,
    mid: Option<&'a str>,
    kinds: &'a [AlbumKind],
    order: AlbumOrder,
    num: Option<u32>,
    json: bool,
    yes: bool,
}

async fn cmd_artist(sources: &Sources, a: ArtistArgs<'_>, settings: &Settings) -> Result<bool> {
    let kind = a
        .query
        .and_then(source::detect)
        .unwrap_or(settings.source());
    let (singer_mid, singer_name) = match (a.mid, a.query) {
        (Some(m), _) => (
            source::parse_singer(kind, m).with_context(|| match kind {
                SourceKind::Qq => format!("--mid 需要 14 位 singermid,收到:{m}"),
                SourceKind::Netease => format!("--mid 需要网易云数字歌手 id,收到:{m}"),
            })?,
            None,
        ),
        (None, Some(q)) => match source::parse_singer(kind, q).filter(|_| q.contains("://")) {
            Some(m) => (m, None),
            None => match pick_singer(sources, kind, q, a.yes || a.json).await? {
                Some(h) => {
                    eprintln!(
                        "歌手:{}({},专辑 {},歌曲 {})",
                        h.name, h.id, h.album_num, h.song_num
                    );
                    (h.id, Some(h.name))
                }
                None => {
                    eprintln!("未选择歌手");
                    return Ok(true);
                }
            },
        },
        (None, None) => unreachable!("clap 保证至少有一个"),
    };
    let all = sources.artist_albums(kind, &singer_mid, a.order).await?;
    let total = all.len();
    let singer_name = singer_name.or_else(|| model::main_singer(&all));
    let albums = filter_albums(all, a.kinds, a.num);
    if a.json {
        println!("{}", serde_json::to_string_pretty(&albums)?);
        return Ok(true);
    }
    let who = singer_name.unwrap_or(singer_mid);
    if albums.is_empty() {
        anyhow::bail!("{who} 共 {total} 张专辑,没有符合 --type 的");
    }
    eprintln!("{who} 共 {total} 张专辑,列出 {} 张", albums.len());
    print_artist_albums(&albums);
    let picked: Vec<usize> = if a.yes {
        (0..albums.len()).collect()
    } else if !interactive() {
        eprintln!(
            "非交互环境,无法选择专辑。可加 -y 下载全部(建议配合 --type / -n 缩小范围),或用 `uta album{} --mid <id>` 下载单张。",
            source_flag(kind)
        );
        return Ok(true);
    } else {
        choose_albums(&albums)?
    };
    if picked.is_empty() {
        eprintln!("未选择任何专辑");
        return Ok(true);
    }
    let n = picked.len();
    let mut failed = Vec::new();
    for (k, i) in picked.into_iter().enumerate() {
        let hit = &albums[i];
        eprintln!("\n[{}/{n}] 《{}》", k + 1, hit.name);
        let r = async {
            let album = sources
                .album(&source::AlbumKey::from_id(kind, &hit.id))
                .await?;
            print_album_header(&album);
            let subdir = album.dir_name();
            download_collection(sources, album.songs, &subdir, None, false, true, settings).await
        }
        .await;
        match r {
            Ok(true) => {}
            Ok(false) => failed.push(hit.name.clone()),
            Err(e) => {
                eprintln!("✘ 《{}》:{e:#}", hit.name);
                failed.push(hit.name.clone());
            }
        }
    }
    if failed.is_empty() {
        eprintln!("\n全部 {n} 张专辑完成");
        Ok(true)
    } else {
        eprintln!(
            "\n{n} 张专辑中 {} 张有失败:{}",
            failed.len(),
            failed
                .iter()
                .map(|f| format!("《{f}》"))
                .collect::<Vec<_>>()
                .join("、")
        );
        Ok(false)
    }
}

async fn cmd_get(sources: &Sources, mids: &[String], settings: &Settings) -> Result<bool> {
    let opts = settings.opts;
    let mut seen = std::collections::HashSet::new();
    let mids: Vec<&String> = mids.iter().filter(|m| seen.insert(m.trim())).collect();
    let details: Vec<(usize, Result<Song>)> = stream::iter(mids.iter().enumerate())
        .map(|(i, input)| async move {
            let kind = source::detect(input).unwrap_or(settings.source());
            let r = sources.song(kind, input).await;
            // 纯数字在 QQ 是 songid,用户想要的可能是网易云 id
            let numeric = input.trim().bytes().all(|b| b.is_ascii_digit());
            let r = match r {
                Err(e) if kind == SourceKind::Qq && numeric => {
                    Err(anyhow::anyhow!("{e:#}(网易云的歌曲 id 请加 -s netease)"))
                }
                r => r,
            };
            (i, r)
        })
        .buffer_unordered(settings.jobs)
        .collect()
        .await;
    let mut details = details;
    details.sort_by_key(|(i, _)| *i);
    let mut all_ok = true;
    let mut songs = Vec::new();
    // 同一首歌可能以 mid、songid、链接等不同形式重复给出
    let mut seen = std::collections::HashSet::new();
    for (_, d) in details {
        match d {
            Ok(s) if !seen.insert((s.source, s.id.clone())) => {}
            Ok(s) => songs.push(s),
            Err(e) => {
                all_ok = false;
                eprintln!("✘ {e:#}");
            }
        }
    }
    if songs.is_empty() {
        anyhow::bail!("没有可下载的歌曲");
    }
    let wanted = songs.len();
    let items = resolve_all(sources, songs, opts, settings.jobs, settings.fallback).await;
    if items.len() < wanted {
        all_ok = false;
    }
    if items.is_empty() {
        return Ok(false);
    }
    print_table(&items);
    Ok(download_and_report(sources, &items, settings).await? && all_ok)
}

fn cmd_config(action: &ConfigAction, explicit: Option<&Path>) -> Result<bool> {
    let path = match explicit {
        Some(p) => p.to_path_buf(),
        None => config::default_path().context("无法确定配置目录")?,
    };
    match action {
        ConfigAction::Path => {
            let state = if path.exists() {
                "已存在"
            } else {
                "不存在"
            };
            println!("{}", path.display());
            eprintln!("({state})");
        }
        ConfigAction::Init { force } => {
            if path.exists() && !force {
                anyhow::bail!("{} 已存在,如需覆盖请加 --force", path.display());
            }
            if let Some(dir) = path.parent() {
                std::fs::create_dir_all(dir)
                    .with_context(|| format!("无法创建目录 {}", dir.display()))?;
            }
            std::fs::write(&path, include_str!("../config.example.toml"))
                .with_context(|| format!("无法写入 {}", path.display()))?;
            eprintln!("已生成 {},按需修改 [defaults] 等配置", path.display());
        }
    }
    Ok(true)
}

/// 网络类错误附加一句可操作的提示。
fn error_hint(e: &anyhow::Error) -> Option<&'static str> {
    e.chain().find_map(|c| {
        let re = c.downcast_ref::<reqwest::Error>()?;
        if re.is_timeout() {
            Some("网络请求超时,请检查网络或代理设置(HTTPS_PROXY 等环境变量)")
        } else if re.is_connect() {
            Some("无法连接服务器,请检查网络或代理设置(HTTPS_PROXY 等环境变量)")
        } else {
            None
        }
    })
}

async fn run(cli: Cli) -> Result<bool> {
    if let Command::Config { action } = &cli.command {
        return cmd_config(action, cli.config.as_deref());
    }
    if let Command::Completions { shell } = &cli.command {
        use clap::CommandFactory;
        clap_complete::generate(*shell, &mut Cli::command(), "uta", &mut std::io::stdout());
        return Ok(true);
    }
    let config = Config::load(cli.config.as_deref())?;
    if !config.vkeys.enabled() && !config.tang.enabled() && !config.netease.any_enabled() {
        eprintln!(
            "提示:未配置第三方接口(见 config.example.toml),只能使用官方接口,通常拿不到无损。"
        );
    }
    let defaults = config.defaults.clone();
    let sources = Sources::new(build_api_client()?, config);
    match &cli.command {
        Command::Search {
            keyword,
            num,
            json,
            no_merge,
            common,
        } => {
            let settings = common.settings(&defaults)?;
            cmd_search(
                &sources,
                keyword,
                *num as usize,
                *json,
                *no_merge,
                &settings,
            )
            .await
        }
        Command::Get { mids, common } => {
            let settings = common.settings(&defaults)?.single("get")?;
            cmd_get(&sources, mids, &settings).await
        }
        Command::Playlist {
            playlist,
            num,
            json,
            yes,
            common,
        } => {
            let settings = common.settings(&defaults)?.single("playlist")?;
            cmd_playlist(&sources, playlist, *num, *json, *yes, &settings).await
        }
        Command::Album {
            query,
            mid,
            num,
            json,
            yes,
            common,
        } => {
            let settings = common.settings(&defaults)?.single("album")?;
            cmd_album(
                &sources,
                query.as_deref(),
                mid.as_deref(),
                *num,
                *json,
                *yes,
                &settings,
            )
            .await
        }
        Command::Artist {
            query,
            mid,
            kinds,
            order,
            num,
            json,
            yes,
            common,
        } => {
            let settings = common.settings(&defaults)?.single("artist")?;
            let args = ArtistArgs {
                query: query.as_deref(),
                mid: mid.as_deref(),
                kinds,
                order: *order,
                num: *num,
                json: *json,
                yes: *yes,
            };
            cmd_artist(&sources, args, &settings).await
        }
        Command::Doctor { source } => {
            // 未指定时与其他命令一致:配置的默认音源,未配置为 QQ
            let list = if source.is_empty() {
                defaults.source.clone().unwrap_or_default()
            } else {
                source.clone()
            };
            let mut seen = std::collections::HashSet::new();
            let mut kinds: Vec<SourceKind> = list.into_iter().filter(|k| seen.insert(*k)).collect();
            if kinds.is_empty() {
                kinds.push(SourceKind::default());
            }
            Ok(doctor::run(&sources, &kinds).await)
        }
        Command::Config { .. } | Command::Completions { .. } => unreachable!("已在前面处理"),
    }
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    init_logging(cli.verbose);
    match run(cli).await {
        Ok(true) => ExitCode::SUCCESS,
        Ok(false) => ExitCode::FAILURE,
        Err(e) => {
            eprintln!("错误:{e:#}");
            if let Some(hint) = error_hint(&e) {
                eprintln!("提示:{hint}");
            }
            ExitCode::FAILURE
        }
    }
}

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

    #[test]
    fn durations_and_sizes() {
        assert_eq!(fmt_duration(226), "3:46");
        assert_eq!(fmt_duration(5), "0:05");
        assert_eq!(fmt_size(0), "未知");
        assert_eq!(fmt_size(26_691_277), "25.45 MB");
    }

    fn get_args(args: &[&str]) -> CommonArgs {
        let mut v = vec!["uta", "get", "m"];
        v.extend(args);
        match Cli::parse_from(v).command {
            Command::Get { common, .. } => common,
            _ => unreachable!(),
        }
    }

    #[test]
    fn artist_cli() {
        let cli = Cli::parse_from([
            "uta",
            "artist",
            "周杰伦",
            "-t",
            "studio,ep",
            "--order",
            "hot",
            "-n",
            "3",
            "-y",
        ]);
        let Command::Artist {
            query,
            kinds,
            order,
            num,
            yes,
            json,
            ..
        } = cli.command
        else {
            panic!("应为 artist");
        };
        assert_eq!(query.as_deref(), Some("周杰伦"));
        assert_eq!(kinds, [AlbumKind::Studio, AlbumKind::Ep]);
        assert_eq!(
            (order, num, yes, json),
            (AlbumOrder::Hot, Some(3), true, false)
        );
        let Command::Artist { kinds, order, .. } =
            Cli::parse_from(["uta", "artist", "--mid", "0025NhlN2yWrP4"]).command
        else {
            panic!("应为 artist");
        };
        assert!(kinds.is_empty());
        assert_eq!(order, AlbumOrder::New);
        assert!(Cli::try_parse_from(["uta", "artist"]).is_err());
        assert!(Cli::try_parse_from(["uta", "artist", "x", "--mid", "y"]).is_err());
        assert!(Cli::try_parse_from(["uta", "artist", "x", "-t", "nope"]).is_err());
    }

    #[test]
    fn album_filter() {
        let a = |kind: AlbumKind| ArtistAlbum {
            id: String::new(),
            name: String::new(),
            singer: String::new(),
            album_type: String::new(),
            kind,
            publish_date: String::new(),
            song_num: 0,
        };
        let list = vec![
            a(AlbumKind::Single),
            a(AlbumKind::Studio),
            a(AlbumKind::Ep),
            a(AlbumKind::Studio),
        ];
        assert_eq!(filter_albums(list.clone(), &[], None).len(), 4);
        let f = filter_albums(list.clone(), &[AlbumKind::Studio, AlbumKind::Ep], Some(2));
        assert_eq!(
            f.iter().map(|x| x.kind).collect::<Vec<_>>(),
            [AlbumKind::Studio, AlbumKind::Ep]
        );
        assert!(filter_albums(list, &[AlbumKind::Live], None).is_empty());
    }

    #[test]
    fn verbatim_prefix() {
        assert_eq!(strip_verbatim(r"\\?\C:\Users\a\Music"), r"C:\Users\a\Music");
        // UNC 路径去掉前缀后语义会变,保持原样
        assert_eq!(strip_verbatim(r"\\?\UNC\srv\share"), r"\\?\UNC\srv\share");
        assert_eq!(strip_verbatim("/home/a/Music"), "/home/a/Music");
    }

    #[test]
    fn completions_for_every_shell() {
        use clap::{CommandFactory, ValueEnum};
        for &shell in clap_complete::Shell::value_variants() {
            let mut out = Vec::new();
            clap_complete::generate(shell, &mut Cli::command(), "uta", &mut out);
            let text = String::from_utf8(out).unwrap();
            // 子命令与音源取值都应出现在补全脚本里
            assert!(
                text.contains("playlist") && text.contains("netease"),
                "{shell:?}"
            );
        }
        assert!(Cli::try_parse_from(["uta", "completions", "zsh"]).is_ok());
        assert!(Cli::try_parse_from(["uta", "completions", "tcsh"]).is_err());
    }

    #[test]
    fn cli_parses() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
        let cli = Cli::parse_from(["uta", "search", "夜曲", "-n", "20", "--lossless", "--json"]);
        let Command::Search {
            num, json, common, ..
        } = cli.command
        else {
            panic!("应为 search");
        };
        assert_eq!((num, json, common.lossless), (20, true, true));
        assert_eq!(
            (common.jobs, common.download_jobs, common.output),
            (None, None, None)
        );

        let cli = Cli::parse_from(["uta", "get", "a", "b", "-o", "/tmp/x", "-J", "2"]);
        let Command::Get { mids, common } = cli.command else {
            panic!("应为 get");
        };
        assert_eq!(mids, ["a", "b"]);
        assert_eq!(common.output, Some(PathBuf::from("/tmp/x")));
        assert_eq!(common.download_jobs, Some(2));
        assert!(Cli::try_parse_from(["uta", "get"]).is_err());
        assert!(Cli::try_parse_from(["uta", "get", "m", "-q", "ultra"]).is_err());

        let cli = Cli::parse_from([
            "uta",
            "playlist",
            "https://y.qq.com/n/ryqq/playlist/1",
            "-n",
            "5",
            "-y",
        ]);
        let Command::Playlist {
            playlist,
            num,
            yes,
            json,
            ..
        } = cli.command
        else {
            panic!("应为 playlist");
        };
        assert_eq!(
            (playlist.as_str(), num, yes, json),
            ("https://y.qq.com/n/ryqq/playlist/1", Some(5), true, false)
        );
        assert!(Cli::try_parse_from(["uta", "playlist", "1", "-n", "0"]).is_err());

        let cli = Cli::parse_from(["uta", "album", "十一月的萧邦", "-y", "-n", "3"]);
        let Command::Album {
            query,
            mid,
            num,
            yes,
            ..
        } = cli.command
        else {
            panic!("应为 album");
        };
        assert_eq!(
            (query.as_deref(), mid, num, yes),
            (Some("十一月的萧邦"), None, Some(3), true)
        );
        assert!(matches!(
            Cli::parse_from(["uta", "album", "--mid", "0024bjiL2aocxT"]).command,
            Command::Album {
                query: None,
                mid: Some(_),
                ..
            }
        ));
        // 关键词与 --mid 二选一,且至少一个
        assert!(Cli::try_parse_from(["uta", "album"]).is_err());
        assert!(Cli::try_parse_from(["uta", "album", "x", "--mid", "y"]).is_err());

        assert!(matches!(
            Cli::parse_from(["uta", "config", "init", "--force"]).command,
            Command::Config {
                action: ConfigAction::Init { force: true }
            }
        ));
    }

    #[test]
    fn settings_builtin_defaults() {
        let s = get_args(&[]).settings(&Defaults::default()).unwrap();
        assert_eq!(s.sources, [SourceKind::Qq]);
        assert_eq!(s.opts.max_level, Level::Master);
        assert!(!s.opts.lossless_only);
        assert_eq!(s.output, PathBuf::from("."));
        assert_eq!((s.jobs, s.download_jobs), (8, 4));
    }

    #[test]
    fn settings_priority_cli_over_config() {
        let d = Defaults {
            source: Some(vec![SourceKind::Netease]),
            output: Some("~/Music".into()),
            max_quality: Some(Level::Sq),
            jobs: Some(4),
            download_jobs: Some(2),
        };
        let s = get_args(&[]).settings(&d).unwrap();
        assert_eq!(s.source(), SourceKind::Netease);
        assert_eq!(
            get_args(&["-s", "qq"]).settings(&d).unwrap().source(),
            SourceKind::Qq
        );
        // 多音源:逗号或重复 -s,去重保序;非 search 命令拒绝多个
        let m = get_args(&["-s", "163,qq", "-s", "netease"])
            .settings(&d)
            .unwrap();
        assert_eq!(m.sources, [SourceKind::Netease, SourceKind::Qq]);
        assert!(m.clone().single("get").is_err());
        assert!(s.clone().single("get").is_ok());
        assert_eq!(s.opts.max_level, Level::Sq);
        assert_eq!(s.output, dirs::home_dir().unwrap().join("Music"));
        assert_eq!((s.jobs, s.download_jobs), (4, 2));

        let s = get_args(&["-q", "hires", "-o", "out", "-j", "16", "-J", "1"])
            .settings(&d)
            .unwrap();
        assert_eq!(s.opts.max_level, Level::Hires);
        assert_eq!(s.output, PathBuf::from("out"));
        assert_eq!((s.jobs, s.download_jobs), (16, 1));
    }

    #[test]
    fn lossless_conflict() {
        let none = Defaults::default();
        let s = get_args(&["-q", "sq", "--lossless"])
            .settings(&none)
            .unwrap();
        assert!(s.opts.lossless_only);
        let err = get_args(&["-q", "hq", "--lossless"])
            .settings(&none)
            .unwrap_err();
        assert!(err.to_string().contains("最高音质 hq"));
        // 配置里的 hq 也会冲突,可用 -q 覆盖
        let d = Defaults {
            max_quality: Some(Level::Hq),
            ..Defaults::default()
        };
        assert!(get_args(&["--lossless"]).settings(&d).is_err());
        assert!(get_args(&["--lossless", "-q", "sq"]).settings(&d).is_ok());
    }
}