subx-cli 1.7.4

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
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
//! Comprehensive error types for the SubX CLI application operations.
//!
//! This module defines the `SubXError` enum covering all error conditions
//! that can occur during subtitle processing, AI service integration,
//! audio analysis, file matching, and general command execution.
//!
//! It also provides helper methods to construct errors and generate
//! user-friendly messages.
use thiserror::Error;

/// Represents all possible errors in the SubX application.
///
/// Each variant provides specific context to facilitate debugging and
/// user-friendly reporting.
///
/// # Examples
///
/// ```rust
/// use subx_cli::error::{SubXError, SubXResult};
///
/// fn example() -> SubXResult<()> {
///     Err(SubXError::SubtitleFormat {
///         format: "SRT".to_string(),
///         message: "Invalid timestamp format".to_string(),
///     })
/// }
/// ```
///
/// # Exit Codes
///
/// Each error variant maps to an exit code via `SubXError::exit_code`.
#[derive(Error, Debug)]
pub enum SubXError {
    /// I/O operation failed during file system access.
    ///
    /// This variant wraps `std::io::Error` and provides context about
    /// file operations that failed.
    ///
    /// # Common Causes
    /// - Permission issues
    /// - Insufficient disk space
    /// - Network filesystem errors
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Configuration error due to invalid or missing settings.
    ///
    /// Contains a human-readable message describing the issue.
    #[error("Configuration error: {message}")]
    Config {
        /// Description of the configuration error
        message: String,
    },

    /// Subtitle format error indicating invalid timestamps or structure.
    ///
    /// Provides the subtitle format and detailed message.
    #[error("Subtitle format error [{format}]: {message}")]
    SubtitleFormat {
        /// The subtitle format that caused the error (e.g., "SRT", "ASS")
        format: String,
        /// Detailed error message describing the issue
        message: String,
    },

    /// AI service encountered an error.
    ///
    /// Captures the raw error message from the AI provider.
    #[error("AI service error: {0}")]
    AiService(String),

    /// API request error with specified source.
    ///
    /// Represents errors that occur during API requests, providing both
    /// the error message and the source of the API error.
    #[error("API error [{source:?}]: {message}")]
    Api {
        /// Error message from the API
        message: String,
        /// Source of the API error
        source: ApiErrorSource,
    },

    /// Audio processing error during analysis or format conversion.
    ///
    /// Provides a message describing the audio processing failure.
    #[error("Audio processing error: {message}")]
    AudioProcessing {
        /// Description of the audio processing error
        message: String,
    },

    /// Error during file matching or discovery.
    ///
    /// Contains details about path resolution or pattern matching failures.
    #[error("File matching error: {message}")]
    FileMatching {
        /// Description of the file matching error
        message: String,
    },
    /// Indicates that a file operation failed because the target exists.
    #[error("File already exists: {0}")]
    FileAlreadyExists(String),
    /// Indicates that the specified file was not found.
    #[error("File not found: {0}")]
    FileNotFound(String),
    /// Invalid file name encountered.
    #[error("Invalid file name: {0}")]
    InvalidFileName(String),
    /// Generic file operation failure with message.
    #[error("File operation failed: {0}")]
    FileOperationFailed(String),
    /// Generic command execution error.
    #[error("{0}")]
    CommandExecution(String),

    /// No input path was specified for the operation.
    #[error("No input path specified")]
    NoInputSpecified,

    /// The provided path is invalid or malformed.
    #[error("Invalid path: {0}")]
    InvalidPath(std::path::PathBuf),

    /// The specified path does not exist on the filesystem.
    #[error("Path not found: {0}")]
    PathNotFound(std::path::PathBuf),

    /// Unable to read the specified directory.
    #[error("Unable to read directory: {path}")]
    DirectoryReadError {
        /// The directory path that could not be read
        path: std::path::PathBuf,
        /// The underlying I/O error
        #[source]
        source: std::io::Error,
    },

    /// Invalid synchronization configuration: please specify video and subtitle files, or use -i parameter for batch processing.
    #[error(
        "Invalid sync configuration: please specify video and subtitle files, or use -i parameter for batch processing"
    )]
    InvalidSyncConfiguration,

    /// Unsupported file type encountered.
    #[error("Unsupported file type: {0}")]
    UnsupportedFileType(String),

    /// The active output mode (e.g. `--output json`) is incompatible
    /// with the requested subcommand.
    ///
    /// Currently emitted by `generate-completion`, whose stdout is by
    /// design a shell-completion script and cannot be wrapped in the
    /// JSON envelope contract.
    #[error(
        "The '{command}' command does not support --output json; its stdout is a shell-completion script"
    )]
    OutputModeUnsupported {
        /// The subcommand that rejected the output mode (e.g. `"generate-completion"`).
        command: String,
    },

    /// Catch-all error variant wrapping any other failure.
    #[error("Unknown error: {0}")]
    Other(#[from] anyhow::Error),
}

// Unit test: SubXError error types and helper methods
#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::path::PathBuf;

    // ── Display messages ──────────────────────────────────────────────────────

    #[test]
    fn test_io_error_display() {
        let err = SubXError::Io(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
        assert!(err.to_string().starts_with("I/O error:"));
        assert!(err.to_string().contains("denied"));
    }

    #[test]
    fn test_ai_service_display() {
        let err = SubXError::AiService("timeout".to_string());
        assert_eq!(err.to_string(), "AI service error: timeout");
    }

    #[test]
    fn test_api_display() {
        let err = SubXError::Api {
            message: "bad request".to_string(),
            source: ApiErrorSource::OpenAI,
        };
        let s = err.to_string();
        assert!(s.contains("API error"));
        assert!(s.contains("bad request"));
        assert!(s.contains("OpenAI"));
    }

    #[test]
    fn test_file_already_exists_display() {
        let err = SubXError::FileAlreadyExists("foo.srt".to_string());
        assert_eq!(err.to_string(), "File already exists: foo.srt");
    }

    #[test]
    fn test_file_not_found_display() {
        let err = SubXError::FileNotFound("bar.srt".to_string());
        assert_eq!(err.to_string(), "File not found: bar.srt");
    }

    #[test]
    fn test_invalid_file_name_display() {
        let err = SubXError::InvalidFileName("bad?name".to_string());
        assert_eq!(err.to_string(), "Invalid file name: bad?name");
    }

    #[test]
    fn test_file_operation_failed_display() {
        let err = SubXError::FileOperationFailed("rename failed".to_string());
        assert_eq!(err.to_string(), "File operation failed: rename failed");
    }

    #[test]
    fn test_command_execution_display() {
        let err = SubXError::CommandExecution("exit 1".to_string());
        assert_eq!(err.to_string(), "exit 1");
    }

    #[test]
    fn test_no_input_specified_display() {
        let err = SubXError::NoInputSpecified;
        assert_eq!(err.to_string(), "No input path specified");
    }

    #[test]
    fn test_invalid_path_display() {
        let err = SubXError::InvalidPath(PathBuf::from("/bad/path"));
        assert!(err.to_string().contains("Invalid path:"));
        assert!(err.to_string().contains("/bad/path"));
    }

    #[test]
    fn test_path_not_found_display() {
        let err = SubXError::PathNotFound(PathBuf::from("/missing"));
        assert!(err.to_string().contains("Path not found:"));
    }

    #[test]
    fn test_directory_read_error_display() {
        let err = SubXError::DirectoryReadError {
            path: PathBuf::from("/locked"),
            source: io::Error::new(io::ErrorKind::PermissionDenied, "denied"),
        };
        assert!(err.to_string().contains("Unable to read directory:"));
        assert!(err.to_string().contains("/locked"));
    }

    #[test]
    fn test_invalid_sync_configuration_display() {
        let err = SubXError::InvalidSyncConfiguration;
        assert!(err.to_string().contains("Invalid sync configuration"));
    }

    #[test]
    fn test_unsupported_file_type_display() {
        let err = SubXError::UnsupportedFileType("xyz".to_string());
        assert_eq!(err.to_string(), "Unsupported file type: xyz");
    }

    #[test]
    fn test_other_error_display() {
        let err = SubXError::Other(anyhow::anyhow!("wrapped error"));
        assert!(err.to_string().contains("Unknown error:"));
        assert!(err.to_string().contains("wrapped error"));
    }

    // ── ApiErrorSource ────────────────────────────────────────────────────────

    #[test]
    fn test_api_error_source_display() {
        assert_eq!(ApiErrorSource::OpenAI.to_string(), "OpenAI");
        assert_eq!(ApiErrorSource::Whisper.to_string(), "Whisper");
    }

    // ── exit_code mapping ─────────────────────────────────────────────────────

    #[test]
    fn test_config_error_creation() {
        let error = SubXError::config("test config error");
        assert!(matches!(error, SubXError::Config { .. }));
        assert_eq!(error.to_string(), "Configuration error: test config error");
    }

    #[test]
    fn test_subtitle_format_error_creation() {
        let error = SubXError::subtitle_format("SRT", "invalid format");
        assert!(matches!(error, SubXError::SubtitleFormat { .. }));
        let msg = error.to_string();
        assert!(msg.contains("SRT"));
        assert!(msg.contains("invalid format"));
    }

    #[test]
    fn test_audio_processing_error_creation() {
        let error = SubXError::audio_processing("decode failed");
        assert!(matches!(error, SubXError::AudioProcessing { .. }));
        assert_eq!(error.to_string(), "Audio processing error: decode failed");
    }

    #[test]
    fn test_file_matching_error_creation() {
        let error = SubXError::file_matching("match failed");
        assert!(matches!(error, SubXError::FileMatching { .. }));
        assert_eq!(error.to_string(), "File matching error: match failed");
    }

    #[test]
    fn test_io_error_conversion() {
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let subx_error: SubXError = io_error.into();
        assert!(matches!(subx_error, SubXError::Io(_)));
    }

    #[test]
    fn test_exit_codes() {
        assert_eq!(SubXError::config("test").exit_code(), 2);
        assert_eq!(SubXError::subtitle_format("SRT", "test").exit_code(), 4);
        assert_eq!(SubXError::audio_processing("test").exit_code(), 5);
        assert_eq!(SubXError::file_matching("test").exit_code(), 6);
    }

    #[test]
    fn test_user_friendly_messages() {
        let config_error = SubXError::config("missing key");
        let message = config_error.user_friendly_message();
        assert!(message.contains("Configuration error:"));
        assert!(message.contains("subx-cli config --help"));

        let ai_error = SubXError::ai_service("network failure".to_string());
        let message = ai_error.user_friendly_message();
        assert!(message.contains("AI service error:"));
        assert!(message.contains("check network connection"));
    }

    /// Audit: enumerates every `SubXError` variant and asserts that a
    /// representative instance — built from non-sensitive dummy data —
    /// never surfaces an OpenAI-style API key prefix (`sk-`) through
    /// `Display`, `Debug`, or `user_friendly_message()`. If you add a
    /// new variant, extend this list so the audit remains exhaustive.
    ///
    /// Separately, this test also exercises the sanitizing construction
    /// paths (`From<reqwest::Error>`-style flows via the AI client's
    /// `error_sanitizer` helpers) to confirm that when input *does*
    /// contain an `sk-*` secret, it is stripped before wrapping it in
    /// `SubXError::AiService`.
    #[test]
    fn test_no_api_key_leaks_in_any_variant() {
        use crate::services::ai::error_sanitizer::{
            DEFAULT_ERROR_BODY_MAX_LEN, sanitize_url_in_error, truncate_error_body,
        };
        use std::path::PathBuf;

        // 1. Canonical variant audit: benign dummy data must never yield
        //    an `sk-` substring.
        let variants: Vec<SubXError> = vec![
            SubXError::Io(io::Error::other("disk error")),
            SubXError::Config {
                message: "missing key".to_string(),
            },
            SubXError::SubtitleFormat {
                format: "SRT".to_string(),
                message: "bad timestamp".to_string(),
            },
            SubXError::AiService("upstream service failed".to_string()),
            SubXError::Api {
                message: "auth failed".to_string(),
                source: ApiErrorSource::OpenAI,
            },
            SubXError::AudioProcessing {
                message: "codec failure".to_string(),
            },
            SubXError::FileMatching {
                message: "pattern mismatch".to_string(),
            },
            SubXError::FileAlreadyExists("/tmp/example".to_string()),
            SubXError::FileNotFound("/tmp/example".to_string()),
            SubXError::InvalidFileName("bad?name".to_string()),
            SubXError::FileOperationFailed("rename failed".to_string()),
            SubXError::CommandExecution("exit 1".to_string()),
            SubXError::NoInputSpecified,
            SubXError::InvalidPath(PathBuf::from("/tmp/example")),
            SubXError::PathNotFound(PathBuf::from("/tmp/example")),
            SubXError::DirectoryReadError {
                path: PathBuf::from("/tmp/example"),
                source: io::Error::other("denied"),
            },
            SubXError::InvalidSyncConfiguration,
            SubXError::UnsupportedFileType("xyz".to_string()),
            SubXError::OutputModeUnsupported {
                command: "generate-completion".to_string(),
            },
            SubXError::Other(anyhow::anyhow!("wrapped")),
        ];

        for err in &variants {
            let display = format!("{}", err);
            let debug = format!("{:?}", err);
            let friendly = err.user_friendly_message();
            for (label, text) in [
                ("Display", &display),
                ("Debug", &debug),
                ("friendly", &friendly),
            ] {
                assert!(
                    !text.contains("sk-"),
                    "{} surface for variant {:?} contains `sk-` prefix: {}",
                    label,
                    err,
                    text,
                );
            }
        }

        // 2. Sanitizing construction paths: API keys injected via the
        //    upstream response body or URL query string must be stripped
        //    before being embedded into `SubXError::AiService`.
        const SECRET: &str = "sk-test-key-12345";
        let upstream_body = format!(
            "{{\"error\": \"invalid\", \"echoed\": \"Bearer {}\"}}",
            SECRET
        );
        let truncated = truncate_error_body(&upstream_body, DEFAULT_ERROR_BODY_MAX_LEN);
        // Helper does not itself mask secrets shorter than the limit; this
        // documents that short bodies pass through unchanged so upstream
        // callers must continue to keep secrets out of request bodies.
        assert!(truncated.contains(SECRET));

        let url_leak = format!(
            "request error: https://api.example.com/v1/chat?api-key={}",
            SECRET
        );
        let cleaned = sanitize_url_in_error(&url_leak);
        assert!(!cleaned.contains("sk-test-key"));
        let wrapped = SubXError::AiService(cleaned);
        assert!(!format!("{}", wrapped).contains("sk-test-key"));
        assert!(!format!("{:?}", wrapped).contains("sk-test-key"));
    }

    // ── exit_code – remaining variants ───────────────────────────────────────

    #[test]
    fn test_exit_code_io() {
        let err = SubXError::Io(io::Error::new(io::ErrorKind::NotFound, "x"));
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn test_exit_code_api() {
        let err = SubXError::Api {
            message: "x".to_string(),
            source: ApiErrorSource::OpenAI,
        };
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn test_exit_code_ai_service() {
        let err = SubXError::AiService("x".to_string());
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn test_exit_code_catchall_variants() {
        assert_eq!(SubXError::FileAlreadyExists("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::FileNotFound("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::InvalidFileName("f".to_string()).exit_code(), 1);
        assert_eq!(
            SubXError::FileOperationFailed("f".to_string()).exit_code(),
            1
        );
        assert_eq!(SubXError::CommandExecution("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::NoInputSpecified.exit_code(), 1);
        assert_eq!(SubXError::InvalidPath(PathBuf::from("/x")).exit_code(), 1);
        assert_eq!(SubXError::PathNotFound(PathBuf::from("/x")).exit_code(), 1);
        assert_eq!(SubXError::InvalidSyncConfiguration.exit_code(), 1);
        assert_eq!(
            SubXError::UnsupportedFileType("xyz".to_string()).exit_code(),
            1
        );
        assert_eq!(SubXError::Other(anyhow::anyhow!("other")).exit_code(), 1);
    }

    // ── category / machine_code / exit_code contract ────────────────────────

    /// Exhaustive contract test for the closed `SubXError` mapping locked
    /// by `specs/error-handling/spec.md`. If a new variant is added, this
    /// test (and the exhaustive matches in `category()`/`machine_code()`)
    /// SHALL be updated; the compiler-enforced exhaustive match guards
    /// the source of truth.
    #[test]
    fn test_category_and_machine_code_contract() {
        let cases: Vec<(SubXError, &'static str, &'static str, i32)> = vec![
            (SubXError::Io(io::Error::other("x")), "io", "E_IO", 1),
            (
                SubXError::Config {
                    message: "x".into(),
                },
                "config",
                "E_CONFIG",
                2,
            ),
            (
                SubXError::SubtitleFormat {
                    format: "SRT".into(),
                    message: "x".into(),
                },
                "subtitle_format",
                "E_SUBTITLE_FORMAT",
                4,
            ),
            (
                SubXError::AiService("x".into()),
                "ai_service",
                "E_AI_SERVICE",
                3,
            ),
            (
                SubXError::Api {
                    message: "x".into(),
                    source: ApiErrorSource::OpenAI,
                },
                "api",
                "E_API",
                3,
            ),
            (
                SubXError::AudioProcessing {
                    message: "x".into(),
                },
                "audio_processing",
                "E_AUDIO_PROCESSING",
                5,
            ),
            (
                SubXError::FileMatching {
                    message: "x".into(),
                },
                "file_matching",
                "E_FILE_MATCHING",
                6,
            ),
            (
                SubXError::FileAlreadyExists("x".into()),
                "file_already_exists",
                "E_FILE_ALREADY_EXISTS",
                1,
            ),
            (
                SubXError::FileNotFound("x".into()),
                "file_not_found",
                "E_FILE_NOT_FOUND",
                1,
            ),
            (
                SubXError::InvalidFileName("x".into()),
                "invalid_file_name",
                "E_INVALID_FILE_NAME",
                1,
            ),
            (
                SubXError::FileOperationFailed("x".into()),
                "file_operation_failed",
                "E_FILE_OPERATION_FAILED",
                1,
            ),
            (
                SubXError::CommandExecution("x".into()),
                "command_execution",
                "E_COMMAND_EXECUTION",
                1,
            ),
            (
                SubXError::NoInputSpecified,
                "no_input_specified",
                "E_NO_INPUT_SPECIFIED",
                1,
            ),
            (
                SubXError::InvalidPath(PathBuf::from("/x")),
                "invalid_path",
                "E_INVALID_PATH",
                1,
            ),
            (
                SubXError::PathNotFound(PathBuf::from("/x")),
                "path_not_found",
                "E_PATH_NOT_FOUND",
                1,
            ),
            (
                SubXError::DirectoryReadError {
                    path: PathBuf::from("/x"),
                    source: io::Error::other("denied"),
                },
                "directory_read_error",
                "E_DIRECTORY_READ_ERROR",
                1,
            ),
            (
                SubXError::InvalidSyncConfiguration,
                "invalid_sync_configuration",
                "E_INVALID_SYNC_CONFIGURATION",
                1,
            ),
            (
                SubXError::UnsupportedFileType("xyz".into()),
                "unsupported_file_type",
                "E_UNSUPPORTED_FILE_TYPE",
                1,
            ),
            (
                SubXError::OutputModeUnsupported {
                    command: "generate-completion".into(),
                },
                "command_execution",
                "E_OUTPUT_MODE_UNSUPPORTED",
                1,
            ),
            (
                SubXError::Other(anyhow::anyhow!("x")),
                "other",
                "E_OTHER",
                1,
            ),
        ];

        for (err, cat, code, exit) in &cases {
            assert_eq!(err.category(), *cat, "category mismatch for {:?}", err);
            assert_eq!(
                err.machine_code(),
                *code,
                "machine_code mismatch for {:?}",
                err
            );
            assert_eq!(err.exit_code(), *exit, "exit_code mismatch for {:?}", err);
            assert!(!err.category().is_empty());
            assert!(err.machine_code().starts_with("E_"));
        }
    }

    // ── user_friendly_message – all variants ─────────────────────────────────

    #[test]
    fn test_user_friendly_message_io() {
        let err = SubXError::Io(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
        let msg = err.user_friendly_message();
        assert!(msg.contains("File operation error:"));
        assert!(msg.contains("denied"));
    }

    #[test]
    fn test_user_friendly_message_api() {
        let err = SubXError::Api {
            message: "forbidden".to_string(),
            source: ApiErrorSource::OpenAI,
        };
        let msg = err.user_friendly_message();
        assert!(msg.contains("API error"));
        assert!(msg.contains("forbidden"));
        assert!(msg.contains("check network connection"));
    }

    #[test]
    fn test_user_friendly_message_subtitle_format() {
        let err = SubXError::subtitle_format("ASS", "bad encoding");
        let msg = err.user_friendly_message();
        assert!(msg.contains("Subtitle processing error:"));
        assert!(msg.contains("bad encoding"));
        assert!(msg.contains("check file format"));
    }

    #[test]
    fn test_user_friendly_message_audio_processing() {
        let err = SubXError::audio_processing("corrupt frame");
        let msg = err.user_friendly_message();
        assert!(msg.contains("Audio processing error:"));
        assert!(msg.contains("corrupt frame"));
        assert!(msg.contains("media file integrity"));
    }

    #[test]
    fn test_user_friendly_message_file_matching() {
        let err = SubXError::file_matching("pattern mismatch");
        let msg = err.user_friendly_message();
        assert!(msg.contains("File matching error:"));
        assert!(msg.contains("pattern mismatch"));
        assert!(msg.contains("verify file paths"));
    }

    #[test]
    fn test_user_friendly_message_file_already_exists() {
        let err = SubXError::FileAlreadyExists("output.srt".to_string());
        assert_eq!(
            err.user_friendly_message(),
            "File already exists: output.srt"
        );
    }

    #[test]
    fn test_user_friendly_message_file_not_found() {
        let err = SubXError::FileNotFound("input.srt".to_string());
        assert_eq!(err.user_friendly_message(), "File not found: input.srt");
    }

    #[test]
    fn test_user_friendly_message_invalid_file_name() {
        let err = SubXError::InvalidFileName("bad?name".to_string());
        assert_eq!(err.user_friendly_message(), "Invalid file name: bad?name");
    }

    #[test]
    fn test_user_friendly_message_file_operation_failed() {
        let err = SubXError::FileOperationFailed("rename failed".to_string());
        assert_eq!(
            err.user_friendly_message(),
            "File operation failed: rename failed"
        );
    }

    #[test]
    fn test_user_friendly_message_command_execution() {
        let err = SubXError::CommandExecution("process died".to_string());
        assert_eq!(err.user_friendly_message(), "process died");
    }

    #[test]
    fn test_user_friendly_message_other() {
        let err = SubXError::Other(anyhow::anyhow!("mystery"));
        let msg = err.user_friendly_message();
        assert!(msg.contains("Unknown error:"));
        assert!(msg.contains("mystery"));
        assert!(msg.contains("please report this issue"));
    }

    #[test]
    fn test_user_friendly_message_catchall_variants() {
        // Variants that fall through to the `_ => format!("Error: {}", self)` arm.
        let cases: Vec<SubXError> = vec![
            SubXError::NoInputSpecified,
            SubXError::InvalidPath(PathBuf::from("/bad")),
            SubXError::PathNotFound(PathBuf::from("/missing")),
            SubXError::DirectoryReadError {
                path: PathBuf::from("/locked"),
                source: io::Error::new(io::ErrorKind::PermissionDenied, "denied"),
            },
            SubXError::InvalidSyncConfiguration,
            SubXError::UnsupportedFileType("xyz".to_string()),
        ];
        for err in &cases {
            let msg = err.user_friendly_message();
            assert!(
                msg.starts_with("Error:"),
                "Expected 'Error:' prefix for {:?}, got: {}",
                err,
                msg
            );
        }
    }

    // ── Helper constructor methods ────────────────────────────────────────────

    #[test]
    fn test_ai_service_helper() {
        let err = SubXError::ai_service("network failure");
        assert!(matches!(err, SubXError::AiService(_)));
        assert_eq!(err.to_string(), "AI service error: network failure");
    }

    #[test]
    fn test_parallel_processing_helper() {
        let err = SubXError::parallel_processing("channel closed".to_string());
        assert!(matches!(err, SubXError::CommandExecution(_)));
        assert!(err.to_string().contains("Parallel processing error:"));
        assert!(err.to_string().contains("channel closed"));
    }

    #[test]
    fn test_task_execution_failed_helper() {
        let err = SubXError::task_execution_failed("task-42".to_string(), "panic".to_string());
        assert!(matches!(err, SubXError::CommandExecution(_)));
        assert!(err.to_string().contains("task-42"));
        assert!(err.to_string().contains("panic"));
    }

    #[test]
    fn test_worker_pool_exhausted_helper() {
        let err = SubXError::worker_pool_exhausted();
        assert!(matches!(err, SubXError::CommandExecution(_)));
        assert_eq!(err.to_string(), "Worker pool exhausted");
    }

    #[test]
    fn test_task_timeout_helper() {
        let dur = std::time::Duration::from_secs(30);
        let err = SubXError::task_timeout("task-7".to_string(), dur);
        assert!(matches!(err, SubXError::CommandExecution(_)));
        assert!(err.to_string().contains("task-7"));
        assert!(err.to_string().contains("timed out"));
    }

    #[test]
    fn test_dialogue_detection_failed_helper() {
        let err = SubXError::dialogue_detection_failed("no speech found");
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("Dialogue detection failed:"));
        assert!(err.to_string().contains("no speech found"));
    }

    #[test]
    fn test_invalid_audio_format_helper() {
        let err = SubXError::invalid_audio_format("flac");
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("Unsupported audio format:"));
        assert!(err.to_string().contains("flac"));
    }

    #[test]
    fn test_dialogue_segment_invalid_helper() {
        let err = SubXError::dialogue_segment_invalid("negative duration");
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("Invalid dialogue segment:"));
        assert!(err.to_string().contains("negative duration"));
    }

    #[test]
    fn test_whisper_api_helper() {
        let err = SubXError::whisper_api("rate limited");
        assert!(matches!(err, SubXError::Api { .. }));
        let s = err.to_string();
        assert!(s.contains("Whisper"));
        assert!(s.contains("rate limited"));
    }

    #[test]
    fn test_audio_extraction_helper() {
        let err = SubXError::audio_extraction("ffmpeg missing");
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("ffmpeg missing"));
    }

    // ── From conversions ─────────────────────────────────────────────────────

    #[test]
    fn test_from_anyhow_error() {
        let anyhow_err = anyhow::anyhow!("some anyhow error");
        let err: SubXError = anyhow_err.into();
        assert!(matches!(err, SubXError::Other(_)));
        assert!(err.to_string().contains("some anyhow error"));
    }

    #[test]
    fn test_from_serde_json_error() {
        let json_err: serde_json::Error =
            serde_json::from_str::<serde_json::Value>("not json {{{").unwrap_err();
        let err: SubXError = json_err.into();
        assert!(matches!(err, SubXError::Config { .. }));
        assert!(
            err.to_string()
                .contains("JSON serialization/deserialization error:")
        );
    }

    #[test]
    fn test_from_config_error_not_found() {
        let config_err = config::ConfigError::NotFound("settings.toml".to_string());
        let err: SubXError = config_err.into();
        assert!(matches!(err, SubXError::Config { .. }));
        assert!(err.to_string().contains("Configuration file not found:"));
        assert!(err.to_string().contains("settings.toml"));
    }

    #[test]
    fn test_from_config_error_message() {
        let config_err = config::ConfigError::Message("bad value".to_string());
        let err: SubXError = config_err.into();
        assert!(matches!(err, SubXError::Config { .. }));
        assert!(err.to_string().contains("bad value"));
    }

    #[test]
    fn test_from_config_error_other() {
        // Use a variant that falls through to the catch-all arm.
        let config_err = config::ConfigError::Foreign(Box::new(io::Error::new(
            io::ErrorKind::Other,
            "foreign cfg error",
        )));
        let err: SubXError = config_err.into();
        assert!(matches!(err, SubXError::Config { .. }));
        assert!(err.to_string().contains("Configuration error:"));
    }

    #[test]
    fn test_from_box_dyn_error() {
        let boxed: Box<dyn std::error::Error> =
            Box::new(io::Error::new(io::ErrorKind::Other, "boxed error"));
        let err: SubXError = boxed.into();
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("Audio processing error:"));
        assert!(err.to_string().contains("boxed error"));
    }

    #[test]
    fn test_from_walkdir_error() {
        // Walk a non-existent path to generate a walkdir::Error.
        let walk_err = walkdir::WalkDir::new("/nonexistent_subx_test_path_xyz")
            .into_iter()
            .filter_map(|e| e.err())
            .next();
        if let Some(we) = walk_err {
            let err: SubXError = we.into();
            assert!(matches!(err, SubXError::FileMatching { .. }));
        }
        // If no error was produced (unlikely), the From impl was never
        // reached, but the test still passes: we cannot force the error.
    }

    #[test]
    fn test_from_symphonia_error() {
        use symphonia::core::errors::Error as SymphoniaError;
        let sym_err = SymphoniaError::DecodeError("bad frame");
        let err: SubXError = sym_err.into();
        assert!(matches!(err, SubXError::AudioProcessing { .. }));
        assert!(err.to_string().contains("Audio processing error:"));
    }

    // ── SubXResult type alias ─────────────────────────────────────────────────

    #[test]
    fn test_subx_result_ok() {
        let result: SubXResult<i32> = Ok(42);
        assert_eq!(result.unwrap(), 42);
    }

    #[test]
    fn test_subx_result_err() {
        let result: SubXResult<i32> = Err(SubXError::NoInputSpecified);
        assert!(result.is_err());
    }
}

// Convert reqwest error to AI service error
impl From<reqwest::Error> for SubXError {
    fn from(err: reqwest::Error) -> Self {
        let raw = err.to_string();
        // Strip query strings from any embedded URLs, since reqwest's Display
        // implementation includes the full request URL which may carry
        // sensitive credentials (e.g. `?api-key=...`).
        let sanitized = crate::services::ai::error_sanitizer::sanitize_url_in_error(&raw);
        SubXError::AiService(sanitized)
    }
}

// Convert file exploration error to file matching error
impl From<walkdir::Error> for SubXError {
    fn from(err: walkdir::Error) -> Self {
        SubXError::FileMatching {
            message: err.to_string(),
        }
    }
}
// Convert symphonia error to audio processing error
impl From<symphonia::core::errors::Error> for SubXError {
    fn from(err: symphonia::core::errors::Error) -> Self {
        SubXError::audio_processing(err.to_string())
    }
}

// Convert config crate error to configuration error
impl From<config::ConfigError> for SubXError {
    fn from(err: config::ConfigError) -> Self {
        match err {
            config::ConfigError::NotFound(path) => SubXError::Config {
                message: format!("Configuration file not found: {}", path),
            },
            config::ConfigError::Message(msg) => SubXError::Config { message: msg },
            _ => SubXError::Config {
                message: format!("Configuration error: {}", err),
            },
        }
    }
}

impl From<serde_json::Error> for SubXError {
    fn from(err: serde_json::Error) -> Self {
        SubXError::Config {
            message: format!("JSON serialization/deserialization error: {}", err),
        }
    }
}

/// Specialized `Result` type for SubX operations.
pub type SubXResult<T> = Result<T, SubXError>;

impl SubXError {
    /// Create a configuration error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::config("invalid setting");
    /// assert_eq!(err.to_string(), "Configuration error: invalid setting");
    /// ```
    pub fn config<S: Into<String>>(message: S) -> Self {
        SubXError::Config {
            message: message.into(),
        }
    }

    /// Create a subtitle format error for the given format and message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::subtitle_format("SRT", "invalid timestamp");
    /// assert!(err.to_string().contains("SRT"));
    /// ```
    pub fn subtitle_format<S1, S2>(format: S1, message: S2) -> Self
    where
        S1: Into<String>,
        S2: Into<String>,
    {
        SubXError::SubtitleFormat {
            format: format.into(),
            message: message.into(),
        }
    }

    /// Create an audio processing error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::audio_processing("decode failed");
    /// assert_eq!(err.to_string(), "Audio processing error: decode failed");
    /// ```
    pub fn audio_processing<S: Into<String>>(message: S) -> Self {
        SubXError::AudioProcessing {
            message: message.into(),
        }
    }

    /// Create an AI service error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::ai_service("network failure");
    /// assert_eq!(err.to_string(), "AI service error: network failure");
    /// ```
    pub fn ai_service<S: Into<String>>(message: S) -> Self {
        SubXError::AiService(message.into())
    }

    /// Create a file matching error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::file_matching("not found");
    /// assert_eq!(err.to_string(), "File matching error: not found");
    /// ```
    pub fn file_matching<S: Into<String>>(message: S) -> Self {
        SubXError::FileMatching {
            message: message.into(),
        }
    }
    /// Create a parallel processing error with the given message.
    pub fn parallel_processing(msg: String) -> Self {
        SubXError::CommandExecution(format!("Parallel processing error: {}", msg))
    }
    /// Create a task execution failure error with task ID and reason.
    pub fn task_execution_failed(task_id: String, reason: String) -> Self {
        SubXError::CommandExecution(format!("Task {} execution failed: {}", task_id, reason))
    }
    /// Create a worker pool exhausted error.
    pub fn worker_pool_exhausted() -> Self {
        SubXError::CommandExecution("Worker pool exhausted".to_string())
    }
    /// Create a task timeout error with task ID and duration.
    pub fn task_timeout(task_id: String, duration: std::time::Duration) -> Self {
        SubXError::CommandExecution(format!(
            "Task {} timed out (limit: {:?})",
            task_id, duration
        ))
    }
    /// Create a dialogue detection failure error with the given message.
    pub fn dialogue_detection_failed<S: Into<String>>(msg: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Dialogue detection failed: {}", msg.into()),
        }
    }
    /// Create an invalid audio format error for the given format.
    pub fn invalid_audio_format<S: Into<String>>(format: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Unsupported audio format: {}", format.into()),
        }
    }
    /// Create an invalid dialogue segment error with the given reason.
    pub fn dialogue_segment_invalid<S: Into<String>>(reason: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Invalid dialogue segment: {}", reason.into()),
        }
    }
    /// Return the corresponding exit code for this error variant.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// assert_eq!(SubXError::config("x").exit_code(), 2);
    /// ```
    pub fn exit_code(&self) -> i32 {
        match self {
            SubXError::Io(_) => 1,
            SubXError::Config { .. } => 2,
            SubXError::Api { .. } => 3,
            SubXError::AiService(_) => 3,
            SubXError::SubtitleFormat { .. } => 4,
            SubXError::AudioProcessing { .. } => 5,
            SubXError::FileMatching { .. } => 6,
            _ => 1,
        }
    }

    /// Stable snake_case machine-readable category for the JSON error
    /// envelope. The mapping is closed and exhaustive (no wildcard arm)
    /// so the compiler enforces updates whenever a new variant is added.
    ///
    /// This mapping is locked by the `error-handling` capability spec.
    pub fn category(&self) -> &'static str {
        match self {
            // Mapped 1:1 from the closed set defined in the spec.
            SubXError::Io(_) => "io",
            SubXError::Config { .. } => "config",
            SubXError::SubtitleFormat { .. } => "subtitle_format",
            SubXError::AiService(_) => "ai_service",
            SubXError::Api { .. } => "api",
            SubXError::AudioProcessing { .. } => "audio_processing",
            SubXError::FileMatching { .. } => "file_matching",
            SubXError::FileAlreadyExists(_) => "file_already_exists",
            SubXError::FileNotFound(_) => "file_not_found",
            SubXError::InvalidFileName(_) => "invalid_file_name",
            SubXError::FileOperationFailed(_) => "file_operation_failed",
            SubXError::CommandExecution(_) => "command_execution",
            // Spec locks `category == "command_execution"` for this variant
            // even though the machine_code is the more specific
            // `E_OUTPUT_MODE_UNSUPPORTED`.
            SubXError::OutputModeUnsupported { .. } => "command_execution",
            SubXError::NoInputSpecified => "no_input_specified",
            SubXError::InvalidPath(_) => "invalid_path",
            SubXError::PathNotFound(_) => "path_not_found",
            SubXError::DirectoryReadError { .. } => "directory_read_error",
            SubXError::InvalidSyncConfiguration => "invalid_sync_configuration",
            SubXError::UnsupportedFileType(_) => "unsupported_file_type",
            SubXError::Other(_) => "other",
        }
    }

    /// Stable upper-snake-case machine code prefixed with `E_`.
    /// Mirrors [`Self::category`] one-to-one and is similarly closed
    /// against the addition of new variants.
    pub fn machine_code(&self) -> &'static str {
        match self {
            SubXError::Io(_) => "E_IO",
            SubXError::Config { .. } => "E_CONFIG",
            SubXError::SubtitleFormat { .. } => "E_SUBTITLE_FORMAT",
            SubXError::AiService(_) => "E_AI_SERVICE",
            SubXError::Api { .. } => "E_API",
            SubXError::AudioProcessing { .. } => "E_AUDIO_PROCESSING",
            SubXError::FileMatching { .. } => "E_FILE_MATCHING",
            SubXError::FileAlreadyExists(_) => "E_FILE_ALREADY_EXISTS",
            SubXError::FileNotFound(_) => "E_FILE_NOT_FOUND",
            SubXError::InvalidFileName(_) => "E_INVALID_FILE_NAME",
            SubXError::FileOperationFailed(_) => "E_FILE_OPERATION_FAILED",
            SubXError::CommandExecution(_) => "E_COMMAND_EXECUTION",
            SubXError::OutputModeUnsupported { .. } => "E_OUTPUT_MODE_UNSUPPORTED",
            SubXError::NoInputSpecified => "E_NO_INPUT_SPECIFIED",
            SubXError::InvalidPath(_) => "E_INVALID_PATH",
            SubXError::PathNotFound(_) => "E_PATH_NOT_FOUND",
            SubXError::DirectoryReadError { .. } => "E_DIRECTORY_READ_ERROR",
            SubXError::InvalidSyncConfiguration => "E_INVALID_SYNC_CONFIGURATION",
            SubXError::UnsupportedFileType(_) => "E_UNSUPPORTED_FILE_TYPE",
            SubXError::Other(_) => "E_OTHER",
        }
    }

    /// Short user-facing remediation hint, or `None` when none applies.
    ///
    /// This is a separate, structured surface from the prose hints
    /// already baked into [`Self::user_friendly_message`]; JSON callers
    /// receive it under `error.hint`.
    pub fn hint(&self) -> Option<&'static str> {
        match self {
            SubXError::Config { .. } => {
                Some("Run 'subx-cli config --help' for configuration details.")
            }
            SubXError::Api { .. } | SubXError::AiService(_) => {
                Some("Check network connectivity and the configured API key.")
            }
            SubXError::SubtitleFormat { .. } => {
                Some("Check the subtitle file's format and encoding.")
            }
            SubXError::AudioProcessing { .. } => {
                Some("Verify the media file's integrity and supported codecs.")
            }
            SubXError::FileMatching { .. } => Some("Verify file paths and patterns."),
            SubXError::NoInputSpecified => Some("Pass an input path or use the -i/--input flag."),
            SubXError::InvalidSyncConfiguration => {
                Some("Specify both video and subtitle files, or use -i for batch processing.")
            }
            SubXError::PathNotFound(_) | SubXError::FileNotFound(_) => {
                Some("Verify the path exists and is accessible.")
            }
            SubXError::OutputModeUnsupported { .. } => Some(
                "Run the command without `--output json` (and without SUBX_OUTPUT=json) to receive the shell-completion script.",
            ),
            _ => None,
        }
    }

    /// Return a user-friendly error message with suggested remedies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let msg = SubXError::config("missing key").user_friendly_message();
    /// assert!(msg.contains("Configuration error:"));
    /// ```
    pub fn user_friendly_message(&self) -> String {
        match self {
            SubXError::Io(e) => format!("File operation error: {}", e),
            SubXError::Config { message } => format!(
                "Configuration error: {}\nHint: run 'subx-cli config --help' for details",
                message
            ),
            SubXError::Api { message, source } => format!(
                "API error ({:?}): {}\nHint: check network connection and API key settings",
                source, message
            ),
            SubXError::AiService(msg) => format!(
                "AI service error: {}\nHint: check network connection and API key settings",
                msg
            ),
            SubXError::SubtitleFormat { message, .. } => format!(
                "Subtitle processing error: {}\nHint: check file format and encoding",
                message
            ),
            SubXError::AudioProcessing { message } => format!(
                "Audio processing error: {}\nHint: ensure media file integrity and support",
                message
            ),
            SubXError::FileMatching { message } => format!(
                "File matching error: {}\nHint: verify file paths and patterns",
                message
            ),
            SubXError::FileAlreadyExists(path) => format!("File already exists: {}", path),
            SubXError::FileNotFound(path) => format!("File not found: {}", path),
            SubXError::InvalidFileName(name) => format!("Invalid file name: {}", name),
            SubXError::FileOperationFailed(msg) => format!("File operation failed: {}", msg),
            SubXError::CommandExecution(msg) => msg.clone(),
            SubXError::OutputModeUnsupported { command } => format!(
                "The '{}' command does not support --output json; its stdout is a shell-completion script.\nHint: rerun without --output json (and ensure SUBX_OUTPUT is unset)",
                command
            ),
            SubXError::Other(err) => {
                format!("Unknown error: {}\nHint: please report this issue", err)
            }
            _ => format!("Error: {}", self),
        }
    }
}

/// Helper functions for Whisper API and audio processing related errors.
impl SubXError {
    /// Create a Whisper API error.
    ///
    /// # Arguments
    ///
    /// * `message` - The error message describing the Whisper API failure
    ///
    /// # Returns
    ///
    /// A new `SubXError::Api` variant with Whisper as the source
    pub fn whisper_api<T: Into<String>>(message: T) -> Self {
        Self::Api {
            message: message.into(),
            source: ApiErrorSource::Whisper,
        }
    }

    /// Create an audio extraction/transcoding error.
    ///
    /// # Arguments
    ///
    /// * `message` - The error message describing the audio processing failure
    ///
    /// # Returns
    ///
    /// A new `SubXError::AudioProcessing` variant
    pub fn audio_extraction<T: Into<String>>(message: T) -> Self {
        Self::AudioProcessing {
            message: message.into(),
        }
    }
}

/// API error source enumeration.
///
/// Specifies the source of API-related errors to help with error diagnosis
/// and handling.
#[derive(Debug, thiserror::Error)]
pub enum ApiErrorSource {
    /// OpenAI Whisper API
    #[error("OpenAI")]
    OpenAI,
    /// Whisper API
    #[error("Whisper")]
    Whisper,
}

// Support conversion from Box<dyn Error> to SubXError::AudioProcessing
impl From<Box<dyn std::error::Error>> for SubXError {
    fn from(err: Box<dyn std::error::Error>) -> Self {
        SubXError::audio_processing(err.to_string())
    }
}