aperture-cli 0.1.9

Dynamic CLI generator for OpenAPI specifications
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
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
//! Error handling module for Aperture CLI
//!
//! This module provides a consolidated error handling system that categorizes
//! all application errors into 9 distinct kinds. The design follows these principles:
//!
//! 1. **Error Consolidation**: All errors are mapped to one of 9 `ErrorKind` categories
//! 2. **Structured Context**: Each error can include structured JSON details and suggestions
//! 3. **Builder Pattern**: `ErrorContext` provides fluent builder methods for error construction
//! 4. **JSON Support**: All errors can be serialized to JSON for programmatic consumption

use crate::constants;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::borrow::Cow;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    // Keep essential external errors that can't be consolidated
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Network error: {0}")]
    Network(#[from] reqwest::Error),
    #[error("YAML parsing error: {0}")]
    Yaml(#[from] serde_yaml::Error),
    #[error("JSON parsing error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("TOML parsing error: {0}")]
    Toml(#[from] toml::de::Error),

    // Consolidated error variant using new infrastructure
    #[error("{kind}: {message}")]
    Internal {
        kind: ErrorKind,
        message: Cow<'static, str>,
        context: Option<ErrorContext>,
    },

    #[error(transparent)]
    Anyhow(#[from] anyhow::Error),
}

/// Error categories for consolidated error handling
///
/// This enum represents the 8 primary error categories used throughout
/// the application. All internal errors are mapped to one of these categories
/// to provide consistent error handling and reporting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
    /// Specification-related errors (not found, already exists, cache issues)
    Specification,
    /// Authentication and authorization errors
    Authentication,
    /// Input validation and configuration errors
    Validation,
    /// Network connectivity and transport errors (connection, DNS, timeouts)
    Network,
    /// HTTP request/response errors (status codes, API errors)
    HttpRequest,
    /// Header processing errors
    Headers,
    /// Interactive input errors
    Interactive,
    /// Server variable resolution errors
    ServerVariable,
    /// Runtime operation errors
    Runtime,
}

/// Additional context for consolidated errors
#[derive(Debug, Clone)]
pub struct ErrorContext {
    /// Structured details for programmatic access
    pub details: Option<serde_json::Value>,
    /// Human-readable suggestion for resolving the error
    pub suggestion: Option<Cow<'static, str>>,
}

impl ErrorContext {
    /// Create a new error context with details and suggestion
    #[must_use]
    pub const fn new(
        details: Option<serde_json::Value>,
        suggestion: Option<Cow<'static, str>>,
    ) -> Self {
        Self {
            details,
            suggestion,
        }
    }

    /// Create error context with only details
    #[must_use]
    pub const fn with_details(details: serde_json::Value) -> Self {
        Self {
            details: Some(details),
            suggestion: None,
        }
    }

    /// Create error context with only suggestion
    #[must_use]
    pub const fn with_suggestion(suggestion: Cow<'static, str>) -> Self {
        Self {
            details: None,
            suggestion: Some(suggestion),
        }
    }

    /// Builder method to add a single detail field
    #[must_use]
    pub fn with_detail(key: &str, value: impl serde::Serialize) -> Self {
        Self {
            details: Some(json!({ key: value })),
            suggestion: None,
        }
    }

    /// Builder method to add name and reason details
    #[must_use]
    pub fn with_name_reason(name_field: &str, name: &str, reason: &str) -> Self {
        Self {
            details: Some(json!({ name_field: name, "reason": reason })),
            suggestion: None,
        }
    }

    /// Add suggestion to existing context
    #[must_use]
    pub fn and_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(Cow::Owned(suggestion.into()));
        self
    }
}

impl ErrorKind {
    /// Get the string identifier for this error kind
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Specification => "Specification",
            Self::Authentication => "Authentication",
            Self::Validation => "Validation",
            Self::Network => "Network",
            Self::HttpRequest => "HttpError",
            Self::Headers => "Headers",
            Self::Interactive => "Interactive",
            Self::ServerVariable => "ServerVariable",
            Self::Runtime => "Runtime",
        }
    }
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// JSON representation of an error for structured output
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonError {
    pub error_type: Cow<'static, str>,
    pub message: String,
    pub context: Option<Cow<'static, str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

impl Error {
    /// Add context to an error for better user messaging
    #[must_use]
    pub fn with_context(self, context: &str) -> Self {
        match self {
            Self::Network(e) => Self::invalid_config(format!("{context}: {e}")),
            Self::Io(e) => Self::invalid_config(format!("{context}: {e}")),
            Self::Internal {
                kind,
                message,
                context: ctx,
            } => Self::Internal {
                kind,
                message: Cow::Owned(format!("{context}: {message}")),
                context: ctx,
            },
            _ => self,
        }
    }

    /// Add operation context to an error for better debugging
    #[must_use]
    pub fn with_operation_context(self, operation: &str, api: &str) -> Self {
        match self {
            Self::Internal {
                kind,
                message,
                context,
            } => Self::Internal {
                kind,
                message: Cow::Owned(format!("Operation '{operation}' on API '{api}': {message}")),
                context,
            },
            Self::Network(e) => {
                Self::invalid_config(format!("Operation '{operation}' on API '{api}': {e}"))
            }
            _ => self,
        }
    }

    /// Add suggestions to error messages for better user guidance
    #[must_use]
    pub fn with_suggestion(self, suggestion: &str) -> Self {
        match self {
            Self::Internal {
                kind,
                message,
                context,
            } => Self::Internal {
                kind,
                message,
                context: context.map_or_else(
                    || {
                        Some(ErrorContext::with_suggestion(Cow::Owned(
                            suggestion.to_string(),
                        )))
                    },
                    |mut ctx| {
                        ctx.suggestion = Some(Cow::Owned(suggestion.to_string()));
                        Some(ctx)
                    },
                ),
            },
            _ => self,
        }
    }

    /// Convert error to JSON representation for structured output
    #[must_use]
    pub fn to_json(&self) -> JsonError {
        let (error_type, message, context, details): (
            &str,
            String,
            Option<Cow<'static, str>>,
            Option<serde_json::Value>,
        ) = match self {
            Self::Io(io_err) => {
                let context = match io_err.kind() {
                    std::io::ErrorKind::NotFound => {
                        Some(Cow::Borrowed(constants::ERR_FILE_NOT_FOUND))
                    }
                    std::io::ErrorKind::PermissionDenied => {
                        Some(Cow::Borrowed(constants::ERR_PERMISSION))
                    }
                    _ => None,
                };
                ("FileSystem", io_err.to_string(), context, None)
            }
            Self::Network(req_err) => {
                let context = match () {
                    () if req_err.is_connect() => Some(Cow::Borrowed(constants::ERR_CONNECTION)),
                    () if req_err.is_timeout() => Some(Cow::Borrowed(constants::ERR_TIMEOUT)),
                    () if req_err.is_status() => {
                        req_err.status().and_then(|status| match status.as_u16() {
                            401 => Some(Cow::Borrowed(constants::ERR_API_CREDENTIALS)),
                            403 => Some(Cow::Borrowed(constants::ERR_PERMISSION_DENIED)),
                            404 => Some(Cow::Borrowed(constants::ERR_ENDPOINT_NOT_FOUND)),
                            429 => Some(Cow::Borrowed(constants::ERR_RATE_LIMITED)),
                            500..=599 => Some(Cow::Borrowed(constants::ERR_SERVER_ERROR)),
                            _ => None,
                        })
                    }
                    () => None,
                };
                ("Network", req_err.to_string(), context, None)
            }
            Self::Yaml(yaml_err) => (
                "YAMLParsing",
                yaml_err.to_string(),
                Some(Cow::Borrowed(constants::ERR_YAML_SYNTAX)),
                None,
            ),
            Self::Json(json_err) => (
                "JSONParsing",
                json_err.to_string(),
                Some(Cow::Borrowed(constants::ERR_JSON_SYNTAX)),
                None,
            ),
            Self::Toml(toml_err) => (
                "TOMLParsing",
                toml_err.to_string(),
                Some(Cow::Borrowed(constants::ERR_TOML_SYNTAX)),
                None,
            ),
            Self::Internal {
                kind,
                message,
                context: ctx,
            } => {
                let context = ctx.as_ref().and_then(|c| c.suggestion.clone());
                let details = ctx.as_ref().and_then(|c| c.details.clone());
                (kind.as_str(), message.to_string(), context, details)
            }
            Self::Anyhow(anyhow_err) => ("Unknown", anyhow_err.to_string(), None, None),
        };

        JsonError {
            error_type: Cow::Borrowed(error_type),
            message,
            context,
            details,
        }
    }
}

impl Error {
    /// Create a specification not found error
    pub fn spec_not_found(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!("API specification '{name}' not found")),
            context: Some(
                ErrorContext::with_detail("spec_name", &name)
                    .and_suggestion(constants::MSG_USE_CONFIG_LIST),
            ),
        }
    }

    /// Create a specification already exists error
    pub fn spec_already_exists(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!(
                "API specification '{name}' already exists. Use --force to overwrite"
            )),
            context: Some(ErrorContext::with_detail("spec_name", &name)),
        }
    }

    /// Create a cache stale error when the spec file has been modified since caching
    pub fn cache_stale(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!(
                "Cache for '{name}' is stale — the spec file has been modified since it was cached"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "spec_name": name })),
                Some(Cow::Owned(format!(
                    "Run 'aperture config reinit {name}' to regenerate the cache."
                ))),
            )),
        }
    }

    /// Create a cached spec not found error
    pub fn cached_spec_not_found(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!(
                "No cached spec found for '{name}'. Run 'aperture config add {name}' first"
            )),
            context: Some(ErrorContext::with_detail("spec_name", &name)),
        }
    }

    /// Create a cached spec corrupted error
    pub fn cached_spec_corrupted(name: impl Into<String>, reason: impl Into<String>) -> Self {
        let name = name.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!(
                "Failed to deserialize cached spec '{name}': {reason}. The cache may be corrupted"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "spec_name": name, "corruption_reason": reason })),
                Some(Cow::Borrowed(
                    "Try removing and re-adding the specification.",
                )),
            )),
        }
    }

    /// Create a cache version mismatch error
    pub fn cache_version_mismatch(name: impl Into<String>, found: u32, expected: u32) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Specification,
            message: Cow::Owned(format!(
                "Cache format version mismatch for '{name}': found v{found}, expected v{expected}"
            )),
            context: Some(ErrorContext::new(
                Some(
                    json!({ "spec_name": name, "found_version": found, "expected_version": expected }),
                ),
                Some(Cow::Borrowed(
                    "Run 'aperture config reinit' to regenerate the cache.",
                )),
            )),
        }
    }

    /// Create a secret not set error
    pub fn secret_not_set(scheme_name: impl Into<String>, env_var: impl Into<String>) -> Self {
        let scheme_name = scheme_name.into();
        let env_var = env_var.into();
        let suggestion = crate::suggestions::suggest_auth_fix(&scheme_name, Some(&env_var));
        Self::Internal {
            kind: ErrorKind::Authentication,
            message: Cow::Owned(format!(
                "Environment variable '{env_var}' required for authentication '{scheme_name}' is not set"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "scheme_name": scheme_name, "env_var": env_var })),
                Some(Cow::Owned(suggestion)),
            )),
        }
    }

    /// Create an unsupported auth scheme error
    pub fn unsupported_auth_scheme(scheme: impl Into<String>) -> Self {
        let scheme = scheme.into();
        Self::Internal {
            kind: ErrorKind::Authentication,
            message: Cow::Owned(format!("Unsupported HTTP authentication scheme: {scheme}")),
            context: Some(ErrorContext::new(
                Some(json!({ "scheme": scheme })),
                Some(Cow::Borrowed(
                    "Only 'bearer' and 'basic' schemes are supported.",
                )),
            )),
        }
    }

    /// Create an unsupported security scheme error
    pub fn unsupported_security_scheme(scheme_type: impl Into<String>) -> Self {
        let scheme_type = scheme_type.into();
        Self::Internal {
            kind: ErrorKind::Authentication,
            message: Cow::Owned(format!("Unsupported security scheme type: {scheme_type}")),
            context: Some(ErrorContext::new(
                Some(json!({ "scheme_type": scheme_type })),
                Some(Cow::Borrowed(
                    "Only 'apiKey' and 'http' security schemes are supported.",
                )),
            )),
        }
    }

    /// Create a generic validation error
    pub fn validation_error(message: impl Into<String>) -> Self {
        let message = message.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Validation error: {message}")),
            context: None,
        }
    }

    /// Create an invalid configuration error
    pub fn invalid_config(reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Invalid configuration: {reason}")),
            context: Some(
                ErrorContext::with_detail("reason", &reason)
                    .and_suggestion("Check the configuration file syntax and structure."),
            ),
        }
    }

    /// Create an invalid JSON body error
    pub fn invalid_json_body(reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Invalid JSON body: {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "reason": reason })),
                Some(Cow::Borrowed(
                    "Check that the JSON body is properly formatted.",
                )),
            )),
        }
    }

    /// Create an invalid path error
    pub fn invalid_path(path: impl Into<String>, reason: impl Into<String>) -> Self {
        let path = path.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Invalid path '{path}': {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "path": path, "reason": reason })),
                Some(Cow::Borrowed("Check the path format and ensure it exists.")),
            )),
        }
    }

    /// Create a request failed error
    pub fn request_failed(status: reqwest::StatusCode, reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::HttpRequest,
            message: Cow::Owned(format!("Request failed with status {status}: {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "status_code": status.as_u16(), "reason": reason })),
                Some(Cow::Borrowed(
                    "Check the API endpoint, parameters, and authentication.",
                )),
            )),
        }
    }

    /// Create a response read error
    pub fn response_read_error(reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::HttpRequest,
            message: Cow::Owned(format!("Failed to read response: {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "reason": reason })),
                Some(Cow::Borrowed(
                    "Check network connectivity and server status.",
                )),
            )),
        }
    }

    /// Create an invalid HTTP method error
    pub fn invalid_http_method(method: impl Into<String>) -> Self {
        let method = method.into();
        Self::Internal {
            kind: ErrorKind::HttpRequest,
            message: Cow::Owned(format!("Invalid HTTP method: {method}")),
            context: Some(ErrorContext::new(
                Some(json!({ "method": method })),
                Some(Cow::Borrowed(
                    "Valid HTTP methods are: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS.",
                )),
            )),
        }
    }

    // ---- Header Errors ----

    /// Create an invalid header name error
    pub fn invalid_header_name(name: impl Into<String>, reason: impl Into<String>) -> Self {
        let name = name.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Headers,
            message: Cow::Owned(format!("Invalid header name '{name}': {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "header_name": name, "reason": reason })),
                Some(Cow::Borrowed(
                    "Header names must contain only valid HTTP header characters.",
                )),
            )),
        }
    }

    /// Create an invalid header value error
    pub fn invalid_header_value(name: impl Into<String>, reason: impl Into<String>) -> Self {
        let name = name.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Headers,
            message: Cow::Owned(format!("Invalid header value for '{name}': {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "header_name": name, "reason": reason })),
                Some(Cow::Borrowed(
                    "Header values must contain only valid HTTP header characters.",
                )),
            )),
        }
    }

    /// Create an invalid header format error
    pub fn invalid_header_format(header: impl Into<String>) -> Self {
        let header = header.into();
        Self::Internal {
            kind: ErrorKind::Headers,
            message: Cow::Owned(format!(
                "Invalid header format '{header}'. Expected 'Name: Value'"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "header": header })),
                Some(Cow::Borrowed("Headers must be in 'Name: Value' format.")),
            )),
        }
    }

    /// Create an empty header name error
    #[must_use]
    pub const fn empty_header_name() -> Self {
        Self::Internal {
            kind: ErrorKind::Headers,
            message: Cow::Borrowed("Header name cannot be empty"),
            context: Some(ErrorContext::with_suggestion(Cow::Borrowed(
                "Provide a valid header name before the colon.",
            ))),
        }
    }

    // ---- Interactive Errors ----

    /// Create an interactive input too long error
    #[must_use]
    pub fn interactive_input_too_long(max_length: usize) -> Self {
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Owned(format!("Input too long (maximum {max_length} characters)")),
            context: Some(
                ErrorContext::with_detail("max_length", max_length)
                    .and_suggestion("Please provide a shorter input."),
            ),
        }
    }

    /// Create an interactive invalid characters error
    pub fn interactive_invalid_characters(
        invalid_chars: impl Into<String>,
        suggestion: impl Into<String>,
    ) -> Self {
        let invalid_chars = invalid_chars.into();
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Owned(format!("Invalid characters found: {invalid_chars}")),
            context: Some(ErrorContext::new(
                Some(json!({ "invalid_characters": invalid_chars })),
                Some(Cow::Owned(suggestion.into())),
            )),
        }
    }

    /// Create an interactive timeout error
    #[must_use]
    pub const fn interactive_timeout() -> Self {
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Borrowed("Input timeout - no response received"),
            context: Some(ErrorContext::with_suggestion(Cow::Borrowed(
                "Please respond within the timeout period.",
            ))),
        }
    }

    /// Create an interactive retries exhausted error
    pub fn interactive_retries_exhausted(
        max_retries: usize,
        last_error: impl Into<String>,
        suggestions: &[String],
    ) -> Self {
        let last_error = last_error.into();
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Owned(format!(
                "Maximum retry attempts ({max_retries}) exceeded: {last_error}"
            )),
            context: Some(ErrorContext::new(
                Some(
                    json!({ "max_attempts": max_retries, "last_error": last_error, "suggestions": suggestions }),
                ),
                Some(Cow::Owned(format!(
                    "Suggestions: {}",
                    suggestions.join("; ")
                ))),
            )),
        }
    }

    // ---- Server Variable Errors ----

    /// Create a missing server variable error
    pub fn missing_server_variable(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::ServerVariable,
            message: Cow::Owned(format!("Required server variable '{name}' is not provided")),
            context: Some(
                ErrorContext::with_detail("variable_name", &name).and_suggestion(format!(
                    "Provide the variable with --server-var {name}=<value>"
                )),
            ),
        }
    }

    /// Create an unknown server variable error
    pub fn unknown_server_variable(name: impl Into<String>, available: &[String]) -> Self {
        let name = name.into();
        let available_list = available.join(", ");
        Self::Internal {
            kind: ErrorKind::ServerVariable,
            message: Cow::Owned(format!(
                "Unknown server variable '{name}'. Available variables: {available_list}"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "variable_name": name, "available_variables": available })),
                Some(Cow::Owned(format!("Use one of: {available_list}"))),
            )),
        }
    }

    /// Create an unresolved template variable error
    pub fn unresolved_template_variable(name: impl Into<String>, url: impl Into<String>) -> Self {
        let name = name.into();
        let url = url.into();
        Self::Internal {
            kind: ErrorKind::ServerVariable,
            message: Cow::Owned(format!(
                "Unresolved template variable '{name}' in URL '{url}'"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "variable_name": name, "template_url": url })),
                Some(Cow::Borrowed(
                    "Ensure all template variables are provided with --server-var",
                )),
            )),
        }
    }

    /// Create an invalid environment variable name error with suggestion
    pub fn invalid_environment_variable_name(
        name: impl Into<String>,
        reason: impl Into<String>,
        suggestion: impl Into<String>,
    ) -> Self {
        let name = name.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Owned(format!(
                "Invalid environment variable name '{name}': {reason}"
            )),
            context: Some(
                ErrorContext::with_name_reason("variable_name", &name, &reason)
                    .and_suggestion(suggestion),
            ),
        }
    }

    /// Create an invalid server variable format error
    pub fn invalid_server_var_format(arg: impl Into<String>, reason: impl Into<String>) -> Self {
        let arg = arg.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::ServerVariable,
            message: Cow::Owned(format!(
                "Invalid server variable format in '{arg}': {reason}"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "argument": arg, "reason": reason })),
                Some(Cow::Borrowed(
                    "Server variables must be in 'key=value' format.",
                )),
            )),
        }
    }

    /// Create an invalid server variable value error
    pub fn invalid_server_var_value(
        name: impl Into<String>,
        value: impl Into<String>,
        allowed_values: &[String],
    ) -> Self {
        let name = name.into();
        let value = value.into();
        Self::Internal {
            kind: ErrorKind::ServerVariable,
            message: Cow::Owned(format!(
                "Invalid value '{value}' for server variable '{name}'"
            )),
            context: Some(ErrorContext::new(
                Some(
                    json!({ "variable_name": name, "provided_value": value, "allowed_values": allowed_values }),
                ),
                Some(Cow::Owned(format!(
                    "Allowed values: {}",
                    allowed_values.join(", ")
                ))),
            )),
        }
    }

    // ---- Runtime Errors ----

    /// Create an operation not found error
    pub fn operation_not_found(operation: impl Into<String>) -> Self {
        let operation = operation.into();
        Self::Internal {
            kind: ErrorKind::Runtime,
            message: Cow::Owned(format!("Operation '{operation}' not found")),
            context: Some(ErrorContext::new(
                Some(json!({ "operation": operation })),
                Some(Cow::Borrowed(
                    "Check available operations with --help or --describe-json",
                )),
            )),
        }
    }

    /// Create an operation not found error with suggestions
    pub fn operation_not_found_with_suggestions(
        operation: impl Into<String>,
        suggestions: &[String],
    ) -> Self {
        let operation = operation.into();
        let suggestion_text = if suggestions.is_empty() {
            "Check available operations with --help or --describe-json".to_string()
        } else {
            format!("Did you mean one of these?\n{}", suggestions.join("\n"))
        };

        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Operation '{operation}' not found")),
            context: Some(ErrorContext::new(
                Some(json!({
                    "operation": operation,
                    "suggestions": suggestions
                })),
                Some(Cow::Owned(suggestion_text)),
            )),
        }
    }

    /// Create a network request failed error
    pub fn network_request_failed(reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Network,
            message: Cow::Owned(format!("Network request failed: {reason}")),
            context: Some(
                ErrorContext::with_detail("reason", &reason)
                    .and_suggestion("Check network connectivity and URL validity"),
            ),
        }
    }

    /// Create a serialization error
    pub fn serialization_error(reason: impl Into<String>) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Serialization failed: {reason}")),
            context: Some(
                ErrorContext::with_detail("reason", &reason)
                    .and_suggestion("Check data structure validity"),
            ),
        }
    }

    /// Create a home directory not found error
    #[must_use]
    pub fn home_directory_not_found() -> Self {
        Self::Internal {
            kind: ErrorKind::Runtime,
            message: Cow::Borrowed("Home directory not found"),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({})),
                Some(Cow::Borrowed("Ensure HOME environment variable is set")),
            )),
        }
    }

    /// Create an invalid command error
    pub fn invalid_command(context: impl Into<String>, reason: impl Into<String>) -> Self {
        let context = context.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Invalid command for '{context}': {reason}")),
            context: Some(
                ErrorContext::with_name_reason("context", &context, &reason)
                    .and_suggestion("Check available commands with --help or --describe-json"),
            ),
        }
    }

    /// Create an HTTP error with context
    pub fn http_error_with_context(
        status: u16,
        body: impl Into<String>,
        api_name: impl Into<String>,
        operation_id: Option<impl Into<String>>,
        security_schemes: &[String],
    ) -> Self {
        let body = body.into();
        let api_name = api_name.into();
        let operation_id = operation_id.map(std::convert::Into::into);

        // Include important parts of response body in message for backward compatibility
        let message = if body.len() <= 200 && !body.is_empty() {
            format!("HTTP {status} error for '{api_name}': {body}")
        } else {
            format!("HTTP {status} error for '{api_name}'")
        };

        Self::Internal {
            kind: ErrorKind::HttpRequest,
            message: Cow::Owned(message),
            context: Some(ErrorContext::new(
                Some(json!({
                    "status": status,
                    "response_body": body,
                    "api_name": api_name,
                    "operation_id": operation_id,
                    "security_schemes": security_schemes
                })),
                Some(Cow::Borrowed(
                    "Check the API endpoint, parameters, and authentication.",
                )),
            )),
        }
    }

    /// Create a JQ filter error
    pub fn jq_filter_error(filter: impl Into<String>, reason: impl Into<String>) -> Self {
        let filter = filter.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("JQ filter error in '{filter}': {reason}")),
            context: Some(
                ErrorContext::with_name_reason("filter", &filter, &reason)
                    .and_suggestion("Check JQ filter syntax and data structure compatibility"),
            ),
        }
    }

    /// Create a transient network error
    pub fn transient_network_error(reason: impl Into<String>, retryable: bool) -> Self {
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Network,
            message: Cow::Owned(format!("Transient network error: {reason}")),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({
                    "reason": reason,
                    "retryable": retryable
                })),
                Some(Cow::Borrowed(if retryable {
                    "This error may be temporary and could succeed on retry"
                } else {
                    "This error is not retryable"
                })),
            )),
        }
    }

    /// Create a retry limit exceeded error
    pub fn retry_limit_exceeded(max_attempts: u32, last_error: impl Into<String>) -> Self {
        let last_error = last_error.into();
        Self::Internal {
            kind: ErrorKind::Network,
            message: Cow::Owned(format!(
                "Retry limit exceeded after {max_attempts} attempts: {last_error}"
            )),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({
                    "max_attempts": max_attempts,
                    "last_error": last_error
                })),
                Some(Cow::Borrowed(
                    "Consider checking network connectivity or increasing retry limits",
                )),
            )),
        }
    }

    /// Create a retry limit exceeded error with detailed retry information
    #[allow(clippy::too_many_arguments)]
    pub fn retry_limit_exceeded_detailed(
        max_attempts: u32,
        attempts_made: u32,
        last_error: impl Into<String>,
        initial_delay_ms: u64,
        max_delay_ms: u64,
        last_status_code: Option<u16>,
        operation_id: impl Into<String>,
    ) -> Self {
        let last_error = last_error.into();
        let operation_id = operation_id.into();
        Self::Internal {
            kind: ErrorKind::Network,
            message: Cow::Owned(format!(
                "Retry limit exceeded after {attempts_made}/{max_attempts} attempts for {operation_id}: {last_error}"
            )),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({
                    "retry_info": {
                        "max_attempts": max_attempts,
                        "attempts_made": attempts_made,
                        "initial_delay_ms": initial_delay_ms,
                        "max_delay_ms": max_delay_ms,
                        "last_status_code": last_status_code,
                        "operation_id": operation_id
                    },
                    "last_error": last_error
                })),
                Some(Cow::Borrowed(
                    "Consider checking network connectivity, API availability, or increasing retry limits",
                )),
            )),
        }
    }

    /// Create a request timeout error
    #[must_use]
    pub fn request_timeout(timeout_seconds: u64) -> Self {
        Self::Internal {
            kind: ErrorKind::Network,
            message: Cow::Owned(format!("Request timed out after {timeout_seconds} seconds")),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({
                    "timeout_seconds": timeout_seconds
                })),
                Some(Cow::Borrowed(
                    "Consider increasing the timeout or checking network connectivity",
                )),
            )),
        }
    }

    /// Create a missing path parameter error
    pub fn missing_path_parameter(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Missing required path parameter: {name}")),
            context: Some(
                ErrorContext::with_detail("parameter_name", &name)
                    .and_suggestion("Provide a value for this required path parameter"),
            ),
        }
    }

    /// Create a general I/O error
    pub fn io_error(message: impl Into<String>) -> Self {
        let message = message.into();
        Self::Internal {
            kind: ErrorKind::Runtime,
            message: Cow::Owned(message),
            context: None,
        }
    }

    /// Create an invalid idempotency key error
    #[must_use]
    pub const fn invalid_idempotency_key() -> Self {
        Self::Internal {
            kind: ErrorKind::Headers,
            message: Cow::Borrowed("Invalid idempotency key format"),
            context: Some(ErrorContext::new(
                None,
                Some(Cow::Borrowed(
                    "Ensure the idempotency key contains only valid header characters",
                )),
            )),
        }
    }

    /// Create an editor not set error
    #[must_use]
    pub const fn editor_not_set() -> Self {
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Borrowed("EDITOR environment variable not set"),
            context: Some(ErrorContext::new(
                None,
                Some(Cow::Borrowed(
                    "Set your preferred editor: export EDITOR=vim",
                )),
            )),
        }
    }

    /// Create an editor failed error
    pub fn editor_failed(name: impl Into<String>) -> Self {
        let name = name.into();
        Self::Internal {
            kind: ErrorKind::Interactive,
            message: Cow::Owned(format!("Editor '{name}' failed to complete")),
            context: Some(ErrorContext::new(
                Some(serde_json::json!({ "editor": name })),
                Some(Cow::Borrowed(
                    "Check if the editor is properly installed and configured",
                )),
            )),
        }
    }

    // ---- API Context Name Errors ----

    /// Create an invalid API context name error
    pub fn invalid_api_context_name(name: impl Into<String>, reason: impl Into<String>) -> Self {
        let name = name.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Invalid API context name '{name}': {reason}")),
            context: Some(ErrorContext::new(
                Some(json!({ "name": name, "reason": reason })),
                Some(Cow::Borrowed(
                    "API names must start with a letter or digit and contain only letters, digits, dots, hyphens, or underscores (max 64 chars).",
                )),
            )),
        }
    }

    // ---- Settings Errors ----

    /// Create an unknown setting key error
    pub fn unknown_setting_key(key: impl Into<String>) -> Self {
        let key = key.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!("Unknown setting key: '{key}'")),
            context: Some(ErrorContext::new(
                Some(json!({ "key": key })),
                Some(Cow::Borrowed(
                    "Run 'aperture config settings' to see available settings.",
                )),
            )),
        }
    }

    /// Create an invalid setting value error
    pub fn invalid_setting_value(
        key: crate::config::settings::SettingKey,
        value: impl Into<String>,
    ) -> Self {
        let value = value.into();
        let expected_type = key.type_name();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Invalid value for '{key}': expected {expected_type}, got '{value}'"
            )),
            context: Some(ErrorContext::new(
                Some(json!({
                    "key": key.as_str(),
                    "value": value,
                    "expected_type": expected_type
                })),
                Some(Cow::Owned(format!(
                    "Provide a valid {expected_type} value for this setting."
                ))),
            )),
        }
    }

    /// Create a setting value out of range error
    pub fn setting_value_out_of_range(
        key: crate::config::settings::SettingKey,
        value: impl Into<String>,
        reason: &str,
    ) -> Self {
        let value = value.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Value '{value}' out of range for '{key}': {reason}"
            )),
            context: Some(ErrorContext::new(
                Some(json!({
                    "key": key.as_str(),
                    "value": value,
                    "reason": reason
                })),
                Some(Cow::Owned(format!(
                    "Provide a value within the valid range: {reason}"
                ))),
            )),
        }
    }

    // ---- Batch Dependency Errors ----

    /// Create a batch dependency cycle detected error
    #[must_use]
    pub fn batch_cycle_detected(cycle: &[String]) -> Self {
        let cycle_str = cycle.join("");
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Dependency cycle detected in batch operations: {cycle_str}"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "cycle": cycle })),
                Some(Cow::Borrowed(
                    "Remove circular dependencies between batch operations.",
                )),
            )),
        }
    }

    /// Create a batch missing dependency reference error
    pub fn batch_missing_dependency(
        operation_id: impl Into<String>,
        missing_dep: impl Into<String>,
    ) -> Self {
        let operation_id = operation_id.into();
        let missing_dep = missing_dep.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Operation '{operation_id}' depends on '{missing_dep}' which does not exist"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "operation_id": operation_id, "missing_dependency": missing_dep })),
                Some(Cow::Borrowed(
                    "Check that the depends_on references match existing operation ids.",
                )),
            )),
        }
    }

    /// Create a batch undefined variable error
    pub fn batch_undefined_variable(
        operation_id: impl Into<String>,
        variable: impl Into<String>,
    ) -> Self {
        let operation_id = operation_id.into();
        let variable = variable.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Operation '{operation_id}' references undefined variable '{{{{{variable}}}}}'"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "operation_id": operation_id, "variable": variable })),
                Some(Cow::Borrowed(
                    "Ensure the variable is captured by a preceding operation.",
                )),
            )),
        }
    }

    /// Create a batch capture failed error
    pub fn batch_capture_failed(
        operation_id: impl Into<String>,
        variable: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        let operation_id = operation_id.into();
        let variable = variable.into();
        let reason = reason.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Failed to capture variable '{variable}' from operation '{operation_id}': {reason}"
            )),
            context: Some(ErrorContext::new(
                Some(
                    json!({ "operation_id": operation_id, "variable": variable, "reason": reason }),
                ),
                Some(Cow::Borrowed(
                    "Check the JQ query and ensure the response contains the expected data.",
                )),
            )),
        }
    }

    /// Create a batch operation missing id error
    pub fn batch_missing_id(context: impl Into<String>) -> Self {
        let context = context.into();
        Self::Internal {
            kind: ErrorKind::Validation,
            message: Cow::Owned(format!(
                "Batch operation requires an id: {context}"
            )),
            context: Some(ErrorContext::new(
                Some(json!({ "context": context })),
                Some(Cow::Borrowed(
                    "Add an 'id' field to operations that use capture, capture_append, or depends_on.",
                )),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // ---- Internal ErrorKind variants via to_json() ----

    #[test]
    fn test_to_json_specification_kind() {
        let err = Error::spec_not_found("my-api");
        let j = err.to_json();
        assert_eq!(j.error_type, "Specification");
        assert!(j.message.contains("my-api"));
        assert!(j.context.is_some(), "spec_not_found carries a suggestion");
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_specification_cache_stale() {
        let err = Error::cache_stale("stale-api");
        let j = err.to_json();
        assert_eq!(j.error_type, "Specification");
        assert!(j.message.contains("stale-api"));
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_authentication_secret_not_set() {
        let err = Error::secret_not_set("api-key", "MY_API_KEY");
        let j = err.to_json();
        assert_eq!(j.error_type, "Authentication");
        assert!(j.message.contains("MY_API_KEY"));
        assert!(j.context.is_some(), "secret_not_set carries a suggestion");
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_authentication_unsupported_scheme() {
        let err = Error::unsupported_auth_scheme("digest");
        let j = err.to_json();
        assert_eq!(j.error_type, "Authentication");
        assert!(j.message.contains("digest"));
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_validation_kind() {
        let err = Error::invalid_config("bad value");
        let j = err.to_json();
        assert_eq!(j.error_type, "Validation");
        assert!(j.message.contains("bad value"));
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_network_internal_kind() {
        // ErrorKind::Network (internal) is produced by retry_limit_exceeded.
        let err = Error::retry_limit_exceeded(3, "connection refused");
        let j = err.to_json();
        assert_eq!(j.error_type, "Network");
        assert!(
            j.context.is_some(),
            "retry_limit_exceeded carries a suggestion"
        );
    }

    #[test]
    fn test_to_json_http_request_kind() {
        let err = Error::request_failed(reqwest::StatusCode::UNPROCESSABLE_ENTITY, "bad body");
        let j = err.to_json();
        assert_eq!(j.error_type, "HttpError");
        assert!(j.message.contains("422") || j.message.contains("Unprocessable"));
        assert!(j.message.contains("bad body"));
        assert!(j.context.is_some());
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_headers_invalid_header_name() {
        let err = Error::invalid_header_name("X-Bad\0Header", "contains NUL");
        let j = err.to_json();
        assert_eq!(j.error_type, "Headers");
        assert!(j.context.is_some(), "header errors carry suggestions");
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_headers_empty_header_name() {
        let err = Error::empty_header_name();
        let j = err.to_json();
        assert_eq!(j.error_type, "Headers");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_headers_invalid_idempotency_key() {
        let err = Error::invalid_idempotency_key();
        let j = err.to_json();
        assert_eq!(j.error_type, "Headers");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_interactive_timeout() {
        let err = Error::interactive_timeout();
        let j = err.to_json();
        assert_eq!(j.error_type, "Interactive");
        assert!(j.context.is_some(), "interactive errors carry suggestions");
    }

    #[test]
    fn test_to_json_interactive_input_too_long() {
        let err = Error::interactive_input_too_long(256);
        let j = err.to_json();
        assert_eq!(j.error_type, "Interactive");
        assert!(j.context.is_some());
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_interactive_editor_not_set() {
        let err = Error::editor_not_set();
        let j = err.to_json();
        assert_eq!(j.error_type, "Interactive");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_server_variable_missing() {
        let err = Error::missing_server_variable("region");
        let j = err.to_json();
        assert_eq!(j.error_type, "ServerVariable");
        assert!(j.message.contains("region"));
        assert!(
            j.context.is_some(),
            "server variable errors carry suggestions"
        );
        assert!(j.details.is_some());
    }

    #[test]
    fn test_to_json_server_variable_unresolved_template() {
        let err = Error::unresolved_template_variable("env", "https://api.{env}.example.com");
        let j = err.to_json();
        assert_eq!(j.error_type, "ServerVariable");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_runtime_kind() {
        let err = Error::operation_not_found("unknown-op");
        let j = err.to_json();
        assert_eq!(j.error_type, "Runtime");
        assert!(j.message.contains("unknown-op"));
        assert!(j.context.is_some());
    }

    // ---- External error variants via to_json() ----

    #[test]
    fn test_to_json_io_not_found() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
        let err = Error::Io(io_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "FileSystem");
        assert!(j.context.is_some(), "NotFound carries a suggestion");
    }

    #[test]
    fn test_to_json_io_permission_denied() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let err = Error::Io(io_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "FileSystem");
        assert!(j.context.is_some(), "PermissionDenied carries a suggestion");
    }

    #[test]
    fn test_to_json_io_other_kind() {
        let io_err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "broken pipe");
        let err = Error::Io(io_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "FileSystem");
        assert!(j.context.is_none(), "generic IO kind carries no suggestion");
    }

    #[test]
    fn test_to_json_yaml_error() {
        let yaml_err = serde_yaml::from_str::<serde_yaml::Value>("key: - value").unwrap_err();
        let err = Error::Yaml(yaml_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "YAMLParsing");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_json_error() {
        let json_err = serde_json::from_str::<serde_json::Value>("{bad").unwrap_err();
        let err = Error::Json(json_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "JSONParsing");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_toml_error() {
        let toml_err = toml::from_str::<toml::Value>("key = ").unwrap_err();
        let err = Error::Toml(toml_err);
        let j = err.to_json();
        assert_eq!(j.error_type, "TOMLParsing");
        assert!(j.context.is_some());
    }

    #[test]
    fn test_to_json_anyhow_error() {
        let err = Error::Anyhow(anyhow::anyhow!("unexpected failure"));
        let j = err.to_json();
        assert_eq!(j.error_type, "Unknown");
        assert!(j.message.contains("unexpected failure"));
        assert!(j.context.is_none(), "anyhow errors carry no suggestion");
    }

    // ---- Error::Network (reqwest::Error) via to_json() ----
    //
    // These tests require a live socket to produce real reqwest::Error values.

    async fn status_req_error(status: u16) -> reqwest::Error {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/err"))
            .respond_with(ResponseTemplate::new(status))
            .mount(&server)
            .await;
        reqwest::Client::new()
            .get(format!("{}/err", server.uri()))
            .send()
            .await
            .expect("mock server must respond")
            .error_for_status()
            .expect_err("status >= 400 must produce an error")
    }

    #[tokio::test]
    async fn test_to_json_network_connect_error() {
        let req_err = reqwest::Client::new()
            .get("http://127.0.0.1:1/")
            .send()
            .await
            .expect_err("port 1 must refuse connections");
        assert!(req_err.is_connect());
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(
            j.context.is_some(),
            "connect error carries ERR_CONNECTION hint"
        );
    }

    #[tokio::test]
    async fn test_to_json_network_timeout_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/slow"))
            .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(10)))
            .mount(&server)
            .await;
        let req_err = reqwest::Client::builder()
            .timeout(Duration::from_millis(1))
            .build()
            .unwrap()
            .get(format!("{}/slow", server.uri()))
            .send()
            .await
            .expect_err("must time out");
        assert!(req_err.is_timeout());
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(
            j.context.is_some(),
            "timeout error carries ERR_TIMEOUT hint"
        );
    }

    #[tokio::test]
    async fn test_to_json_network_401() {
        let req_err = status_req_error(401).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(j.context.is_some());
    }

    #[tokio::test]
    async fn test_to_json_network_403() {
        let req_err = status_req_error(403).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(j.context.is_some());
    }

    #[tokio::test]
    async fn test_to_json_network_404() {
        let req_err = status_req_error(404).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(j.context.is_some());
    }

    #[tokio::test]
    async fn test_to_json_network_429() {
        let req_err = status_req_error(429).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(j.context.is_some());
    }

    #[tokio::test]
    async fn test_to_json_network_500() {
        let req_err = status_req_error(500).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(j.context.is_some());
    }

    /// Exercises the `_ => None` fallback within the `is_status()` arm — context must be None.
    /// Redirect codes (3xx) cannot be used because reqwest follows them automatically.
    /// 418 (I'm a Teapot) is not followed by reqwest and is not matched by any explicit arm.
    #[tokio::test]
    async fn test_to_json_network_status_fallback_no_context() {
        let req_err = status_req_error(418).await;
        let j = Error::Network(req_err).to_json();
        assert_eq!(j.error_type, "Network");
        assert!(
            j.context.is_none(),
            "unrecognised status code must produce no suggestion"
        );
    }
}