audiobook-forge 2.10.0

CLI tool for converting audiobook directories to M4B format with chapters and metadata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
//! CLI command handlers

use crate::cli::commands::{BuildArgs, ConfigCommands, OrganizeArgs, MetadataCommands, MatchArgs};
use crate::core::{Analyzer, BatchProcessor, M4bMerger, Organizer, RetryConfig, Scanner};
use crate::models::{BookCase, Config, AudibleRegion, CurrentMetadata, MetadataSource};
use crate::utils::{ConfigManager, DependencyChecker, AudibleCache, scoring, extraction};
use crate::audio::{AacEncoder, AudibleClient, detect_asin};
use crate::ui::{prompt_match_selection, prompt_manual_metadata, prompt_custom_search, UserChoice};
use anyhow::{Context, Result, bail};
use console::style;
use std::path::PathBuf;
use std::str::FromStr;

/// Resolve which AAC encoder to use based on config (handles backward compatibility)
fn resolve_encoder(config: &Config, cli_override: Option<&str>) -> AacEncoder {
    // CLI argument takes highest priority
    if let Some(encoder_str) = cli_override {
        if let Some(encoder) = AacEncoder::from_str(encoder_str) {
            tracing::info!("Using encoder from CLI argument: {}", encoder.name());
            return encoder;
        } else {
            tracing::warn!("Unknown encoder '{}', falling back to auto-detection", encoder_str);
        }
    }

    // Handle backward compatibility with old use_apple_silicon_encoder field
    if let Some(use_apple_silicon) = config.advanced.use_apple_silicon_encoder {
        let encoder = if use_apple_silicon {
            AacEncoder::AppleSilicon
        } else {
            AacEncoder::Native
        };
        tracing::info!("Using encoder from legacy config: {}", encoder.name());
        return encoder;
    }

    // Use new aac_encoder field
    match config.advanced.aac_encoder.to_lowercase().as_str() {
        "auto" => {
            let encoder = crate::audio::get_encoder();
            tracing::info!("Auto-detected encoder: {}", encoder.name());
            encoder
        }
        encoder_str => {
            if let Some(encoder) = AacEncoder::from_str(encoder_str) {
                tracing::info!("Using configured encoder: {}", encoder.name());
                encoder
            } else {
                tracing::warn!(
                    "Unknown encoder '{}' in config, falling back to auto-detection",
                    encoder_str
                );
                let encoder = crate::audio::get_encoder();
                tracing::info!("Auto-detected encoder: {}", encoder.name());
                encoder
            }
        }
    }
}

/// Try to detect if current directory is an audiobook folder
fn try_detect_current_as_audiobook() -> Result<Option<PathBuf>> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;

    // Safety check: Don't auto-detect from filesystem root
    if current_dir.parent().is_none() {
        return Ok(None);
    }

    // Check for MP3 files in current directory
    let entries = std::fs::read_dir(&current_dir)
        .context("Failed to read current directory")?;

    let mp3_count = entries
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| ext.eq_ignore_ascii_case("mp3") || ext.eq_ignore_ascii_case("m4a"))
                .unwrap_or(false)
        })
        .count();

    // Require at least 1 MP3 file to consider it an audiobook (BookCase A or B)
    if mp3_count >= 1 {
        Ok(Some(current_dir))
    } else {
        Ok(None)
    }
}

/// Check if a directory is itself an audiobook folder
fn is_audiobook_folder(path: &std::path::Path) -> Result<bool> {
    if !path.is_dir() {
        return Ok(false);
    }

    let entries = std::fs::read_dir(path)
        .context("Failed to read directory")?;

    let audio_count = entries
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| {
                    ext.eq_ignore_ascii_case("mp3") ||
                    ext.eq_ignore_ascii_case("m4a") ||
                    ext.eq_ignore_ascii_case("m4b")
                })
                .unwrap_or(false)
        })
        .count();

    Ok(audio_count >= 1)
}

/// Handle the build command
pub async fn handle_build(args: BuildArgs, config: Config) -> Result<()> {
    // Determine root directory (CLI arg > config > auto-detect > error)
    let (root, auto_detected) = if let Some(root_path) = args.root.or(config.directories.source.clone()) {
        // Check if root itself is an audiobook folder
        if is_audiobook_folder(&root_path)? {
            println!(
                "{} Detected audiobook folder (not library): {}",
                style("").cyan(),
                style(root_path.display()).yellow()
            );
            (root_path, true)
        } else {
            (root_path, false)
        }
    } else {
        // Try auto-detecting current directory
        if let Some(current) = try_detect_current_as_audiobook()? {
            println!(
                "{} Auto-detected audiobook folder: {}",
                style("").cyan(),
                style(current.display()).yellow()
            );
            (current, true)
        } else {
            anyhow::bail!(
                "No root directory specified. Use --root, configure directories.source, or run from inside an audiobook folder"
            );
        }
    };

    if !auto_detected {
        println!(
            "{} Scanning audiobooks in: {}",
            style("").cyan(),
            style(root.display()).yellow()
        );
    }

    // Scan for audiobooks
    let scanner = Scanner::from_config(&config);
    let mut book_folders = if auto_detected {
        // Auto-detect mode: treat current dir as single book
        vec![scanner.scan_single_directory(&root)?]
    } else {
        // Normal mode: scan for multiple books
        scanner
            .scan_directory(&root)
            .context("Failed to scan directory")?
    };

    if book_folders.is_empty() {
        println!("{} No audiobooks found", style("").red());
        return Ok(());
    }

    println!(
        "{} Found {} audiobook(s)",
        style("").green(),
        style(book_folders.len()).cyan()
    );

    // Filter by skip_existing if configured
    if config.processing.skip_existing && !args.force {
        book_folders.retain(|b| {
            // Keep if no M4B files OR if it's a mergeable case (E)
            b.m4b_files.is_empty() || b.case == BookCase::E
        });
        println!(
            "{} After filtering existing: {} audiobook(s)",
            style("").cyan(),
            style(book_folders.len()).cyan()
        );
    }

    // Handle --merge-m4b flag: force Case E for multi-M4B folders
    if args.merge_m4b {
        for book in &mut book_folders {
            if book.m4b_files.len() > 1 && book.case == BookCase::C {
                tracing::info!(
                    "Forcing merge for {} (--merge-m4b flag)",
                    book.name
                );
                book.case = BookCase::E;
            }
        }
    }

    if book_folders.is_empty() {
        println!(
            "{} All audiobooks already processed (use --force to reprocess)",
            style("").blue()
        );
        return Ok(());
    }

    // Dry run mode
    if args.dry_run {
        println!("\n{} DRY RUN MODE - No changes will be made\n", style("").blue());
        for book in &book_folders {
            println!(
                "  {} {} ({} files, {:.1} min)",
                style("").cyan(),
                style(&book.name).yellow(),
                book.mp3_files.len(),
                book.get_total_duration() / 60.0
            );
        }
        return Ok(());
    }

    // Analyze all books
    println!("\n{} Analyzing tracks...", style("").cyan());
    let analyzer_workers = args.parallel.unwrap_or(config.processing.parallel_workers);
    let analyzer = Analyzer::with_workers(analyzer_workers as usize)?;

    for book in &mut book_folders {
        analyzer
            .analyze_book_folder(book)
            .await
            .with_context(|| format!("Failed to analyze {}", book.name))?;
    }

    println!("{} Analysis complete", style("").green());

    // Fetch Audible metadata if enabled
    if args.fetch_audible || config.metadata.audible.enabled {
        println!("\n{} Fetching Audible metadata...", style("").cyan());

        let audible_region = args.audible_region
            .as_deref()
            .or(Some(&config.metadata.audible.region))
            .and_then(|r| AudibleRegion::from_str(r).ok())
            .unwrap_or(AudibleRegion::US);

        let retry_config = crate::core::RetryConfig::with_settings(
            config.metadata.audible.api_max_retries as usize,
            std::time::Duration::from_secs(config.metadata.audible.api_retry_delay_secs),
            std::time::Duration::from_secs(config.metadata.audible.api_max_retry_delay_secs),
            2.0,
        );
        let client = AudibleClient::with_config(
            audible_region,
            config.metadata.audible.rate_limit_per_minute,
            retry_config,
        )?;
        let cache = AudibleCache::with_ttl_hours(config.metadata.audible.cache_duration_hours)?;

        for book in &mut book_folders {
            // Try ASIN detection first
            if let Some(asin) = detect_asin(&book.name) {
                tracing::debug!("Detected ASIN {} in folder: {}", asin, book.name);
                book.detected_asin = Some(asin.clone());

                // Try cache first
                match cache.get(&asin).await {
                    Some(cached) => {
                        book.audible_metadata = Some(cached);
                        println!("  {} {} (ASIN: {}, cached)", style("").green(), book.name, asin);
                    }
                    None => {
                        // Fetch from API
                        match client.fetch_by_asin(&asin).await {
                            Ok(metadata) => {
                                // Cache the result
                                let _ = cache.set(&asin, &metadata).await;
                                book.audible_metadata = Some(metadata);
                                println!("  {} {} (ASIN: {})", style("").green(), book.name, asin);

                                // Fetch chapters if enabled
                                if config.metadata.audible.fetch_chapters {
                                    match client.fetch_chapters(&asin).await {
                                        Ok(chapters) => {
                                            tracing::debug!("Fetched {} chapters for ASIN: {}", chapters.len(), asin);
                                        }
                                        Err(e) => {
                                            tracing::debug!("No chapters available for ASIN {}: {:?}", asin, e);
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                tracing::warn!("Failed to fetch metadata for {}: {:?}", book.name, e);
                                println!("  {} {} - fetch failed", style("").yellow(), book.name);
                            }
                        }
                    }
                }
            } else if args.audible_auto_match || config.metadata.audible.auto_match {
                // Try auto-matching by title
                tracing::debug!("Attempting auto-match for: {}", book.name);

                match client.search(Some(&book.name), None).await {
                    Ok(results) if !results.is_empty() => {
                        let asin = &results[0].asin;
                        tracing::debug!("Auto-matched {} to ASIN: {}", book.name, asin);
                        book.detected_asin = Some(asin.clone());

                        // Try cache first
                        match cache.get(asin).await {
                            Some(cached) => {
                                book.audible_metadata = Some(cached);
                                println!("  {} {} (matched: {}, cached)", style("").green(), book.name, asin);
                            }
                            None => {
                                // Fetch from API
                                match client.fetch_by_asin(asin).await {
                                    Ok(metadata) => {
                                        // Cache the result
                                        let _ = cache.set(asin, &metadata).await;
                                        book.audible_metadata = Some(metadata);
                                        println!("  {} {} (matched: {})", style("").green(), book.name, asin);

                                        // Fetch chapters if enabled
                                        if config.metadata.audible.fetch_chapters {
                                            match client.fetch_chapters(asin).await {
                                                Ok(chapters) => {
                                                    tracing::debug!("Fetched {} chapters for ASIN: {}", chapters.len(), asin);
                                                }
                                                Err(e) => {
                                                    tracing::debug!("No chapters available for ASIN {}: {:?}", asin, e);
                                                }
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        tracing::warn!("Failed to fetch metadata after match for {}: {:?}", book.name, e);
                                        println!("  {} {} - fetch failed", style("").yellow(), book.name);
                                    }
                                }
                            }
                        }
                    }
                    Ok(_) => {
                        tracing::debug!("No Audible match found for: {}", book.name);
                        println!("  {} {} - no match found", style("").dim(), book.name);
                    }
                    Err(e) => {
                        tracing::warn!("Search failed for {}: {:?}", book.name, e);
                        println!("  {} {} - search failed", style("").yellow(), book.name);
                    }
                }
            } else {
                tracing::debug!("No ASIN detected and auto-match disabled for: {}", book.name);
            }
        }

        let fetched_count = book_folders.iter().filter(|b| b.audible_metadata.is_some()).count();
        println!("{} Fetched metadata for {}/{} books",
            style("").green(),
            style(fetched_count).cyan(),
            book_folders.len()
        );
    }

    // Determine output directory
    let output_dir = if auto_detected {
        // When auto-detected, default to current directory
        args.out.unwrap_or(root.clone())
    } else {
        // Normal mode: respect config
        args.out.or_else(|| {
            if config.directories.output == "same_as_source" {
                Some(root.clone())
            } else {
                Some(PathBuf::from(&config.directories.output))
            }
        }).context("No output directory specified")?
    };

    // Create batch processor with config settings
    let workers = args.parallel.unwrap_or(config.processing.parallel_workers) as usize;
    let keep_temp = args.keep_temp || config.processing.keep_temp_files;

    // Resolve encoder (handles backward compatibility with legacy config)
    let encoder = resolve_encoder(&config, args.aac_encoder.as_deref());

    // Parse max concurrent encodes from config
    let max_concurrent = if config.performance.max_concurrent_encodes == "auto" {
        num_cpus::get() // Use all CPU cores
    } else {
        config.performance.max_concurrent_encodes
            .parse::<usize>()
            .unwrap_or(num_cpus::get())
            .clamp(1, 16)
    };

    // Parse max concurrent files per book from config
    let max_concurrent_files = if config.performance.max_concurrent_files_per_book == "auto" {
        num_cpus::get()
    } else {
        config.performance.max_concurrent_files_per_book
            .parse::<usize>()
            .unwrap_or(8)
            .clamp(1, 32)
    };

    // Create retry config from settings
    let retry_config = RetryConfig::with_settings(
        config.processing.max_retries as usize,
        std::time::Duration::from_secs(config.processing.retry_delay),
        std::time::Duration::from_secs(30),
        2.0,
    );

    let batch_processor = BatchProcessor::with_options(
        workers,
        keep_temp,
        encoder,
        config.performance.enable_parallel_encoding,
        max_concurrent,
        max_concurrent_files,
        args.quality.clone(),
        retry_config,
    );

    // Separate Case E (M4B merge) from other cases
    let (merge_books, convert_books): (Vec<_>, Vec<_>) = book_folders
        .into_iter()
        .partition(|b| b.case == BookCase::E);

    // Process M4B merges
    if !merge_books.is_empty() {
        println!(
            "\n{} Merging {} M4B audiobook(s)...",
            style("").cyan(),
            style(merge_books.len()).cyan()
        );

        let merger = M4bMerger::with_options(args.keep_temp)?;

        for book in merge_books {
            println!(
                "  {} {} ({} files)",
                style("").cyan(),
                style(&book.name).yellow(),
                book.m4b_files.len()
            );

            match merger.merge_m4b_files(&book, &output_dir).await {
                Ok(output_path) => {
                    println!(
                        "  {} Merged: {}",
                        style("").green(),
                        output_path.display()
                    );
                }
                Err(e) => {
                    println!(
                        "  {} Failed to merge {}: {}",
                        style("").red(),
                        book.name,
                        e
                    );
                }
            }
        }
    }

    // Continue with regular conversion for remaining books
    let book_folders = convert_books;

    // Process batch (regular conversions)
    if !book_folders.is_empty() {
        println!("\n{} Processing {} audiobook(s)...\n", style("").cyan(), book_folders.len());
    }

    let results = batch_processor
        .process_batch(
            book_folders,
            &output_dir,
            &config.quality.chapter_source,
        )
        .await;

    // Print results
    println!();
    let successful = results.iter().filter(|r| r.success).count();
    let failed = results.len() - successful;

    for result in &results {
        if result.success {
            println!(
                "  {} {} ({:.1}s, {})",
                style("").green(),
                style(&result.book_name).yellow(),
                result.processing_time,
                if result.used_copy_mode {
                    "copy mode"
                } else {
                    "transcode"
                }
            );
        } else {
            println!(
                "  {} {} - {}",
                style("").red(),
                style(&result.book_name).yellow(),
                result.error_message.as_deref().unwrap_or("Unknown error")
            );
        }
    }

    println!(
        "\n{} Batch complete: {} successful, {} failed",
        style("").green(),
        style(successful).green(),
        if failed > 0 {
            style(failed).red()
        } else {
            style(failed).dim()
        }
    );

    Ok(())
}

/// Handle the organize command
pub fn handle_organize(args: OrganizeArgs, config: Config) -> Result<()> {
    // Determine root directory
    let root = args
        .root
        .or(config.directories.source.clone())
        .context("No root directory specified. Use --root or configure directories.source")?;

    println!(
        "{} Scanning audiobooks in: {}",
        style("").cyan(),
        style(root.display()).yellow()
    );

    // Scan for audiobooks
    let scanner = Scanner::from_config(&config);
    let book_folders = scanner
        .scan_directory(&root)
        .context("Failed to scan directory")?;

    if book_folders.is_empty() {
        println!("{} No audiobooks found", style("").red());
        return Ok(());
    }

    println!(
        "{} Found {} audiobook(s)",
        style("").green(),
        style(book_folders.len()).cyan()
    );

    // Create organizer
    let organizer = Organizer::with_dry_run(root, &config, args.dry_run);

    // Dry run notice
    if args.dry_run {
        println!("\n{} DRY RUN MODE - No changes will be made\n", style("").blue());
    }

    // Organize books
    let results = organizer.organize_batch(book_folders);

    // Print results
    println!();
    for result in &results {
        let action_str = result.action.description();

        if result.success {
            match result.destination_path {
                Some(ref dest) => {
                    println!(
                        "  {} {}{}",
                        style("").green(),
                        style(&result.book_name).yellow(),
                        style(dest.display()).cyan()
                    );
                }
                None => {
                    println!(
                        "  {} {} ({})",
                        style("").dim(),
                        style(&result.book_name).dim(),
                        style(action_str).dim()
                    );
                }
            }
        } else {
            println!(
                "  {} {} - {}",
                style("").red(),
                style(&result.book_name).yellow(),
                result.error_message.as_deref().unwrap_or("Unknown error")
            );
        }
    }

    let moved = results
        .iter()
        .filter(|r| r.success && r.destination_path.is_some())
        .count();
    let skipped = results.iter().filter(|r| r.destination_path.is_none()).count();
    let failed = results.iter().filter(|r| !r.success).count();

    println!(
        "\n{} Organization complete: {} moved, {} skipped, {} failed",
        style("").green(),
        style(moved).green(),
        style(skipped).dim(),
        if failed > 0 {
            style(failed).red()
        } else {
            style(failed).dim()
        }
    );

    Ok(())
}

/// Handle the config command
pub fn handle_config(command: ConfigCommands) -> Result<()> {
    match command {
        ConfigCommands::Init { force } => {
            let config_path = ConfigManager::default_config_path()?;

            if config_path.exists() && !force {
                println!(
                    "{} Configuration file already exists: {}",
                    style("").red(),
                    style(config_path.display()).yellow()
                );
                println!("Use --force to overwrite");
                return Ok(());
            }

            // Create config directory if needed
            ConfigManager::ensure_config_dir()?;

            // Create default config
            let config = Config::default();
            ConfigManager::save(&config, Some(&config_path))?;

            println!(
                "{} Configuration file created: {}",
                style("").green(),
                style(config_path.display()).yellow()
            );
        }

        ConfigCommands::Show { config: _ } => {
            let config_path = ConfigManager::default_config_path()?;
            let config = ConfigManager::load(&config_path)?;
            let yaml = serde_yaml::to_string(&config)?;
            println!("{}", yaml);
        }

        ConfigCommands::Path => {
            let config_path = ConfigManager::default_config_path()?;
            println!("{}", config_path.display());
        }

        ConfigCommands::Validate { config: _ } => {
            let config_path = ConfigManager::default_config_path()?;
            ConfigManager::load(&config_path)?;
            println!(
                "{} Configuration is valid",
                style("").green()
            );
        }

        ConfigCommands::Edit => {
            let config_path = ConfigManager::default_config_path()?;
            println!("{} Opening editor for: {}", style("").cyan(), style(config_path.display()).yellow());
            // TODO: Implement editor opening
            println!("{} Editor integration not yet implemented", style("").blue());
        }
    }

    Ok(())
}

/// Handle the check command
pub fn handle_check() -> Result<()> {
    println!("{} Checking system dependencies...\n", style("").cyan());

    let results = vec![
        ("FFmpeg", DependencyChecker::check_ffmpeg().found),
        ("AtomicParsley", DependencyChecker::check_atomic_parsley().found),
        ("MP4Box", DependencyChecker::check_mp4box().found),
    ];

    let all_found = results.iter().all(|(_, found)| *found);

    for (tool, found) in &results {
        if *found {
            println!("  {} {}", style("").green(), style(tool).cyan());

            // Show encoder information for FFmpeg
            if *tool == "FFmpeg" {
                let available_encoders = DependencyChecker::get_available_encoders();
                let selected_encoder = DependencyChecker::get_selected_encoder();

                if !available_encoders.is_empty() {
                    print!("    AAC Encoders: ");
                    for (i, encoder) in available_encoders.iter().enumerate() {
                        if i > 0 {
                            print!(", ");
                        }
                        if *encoder == selected_encoder {
                            print!("{} {}", style(encoder).green(), style("(selected)").dim());
                        } else {
                            print!("{}", style(encoder).dim());
                        }
                    }
                    println!();
                }
            }
        } else {
            println!("  {} {} (not found)", style("").red(), style(tool).yellow());
        }
    }

    println!();
    if all_found {
        println!("{} All dependencies found", style("").green());
    } else {
        println!("{} Some dependencies are missing", style("").red());
        println!("\nInstall missing dependencies:");
        println!("  macOS:   brew install ffmpeg atomicparsley gpac");
        println!("  Ubuntu:  apt install ffmpeg atomicparsley gpac");
    }

    Ok(())
}

/// Handle the metadata command
pub async fn handle_metadata(command: MetadataCommands, config: Config) -> Result<()> {
    match command {
        MetadataCommands::Fetch { asin, title, author, region, output } => {
            println!("{} Fetching Audible metadata...", style("").cyan());

            // Parse region
            let audible_region = AudibleRegion::from_str(&region)
                .unwrap_or(AudibleRegion::US);

            // Create client and cache
            let client = AudibleClient::with_rate_limit(
                audible_region,
                config.metadata.audible.rate_limit_per_minute
            )?;
            let cache = AudibleCache::with_ttl_hours(config.metadata.audible.cache_duration_hours)?;

            // Fetch metadata
            let metadata = if let Some(asin_val) = asin {
                // Direct ASIN lookup
                println!("  {} Looking up ASIN: {}", style("").cyan(), asin_val);

                // Try cache first
                if let Some(cached) = cache.get(&asin_val).await {
                    println!("  {} Using cached metadata", style("").green());
                    cached
                } else {
                    let fetched = client.fetch_by_asin(&asin_val).await?;
                    cache.set(&asin_val, &fetched).await?;
                    fetched
                }
            } else if title.is_some() || author.is_some() {
                // Search by title/author
                println!("  {} Searching: title={:?}, author={:?}",
                    style("").cyan(), title, author);

                let results = client.search(title.as_deref(), author.as_deref()).await?;

                if results.is_empty() {
                    bail!("No results found for search query");
                }

                // Display search results
                println!("\n{} Found {} result(s):", style("").green(), results.len());
                for (i, result) in results.iter().enumerate().take(5) {
                    println!("  {}. {} by {}",
                        i + 1,
                        style(&result.title).yellow(),
                        style(result.authors_string()).cyan()
                    );
                }

                // Fetch first result
                println!("\n{} Fetching details for first result...", style("").cyan());
                let asin_to_fetch = &results[0].asin;

                if let Some(cached) = cache.get(asin_to_fetch).await {
                    cached
                } else {
                    let fetched = client.fetch_by_asin(asin_to_fetch).await?;
                    cache.set(asin_to_fetch, &fetched).await?;
                    fetched
                }
            } else {
                bail!("Must provide --asin or --title/--author");
            };

            // Display metadata
            println!("\n{}", style("=".repeat(60)).dim());
            println!("{}: {}", style("Title").bold(), metadata.title);
            if let Some(subtitle) = &metadata.subtitle {
                println!("{}: {}", style("Subtitle").bold(), subtitle);
            }
            if !metadata.authors.is_empty() {
                println!("{}: {}", style("Author(s)").bold(), metadata.authors_string());
            }
            if !metadata.narrators.is_empty() {
                println!("{}: {}", style("Narrator(s)").bold(), metadata.narrators_string());
            }
            if let Some(publisher) = &metadata.publisher {
                println!("{}: {}", style("Publisher").bold(), publisher);
            }
            if let Some(year) = metadata.published_year {
                println!("{}: {}", style("Published").bold(), year);
            }
            if let Some(duration_min) = metadata.runtime_minutes() {
                let hours = duration_min / 60;
                let mins = duration_min % 60;
                println!("{}: {}h {}m", style("Duration").bold(), hours, mins);
            }
            if let Some(lang) = &metadata.language {
                println!("{}: {}", style("Language").bold(), lang);
            }
            if !metadata.genres.is_empty() {
                println!("{}: {}", style("Genres").bold(), metadata.genres.join(", "));
            }
            if !metadata.series.is_empty() {
                for series in &metadata.series {
                    let seq_info = if let Some(seq) = &series.sequence {
                        format!(" (Book {})", seq)
                    } else {
                        String::new()
                    };
                    println!("{}: {}{}", style("Series").bold(), series.name, seq_info);
                }
            }
            println!("{}: {}", style("ASIN").bold(), metadata.asin);
            println!("{}", style("=".repeat(60)).dim());

            // Save to file if requested
            if let Some(output_path) = output {
                let json = serde_json::to_string_pretty(&metadata)?;
                std::fs::write(&output_path, json)?;
                println!("\n{} Saved metadata to: {}",
                    style("").green(),
                    style(output_path.display()).yellow()
                );
            }

            Ok(())
        }

        MetadataCommands::Enrich {
            file,
            asin,
            auto_detect,
            region,
            chapters,
            chapters_asin,
            update_chapters_only,
            merge_strategy,
        } => {
            use crate::audio::{read_m4b_chapters, parse_text_chapters, parse_epub_chapters, merge_chapters, inject_chapters_mp4box, write_mp4box_chapters, ChapterMergeStrategy};
            use std::str::FromStr;

            let action = if update_chapters_only {
                "Updating chapters"
            } else {
                "Enriching M4B file with Audible metadata"
            };
            println!("{} {}...", style("").cyan(), action);

            if !file.exists() {
                bail!("File does not exist: {}", file.display());
            }

            // Parse merge strategy
            let strategy = match merge_strategy.as_str() {
                "keep-timestamps" => ChapterMergeStrategy::KeepTimestamps,
                "replace-all" => ChapterMergeStrategy::ReplaceAll,
                "skip-on-mismatch" => ChapterMergeStrategy::SkipOnMismatch,
                "interactive" => ChapterMergeStrategy::Interactive,
                _ => bail!("Invalid merge strategy: {}. Valid options: keep-timestamps, replace-all, skip-on-mismatch, interactive", merge_strategy),
            };

            // Handle chapter update if requested
            let chapter_update_performed = if chapters.is_some() || chapters_asin.is_some() {
                println!("  {} Reading existing chapters from M4B...", style("").cyan());
                let existing_chapters = read_m4b_chapters(&file).await?;
                println!("  {} Found {} existing chapters", style("").green(), existing_chapters.len());

                // Fetch new chapters based on source
                let new_chapters = if let Some(chapters_file) = chapters {
                    println!("  {} Parsing chapters from file...", style("").cyan());
                    if chapters_file.extension().and_then(|s| s.to_str()) == Some("epub") {
                        parse_epub_chapters(&chapters_file)?
                    } else {
                        parse_text_chapters(&chapters_file)?
                    }
                } else if let Some(asin_val) = chapters_asin {
                    println!("  {} Fetching chapters from Audnex API...", style("").cyan());
                    let audible_region = AudibleRegion::from_str(&region).unwrap_or(AudibleRegion::US);
                    let client = crate::audio::AudibleClient::with_rate_limit(
                        audible_region,
                        config.metadata.audible.rate_limit_per_minute
                    )?;
                    let audible_chapters = client.fetch_chapters(&asin_val).await?;
                    audible_chapters.into_iter().enumerate().map(|(i, ch)| ch.to_chapter((i + 1) as u32)).collect()
                } else {
                    vec![]
                };

                println!("  {} Loaded {} new chapters", style("").green(), new_chapters.len());

                // Merge chapters
                println!("  {} Merging chapters (strategy: {})...", style("").cyan(), merge_strategy);
                let merged = merge_chapters(&existing_chapters, &new_chapters, strategy)?;
                println!("  {} Merged into {} chapters", style("").green(), merged.len());

                // Write chapters to temp file
                let temp_chapters = std::env::temp_dir().join(format!("chapters_{}.txt", file.file_stem().unwrap().to_string_lossy()));
                write_mp4box_chapters(&merged, &temp_chapters)?;

                // Inject chapters back into M4B
                println!("  {} Injecting chapters into M4B...", style("").cyan());
                inject_chapters_mp4box(&file, &temp_chapters).await?;
                std::fs::remove_file(&temp_chapters)?;

                println!("  {} Chapters updated successfully", style("").green());
                true
            } else {
                false
            };

            // Skip metadata enrichment if only updating chapters
            if update_chapters_only {
                if !chapter_update_performed {
                    bail!("--update-chapters-only specified but no chapter source provided (use --chapters or --chapters-asin)");
                }
                println!("\n{} Successfully updated chapters: {}",
                    style("").green(),
                    style(file.display()).yellow()
                );
                return Ok(());
            }

            // Detect or use provided ASIN
            let asin_to_use = if let Some(asin_val) = asin {
                asin_val
            } else if auto_detect {
                detect_asin(&file.display().to_string())
                    .ok_or_else(|| anyhow::anyhow!("Could not detect ASIN from filename: {}", file.display()))?
            } else {
                bail!("Must provide --asin or use --auto-detect");
            };

            println!("  {} Using ASIN: {}", style("").cyan(), asin_to_use);

            // Parse region
            let audible_region = AudibleRegion::from_str(&region)
                .unwrap_or(AudibleRegion::US);

            // Create client and cache
            let client = AudibleClient::with_rate_limit(
                audible_region,
                config.metadata.audible.rate_limit_per_minute
            )?;
            let cache = AudibleCache::with_ttl_hours(config.metadata.audible.cache_duration_hours)?;

            // Fetch metadata
            let metadata = if let Some(cached) = cache.get(&asin_to_use).await {
                println!("  {} Using cached metadata", style("").green());
                cached
            } else {
                println!("  {} Fetching from Audible...", style("").cyan());
                let fetched = client.fetch_by_asin(&asin_to_use).await?;
                cache.set(&asin_to_use, &fetched).await?;
                fetched
            };

            println!("  {} Found: {}", style("").green(), metadata.title);

            // Download cover if available and enabled
            let cover_path = if config.metadata.audible.download_covers {
                if let Some(cover_url) = &metadata.cover_url {
                    println!("  {} Downloading cover art...", style("").cyan());
                    let temp_cover = std::env::temp_dir().join(format!("{}.jpg", asin_to_use));
                    client.download_cover(cover_url, &temp_cover).await?;
                    println!("  {} Cover downloaded", style("").green());
                    Some(temp_cover)
                } else {
                    None
                }
            } else {
                None
            };

            // Inject metadata (this will be implemented in metadata.rs)
            println!("  {} Injecting metadata...", style("").cyan());
            crate::audio::inject_audible_metadata(&file, &metadata, cover_path.as_deref()).await?;

            println!("\n{} Successfully enriched: {}",
                style("").green(),
                style(file.display()).yellow()
            );

            Ok(())
        }
    }
}

/// Handle the match command
pub async fn handle_match(args: MatchArgs, config: Config) -> Result<()> {
    // Determine files to process
    let files = get_files_to_process(&args)?;

    if files.is_empty() {
        println!("{} No M4B files found", style("").red());
        return Ok(());
    }

    println!(
        "{} Found {} M4B file(s)",
        style("").green(),
        style(files.len()).cyan()
    );

    // Initialize Audible client and cache
    let region = AudibleRegion::from_str(&args.region)?;
    let retry_config = crate::core::RetryConfig::with_settings(
        config.metadata.audible.api_max_retries as usize,
        std::time::Duration::from_secs(config.metadata.audible.api_retry_delay_secs),
        std::time::Duration::from_secs(config.metadata.audible.api_max_retry_delay_secs),
        2.0,
    );
    let client = AudibleClient::with_config(
        region,
        config.metadata.audible.rate_limit_per_minute,
        retry_config,
    )?;
    let cache = AudibleCache::with_ttl_hours(
        config.metadata.audible.cache_duration_hours
    )?;

    // Process each file
    let mut processed = 0;
    let mut skipped = 0;
    let mut failed = 0;

    for (idx, file_path) in files.iter().enumerate() {
        println!(
            "\n{} [{}/{}] Processing: {}",
            style("").cyan(),
            idx + 1,
            files.len(),
            style(file_path.display()).yellow()
        );

        match process_single_file(&file_path, &args, &client, &cache, &config).await {
            Ok(ProcessResult::Applied) => processed += 1,
            Ok(ProcessResult::Skipped) => skipped += 1,
            Err(e) => {
                eprintln!("{} Error: {}", style("").red(), e);
                failed += 1;
            }
        }
    }

    // Summary
    println!("\n{}", style("Summary:").bold().cyan());
    println!("  {} Processed: {}", style("").green(), processed);
    println!("  {} Skipped: {}", style("").yellow(), skipped);
    if failed > 0 {
        println!("  {} Failed: {}", style("").red(), failed);
    }

    Ok(())
}

/// Result of processing a single file
enum ProcessResult {
    Applied,
    Skipped,
}

/// Process a single M4B file
async fn process_single_file(
    file_path: &PathBuf,
    args: &MatchArgs,
    client: &AudibleClient,
    _cache: &AudibleCache,
    config: &Config,
) -> Result<ProcessResult> {
    // Extract current metadata
    let mut current = if args.title.is_some() || args.author.is_some() {
        // Manual override
        CurrentMetadata {
            title: args.title.clone(),
            author: args.author.clone(),
            year: None,
            duration: None,
            source: MetadataSource::Manual,
        }
    } else {
        // Auto-extract
        extraction::extract_current_metadata(file_path)?
    };

    // Search loop (allows re-search)
    loop {
        // Search Audible
        let search_results = search_audible(&current, client).await?;

        if search_results.is_empty() {
            println!("{} No matches found on Audible", style("").yellow());

            if args.auto {
                return Ok(ProcessResult::Skipped);
            }

            // Offer manual entry or skip
            match prompt_no_results_action()? {
                NoResultsAction::ManualEntry => {
                    let manual_metadata = prompt_manual_metadata()?;
                    apply_metadata(file_path, &manual_metadata, args, config).await?;
                    return Ok(ProcessResult::Applied);
                }
                NoResultsAction::CustomSearch => {
                    let (title, author) = prompt_custom_search()?;
                    current.title = title;
                    current.author = author;
                    current.source = MetadataSource::Manual;
                    continue; // Re-search
                }
                NoResultsAction::Skip => {
                    return Ok(ProcessResult::Skipped);
                }
            }
        }

        // Score and rank candidates
        let candidates = scoring::score_and_sort(&current, search_results);

        // Auto mode: select best match
        if args.auto {
            let best = &candidates[0];
            println!(
                "  {} Auto-selected: {} ({:.1}%)",
                style("").green(),
                best.metadata.title,
                (1.0 - best.distance.total_distance()) * 100.0
            );

            if !args.dry_run {
                apply_metadata(file_path, &best.metadata, args, config).await?;
            }
            return Ok(ProcessResult::Applied);
        }

        // Interactive mode
        match prompt_match_selection(&current, &candidates)? {
            UserChoice::SelectMatch(idx) => {
                let selected = &candidates[idx];

                // Show what's about to be applied
                println!(
                    "  {} Applying: {} by {}",
                    style("").cyan(),
                    style(&selected.metadata.title).yellow(),
                    style(selected.metadata.authors.first().map(|a| a.name.as_str()).unwrap_or("Unknown")).cyan()
                );

                // Apply directly - selecting is confirming
                if !args.dry_run {
                    apply_metadata(file_path, &selected.metadata, args, config).await?;
                } else {
                    println!("  {} Dry run - metadata not applied", style("").yellow());
                }
                return Ok(ProcessResult::Applied);
            }
            UserChoice::Skip => {
                return Ok(ProcessResult::Skipped);
            }
            UserChoice::ManualEntry => {
                let manual_metadata = prompt_manual_metadata()?;
                if !args.dry_run {
                    apply_metadata(file_path, &manual_metadata, args, config).await?;
                }
                return Ok(ProcessResult::Applied);
            }
            UserChoice::CustomSearch => {
                let (title, author) = prompt_custom_search()?;
                current.title = title;
                current.author = author;
                current.source = MetadataSource::Manual;
                continue; // Re-search
            }
        }
    }
}

/// Get list of M4B files to process
fn get_files_to_process(args: &MatchArgs) -> Result<Vec<PathBuf>> {
    if let Some(file) = &args.file {
        // Single file mode
        if !file.exists() {
            bail!("File not found: {}", file.display());
        }
        if !is_m4b_file(file) {
            bail!("File is not an M4B: {}", file.display());
        }
        Ok(vec![file.clone()])
    } else if let Some(dir) = &args.dir {
        // Directory mode
        if !dir.is_dir() {
            bail!("Not a directory: {}", dir.display());
        }

        let mut files = Vec::new();
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() && is_m4b_file(&path) {
                files.push(path);
            }
        }

        files.sort();
        Ok(files)
    } else {
        bail!("Must specify --file or --dir");
    }
}

/// Check if file is M4B
fn is_m4b_file(path: &PathBuf) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e.eq_ignore_ascii_case("m4b"))
        .unwrap_or(false)
}

/// Search Audible API
async fn search_audible(
    current: &CurrentMetadata,
    client: &AudibleClient,
) -> Result<Vec<crate::models::AudibleMetadata>> {
    // Build search query
    let title = current.title.as_deref();
    let author = current.author.as_deref();

    if title.is_none() && author.is_none() {
        bail!("Need at least title or author to search");
    }

    // Search Audible (now returns full metadata via two-step process)
    let metadata_results = client.search(title, author).await?;

    Ok(metadata_results)
}

/// Apply metadata to M4B file
async fn apply_metadata(
    file_path: &PathBuf,
    metadata: &crate::models::AudibleMetadata,
    args: &MatchArgs,
    config: &Config,
) -> Result<()> {
    // Download cover if needed
    let cover_path = if !args.keep_cover && metadata.cover_url.is_some() && config.metadata.audible.download_covers {
        let temp_cover = std::env::temp_dir().join(format!("{}.jpg", metadata.asin));

        if let Some(cover_url) = &metadata.cover_url {
            let retry_config = crate::core::RetryConfig::with_settings(
                config.metadata.audible.api_max_retries as usize,
                std::time::Duration::from_secs(config.metadata.audible.api_retry_delay_secs),
                std::time::Duration::from_secs(config.metadata.audible.api_max_retry_delay_secs),
                2.0,
            );
            let client = AudibleClient::with_config(
                AudibleRegion::US, // Region doesn't matter for covers
                config.metadata.audible.rate_limit_per_minute,
                retry_config,
            )?;
            client.download_cover(cover_url, &temp_cover).await?;
            Some(temp_cover)
        } else {
            None
        }
    } else {
        None
    };

    // Inject metadata
    crate::audio::inject_audible_metadata(file_path, metadata, cover_path.as_deref()).await?;

    println!(
        "  {} Metadata applied successfully{}",
        style("").green(),
        if cover_path.is_some() {
            " (including cover art)"
        } else {
            ""
        }
    );

    Ok(())
}

/// Action to take when no results found
enum NoResultsAction {
    ManualEntry,
    CustomSearch,
    Skip,
}

/// Prompt for action when no results found
fn prompt_no_results_action() -> Result<NoResultsAction> {
    use inquire::Select;

    let options = vec![
        "[S]kip this file",
        "Search with [D]ifferent terms",
        "Enter metadata [M]anually",
    ];

    let selection = Select::new("What would you like to do?", options).prompt()?;

    match selection {
        "[S]kip this file" => Ok(NoResultsAction::Skip),
        "Search with [D]ifferent terms" => Ok(NoResultsAction::CustomSearch),
        "Enter metadata [M]anually" => Ok(NoResultsAction::ManualEntry),
        _ => Ok(NoResultsAction::Skip),
    }
}