intelli-shell 3.4.0

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

use color_eyre::{
    Result,
    eyre::{Context, ContextCompat, eyre},
};
use crossterm::{
    event::{KeyCode, KeyEvent, KeyModifiers},
    style::{Attribute, Attributes, Color, ContentStyle},
};
use directories::ProjectDirs;
use itertools::Itertools;
use serde::{
    Deserialize,
    de::{Deserializer, Error},
};

use crate::{
    ai::{AiClient, AiProviderBase},
    model::SearchMode,
};

/// Main configuration struct for the application
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct Config {
    /// Directory where the data must be stored
    pub data_dir: PathBuf,
    /// Whether to check for updates
    pub check_updates: bool,
    /// Whether the TUI must be rendered "inline" below the shell prompt
    pub inline: bool,
    /// Configuration for the search command
    pub search: SearchConfig,
    /// Configuration settings for application logging
    pub logs: LogsConfig,
    /// Configuration for the key bindings used within the TUI
    pub keybindings: KeyBindingsConfig,
    /// Configuration for the visual theme of the TUI
    pub theme: Theme,
    /// Configuration for the default gist when importing or exporting
    pub gist: GistConfig,
    /// Configuration to tune the search algorithm
    pub tuning: SearchTuning,
    /// Configuration for the AI integration
    pub ai: AiConfig,
}

/// Configuration for the search command
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchConfig {
    /// The delay (in ms) to wait and accumulate type events before triggering the query
    pub delay: u64,
    /// The default search mode
    pub mode: SearchMode,
    /// Whether to search for user commands only by default (excluding tldr)
    pub user_only: bool,
    /// Whether to directly execute the command if it matches an alias exactly, instead of just selecting
    pub exec_on_alias_match: bool,
}

/// Configuration settings for application logging
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct LogsConfig {
    /// Whether application logging is enabled
    pub enabled: bool,
    /// The log filter to apply, controlling which logs are recorded.
    ///
    /// This string supports the `tracing-subscriber`'s environment filter syntax.
    pub filter: String,
}

/// Configuration for the key bindings used in the Terminal User Interface (TUI).
///
/// This struct holds the `KeyBinding` instances for various actions within the application's TUI, allowing users to
/// customize their interaction with the interface.
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct KeyBindingsConfig(
    #[serde(deserialize_with = "deserialize_bindings_with_defaults")] BTreeMap<KeyBindingAction, KeyBinding>,
);

/// Represents the distinct actions within the application that can be configured with specific key bindings
#[derive(Copy, Clone, Deserialize, PartialOrd, PartialEq, Eq, Ord, Debug)]
#[cfg_attr(test, derive(strum::EnumIter))]
#[serde(rename_all = "snake_case")]
pub enum KeyBindingAction {
    /// Exit the TUI gracefully
    Quit,
    /// Update the currently highlighted record or item
    Update,
    /// Delete the currently highlighted record or item
    Delete,
    /// Confirm a selection or action related to the highlighted record
    Confirm,
    /// Execute the action associated with the highlighted record or item
    Execute,
    /// Execute the action associated with the highlighted record or item
    #[serde(rename = "ai")]
    AI,
    /// Toggle the search mode
    SearchMode,
    /// Toggle whether to search for user commands only or include tldr's
    SearchUserOnly,
    /// Move to the next variable when replacing variables
    VariableNext,
    /// Move to the previous variable when replacing variables
    VariablePrev,
}

/// Represents a single logical key binding that can be triggered by one or more physical `KeyEvent`s.
///
/// Internally, it is stored as a `Vec<KeyEvent>` because multiple different key press combinations can map to the same
/// action.
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct KeyBinding(#[serde(deserialize_with = "deserialize_key_events")] Vec<KeyEvent>);

/// TUI theme configuration.
///
/// Defines the colors, styles, and highlighting behavior for the Terminal User Interface.
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct Theme {
    /// To be used as the primary style, like for selected items or main text
    #[serde(deserialize_with = "deserialize_style")]
    pub primary: ContentStyle,
    /// To be used as the secondary style, like for unselected items or less important text
    #[serde(deserialize_with = "deserialize_style")]
    pub secondary: ContentStyle,
    /// Accent style, typically used for highlighting specific elements like aliases or important keywords
    #[serde(deserialize_with = "deserialize_style")]
    pub accent: ContentStyle,
    /// Style for comments or less prominent information
    #[serde(deserialize_with = "deserialize_style")]
    pub comment: ContentStyle,
    /// Style for errors
    #[serde(deserialize_with = "deserialize_style")]
    pub error: ContentStyle,
    /// Optional background color for highlighted items
    #[serde(deserialize_with = "deserialize_color")]
    pub highlight: Option<Color>,
    /// The symbol displayed next to a highlighted item
    pub highlight_symbol: String,
    /// Primary style applied when an item is highlighted
    #[serde(deserialize_with = "deserialize_style")]
    pub highlight_primary: ContentStyle,
    /// Secondary style applied when an item is highlighted
    #[serde(deserialize_with = "deserialize_style")]
    pub highlight_secondary: ContentStyle,
    /// Accent style applied when an item is highlighted
    #[serde(deserialize_with = "deserialize_style")]
    pub highlight_accent: ContentStyle,
    /// Comments style applied when an item is highlighted
    #[serde(deserialize_with = "deserialize_style")]
    pub highlight_comment: ContentStyle,
}

/// Configuration settings for the default gist
#[derive(Clone, Default, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct GistConfig {
    /// Gist unique identifier
    pub id: String,
    /// Authentication token to use when writing to the gist
    pub token: String,
}

/// Holds all tunable parameters for the command and variable search ranking algorithms
#[derive(Clone, Copy, Default, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchTuning {
    /// Configuration for the command search ranking
    pub commands: SearchCommandTuning,
    /// Configuration for the variable values ranking
    pub variables: SearchVariableTuning,
}

/// Configures the ranking parameters for command search
#[derive(Clone, Copy, Default, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchCommandTuning {
    /// Defines weights and points for the text relevance component
    pub text: SearchCommandsTextTuning,
    /// Defines weights and points for the path-aware usage component
    pub path: SearchPathTuning,
    /// Defines points for the total usage component
    pub usage: SearchUsageTuning,
}

/// Defines weights and points for the text relevance (FTS) score component
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchCommandsTextTuning {
    /// Points assigned to the normalized text relevance score in the final calculation
    pub points: u32,
    /// Weight for the command within the FTS bm25 calculation
    pub command: f64,
    /// Weight for the description field within the FTS bm25 calculation
    pub description: f64,
    /// Specific weights for the different strategies within the 'auto' search algorithm
    pub auto: SearchCommandsTextAutoTuning,
}

/// Tunable weights for the different matching strategies within the 'auto' search mode
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchCommandsTextAutoTuning {
    /// Weight multiplier for results from the prefix-based FTS query
    pub prefix: f64,
    /// Weight multiplier for results from the fuzzy, all-words-match FTS query
    pub fuzzy: f64,
    /// Weight multiplier for results from the relaxed, any-word-match FTS query
    pub relaxed: f64,
    /// Boost multiplier to add when the first search term matches the start of the command's text
    pub root: f64,
}

/// Configures the path-aware scoring model
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchPathTuning {
    /// Points assigned to the normalized path score in the final calculation
    pub points: u32,
    /// Weight for a usage record that matches the current working directory exactly
    pub exact: f64,
    /// Weight for a usage record from an ancestor (parent) directory
    pub ancestor: f64,
    /// Weight for a usage record from a descendant (child) directory
    pub descendant: f64,
    /// Weight for a usage record from any other unrelated path
    pub unrelated: f64,
}

/// Configures the total usage scoring model
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchUsageTuning {
    /// Points assigned to the normalized total usage in the final calculation
    pub points: u32,
}

/// Configures the ranking parameters for variable values ranking
#[derive(Clone, Copy, Default, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchVariableTuning {
    /// Defines points for completions relevance component
    pub completion: SearchVariableCompletionTuning,
    /// Defines points for the context relevance component
    pub context: SearchVariableContextTuning,
    /// Defines weights and points for the path-aware usage component
    pub path: SearchPathTuning,
}

/// Defines points for the completions relevance score component of variable values
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchVariableCompletionTuning {
    /// Points assigned for values present on the completions
    pub points: u32,
}

/// Defines points for the context relevance score component of variable values
#[derive(Clone, Copy, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct SearchVariableContextTuning {
    /// Points assigned for matching contextual information (e.g. other selected values)
    pub points: u32,
}

/// Main configuration for all AI-related features
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct AiConfig {
    /// A global switch to enable or disable all AI-powered functionality
    pub enabled: bool,
    /// Prompts used by the different ai-enabled features
    pub prompts: AiPromptsConfig,
    /// Which models from the catalog are used by which feature
    pub models: AiModelsConfig,
    /// A collection of named AI model configurations.
    ///
    /// Each entry maps a custom alias (e.g., `fast-model`, `smart-model`) to its specific provider settings. These
    /// aliases are then referenced by the `suggest`, `fix`, `import`, and `fallback` fields.
    #[serde(deserialize_with = "deserialize_catalog_with_defaults")]
    pub catalog: BTreeMap<String, AiModelConfig>,
}

/// Configuration for the prompts
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct AiPromptsConfig {
    /// The prompt to use when generating command suggestions from natural language.
    pub suggest: String,
    /// The prompt to use when explaining the fix for a failed command.
    pub fix: String,
    /// The prompt to use when importing commands (e.g., from a natural language page).
    pub import: String,
    /// The prompt used to generate a command for a dynamic completion.
    pub completion: String,
}

/// Configuration for the models to be used
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[cfg_attr(not(test), serde(default))]
pub struct AiModelsConfig {
    /// The alias of the AI model to use for generating command suggestions from natural language.
    /// This alias must correspond to a key in the `catalog` map.
    pub suggest: String,
    /// The alias of the AI model used to explain the fix for a failed command.
    /// This alias must correspond to a key in the `catalog` map.
    pub fix: String,
    /// The alias of the AI model to use when importing commands (e.g., from a natural language page).
    /// This alias must correspond to a key in the `catalog` map.
    pub import: String,
    /// The alias of the AI model to use when suggesting variable completion commands
    /// This alias must correspond to a key in the `catalog` map.
    pub completion: String,
    /// The alias of a model to use as a fallback when the primary model for a task fails due to rate limiting.
    /// This alias must correspond to a key in the `catalog` map.
    pub fallback: String,
}

/// Represents the configuration for a specific AI model, distinguished by the provider
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[serde(tag = "provider", rename_all = "snake_case")]
pub enum AiModelConfig {
    /// Configuration for OpenAI or compatible APIs
    Openai(OpenAiModelConfig),
    /// Configuration for Google Gemini API
    Gemini(GeminiModelConfig),
    /// Configuration for Anthropic API
    Anthropic(AnthropicModelConfig),
    /// Configuration for models served via Ollama
    Ollama(OllamaModelConfig),
}

/// Configuration for connecting to an OpenAI or a compatible API
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct OpenAiModelConfig {
    /// The exact model identifier to use (e.g., "gpt-4o", "gpt-3.5-turbo")
    pub model: String,
    /// The base URL of the API endpoint. Defaults to the official OpenAI API.
    ///
    /// Can be overridden to use other compatible services (e.g., Azure OpenAI, LiteLLM).
    #[serde(default = "default_openai_url")]
    pub url: String,
    /// The name of the environment variable containing the API key for this model. Defaults to `OPENAI_API_KEY`.
    #[serde(default = "default_openai_api_key_env")]
    pub api_key_env: String,
}
fn default_openai_url() -> String {
    "https://api.openai.com/v1".to_string()
}
fn default_openai_api_key_env() -> String {
    "OPENAI_API_KEY".to_string()
}

/// Configuration for connecting to the Google Gemini API
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct GeminiModelConfig {
    /// The exact model identifier to use (e.g., "gemini-2.5-flash-lite")
    pub model: String,
    /// The base URL of the API endpoint. Defaults to the official Google Gemini API.
    #[serde(default = "default_gemini_url")]
    pub url: String,
    /// The name of the environment variable containing the API key for this model. Defaults to `GEMINI_API_KEY`.
    #[serde(default = "default_gemini_api_key_env")]
    pub api_key_env: String,
}
fn default_gemini_url() -> String {
    "https://generativelanguage.googleapis.com/v1beta".to_string()
}
fn default_gemini_api_key_env() -> String {
    "GEMINI_API_KEY".to_string()
}

/// Configuration for connecting to the Anthropic API
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct AnthropicModelConfig {
    /// The exact model identifier to use (e.g., "claude-sonnet-4-0")
    pub model: String,
    /// The base URL of the API endpoint. Defaults to the official Anthropic API
    #[serde(default = "default_anthropic_url")]
    pub url: String,
    /// The name of the environment variable containing the API key for this model. Defaults to `ANTHROPIC_API_KEY`.
    #[serde(default = "default_anthropic_api_key_env")]
    pub api_key_env: String,
}
fn default_anthropic_url() -> String {
    "https://api.anthropic.com/v1".to_string()
}
fn default_anthropic_api_key_env() -> String {
    "ANTHROPIC_API_KEY".to_string()
}

/// Configuration for connecting to a local or remote Ollama instance
#[derive(Clone, Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct OllamaModelConfig {
    /// The model name as configured in Ollama (e.g., "llama3", "mistral")
    pub model: String,
    /// The base URL of the Ollama server. Defaults to the standard local address.
    #[serde(default = "default_ollama_url")]
    pub url: String,
    /// The name of the environment variable containing the API key for this model. Defaults to `OLLAMA_API_KEY`.
    #[serde(default = "default_ollama_api_key_env")]
    pub api_key_env: String,
}
fn default_ollama_url() -> String {
    "http://localhost:11434".to_string()
}
fn default_ollama_api_key_env() -> String {
    "OLLAMA_API_KEY".to_string()
}

/// Statistics about how the configuration was loaded
pub struct ConfigLoadStats {
    /// Whether the config path used was the default one
    pub default_config_path: bool,
    /// The actual path from which the config was loaded (or attempted to be loaded)
    pub config_path: PathBuf,
    /// Whether the config file was found and loaded or the defaults were used
    pub config_loaded: bool,
    /// Whether the data dir used was the default one
    pub default_data_dir: bool,
}

impl Config {
    /// Initializes the application configuration.
    ///
    /// Attempts to load the configuration from the user's config directory (`config.toml`). If the file does not exist
    /// or has missing fields, it falls back to default values.
    pub fn init(config_file: Option<PathBuf>) -> Result<(Self, ConfigLoadStats)> {
        // Initialize directories
        let proj_dirs = ProjectDirs::from("org", "IntelliShell", "Intelli-Shell")
            .wrap_err("Couldn't initialize project directory")?;
        let config_dir = proj_dirs.config_dir().to_path_buf();

        // Initialize the stats and config
        let mut stats = ConfigLoadStats {
            default_config_path: config_file.is_none(),
            config_path: config_file.unwrap_or_else(|| config_dir.join("config.toml")),
            config_loaded: false,
            default_data_dir: false,
        };
        let mut config = if stats.config_path.exists() {
            stats.config_loaded = true;
            // Read from the config file, if found
            let config_str = fs::read_to_string(&stats.config_path)
                .wrap_err_with(|| format!("Couldn't read config file {}", stats.config_path.display()))?;
            toml::from_str(&config_str)
                .wrap_err_with(|| format!("Couldn't parse config file {}", stats.config_path.display()))?
        } else {
            // Use default values if not found
            Config::default()
        };
        // If no data dir is provided, use the default
        if config.data_dir.as_os_str().is_empty() {
            stats.default_data_dir = true;
            config.data_dir = proj_dirs.data_dir().to_path_buf();
        }

        // Validate there are no conflicts on the key bindings
        let conflicts = config.keybindings.find_conflicts();
        if !conflicts.is_empty() {
            return Err(eyre!(
                "Couldn't parse config file {}\n\nThere are some key binding conflicts:\n{}",
                stats.config_path.display(),
                conflicts
                    .into_iter()
                    .map(|(_, a)| format!("- {}", a.into_iter().map(|a| format!("{a:?}")).join(", ")))
                    .join("\n")
            ));
        }

        // Validate AI models are properly setup
        if config.ai.enabled {
            let AiModelsConfig {
                suggest,
                fix,
                import,
                completion,
                fallback,
            } = &config.ai.models;
            let catalog = &config.ai.catalog;

            let mut missing = Vec::new();
            if !catalog.contains_key(suggest) {
                missing.push((suggest, "suggest"));
            }
            if !catalog.contains_key(fix) {
                missing.push((fix, "fix"));
            }
            if !catalog.contains_key(import) {
                missing.push((import, "import"));
            }
            if !catalog.contains_key(completion) {
                missing.push((completion, "completion"));
            }
            if !catalog.contains_key(fallback) {
                missing.push((fallback, "fallback"));
            }

            if !missing.is_empty() {
                return Err(eyre!(
                    "Couldn't parse config file {}\n\nMissing model definitions on the catalog:\n{}",
                    stats.config_path.display(),
                    missing
                        .into_iter()
                        .into_group_map()
                        .into_iter()
                        .map(|(k, v)| format!(
                            "- {k} used in {}",
                            v.into_iter().map(|v| format!("ai.models.{v}")).join(", ")
                        ))
                        .join("\n")
                ));
            }
        }

        // Create the data directory if not found
        fs::create_dir_all(&config.data_dir)
            .wrap_err_with(|| format!("Could't create data dir {}", config.data_dir.display()))?;

        Ok((config, stats))
    }
}

impl KeyBindingsConfig {
    /// Retrieves the [KeyBinding] for a specific action
    pub fn get(&self, action: &KeyBindingAction) -> &KeyBinding {
        self.0.get(action).unwrap()
    }

    /// Finds the [KeyBindingAction] associated with the given [KeyEvent], if any
    pub fn get_action_matching(&self, event: &KeyEvent) -> Option<KeyBindingAction> {
        self.0.iter().find_map(
            |(action, binding)| {
                if binding.matches(event) { Some(*action) } else { None }
            },
        )
    }

    /// Finds all ambiguous key bindings where a single `KeyEvent` maps to multiple `KeyBindingAction`s
    pub fn find_conflicts(&self) -> Vec<(KeyEvent, Vec<KeyBindingAction>)> {
        // A map to store each KeyEvent and the list of actions it's bound to.
        let mut event_to_actions_map: HashMap<KeyEvent, Vec<KeyBindingAction>> = HashMap::new();

        // Iterate over all configured actions and their bindings.
        for (action, key_binding) in self.0.iter() {
            // For each KeyEvent defined within the current KeyBinding...
            for event_in_binding in key_binding.0.iter() {
                // Record that this event maps to the current action.
                event_to_actions_map.entry(*event_in_binding).or_default().push(*action);
            }
        }

        // Filter the map to find KeyEvents that map to more than one action.
        event_to_actions_map
            .into_iter()
            .filter_map(|(key_event, actions)| {
                if actions.len() > 1 {
                    Some((key_event, actions))
                } else {
                    None
                }
            })
            .collect()
    }
}

impl KeyBinding {
    /// Checks if a given `KeyEvent` matches any of the key events configured for this key binding, considering only the
    /// key `code` and its `modifiers`.
    pub fn matches(&self, event: &KeyEvent) -> bool {
        self.0
            .iter()
            .any(|e| e.code == event.code && e.modifiers == event.modifiers)
    }
}

impl Theme {
    /// Primary style applied when an item is highlighted, including the background color
    pub fn highlight_primary_full(&self) -> ContentStyle {
        if let Some(color) = self.highlight {
            let mut ret = self.highlight_primary;
            ret.background_color = Some(color);
            ret
        } else {
            self.highlight_primary
        }
    }

    /// Secondary style applied when an item is highlighted, including the background color
    pub fn highlight_secondary_full(&self) -> ContentStyle {
        if let Some(color) = self.highlight {
            let mut ret = self.highlight_secondary;
            ret.background_color = Some(color);
            ret
        } else {
            self.highlight_secondary
        }
    }

    /// Accent style applied when an item is highlighted, including the background color
    pub fn highlight_accent_full(&self) -> ContentStyle {
        if let Some(color) = self.highlight {
            let mut ret = self.highlight_accent;
            ret.background_color = Some(color);
            ret
        } else {
            self.highlight_accent
        }
    }

    /// Comments style applied when an item is highlighted, including the background color
    pub fn highlight_comment_full(&self) -> ContentStyle {
        if let Some(color) = self.highlight {
            let mut ret = self.highlight_comment;
            ret.background_color = Some(color);
            ret
        } else {
            self.highlight_comment
        }
    }
}

impl AiConfig {
    /// Retrieves a client configured for the `suggest` action
    pub fn suggest_client(&self) -> crate::errors::Result<AiClient<'_>> {
        AiClient::new(
            &self.models.suggest,
            self.catalog.get(&self.models.suggest).unwrap(),
            &self.models.fallback,
            self.catalog.get(&self.models.fallback),
        )
    }

    /// Retrieves a client configured for the `fix` action
    pub fn fix_client(&self) -> crate::errors::Result<AiClient<'_>> {
        AiClient::new(
            &self.models.fix,
            self.catalog.get(&self.models.fix).unwrap(),
            &self.models.fallback,
            self.catalog.get(&self.models.fallback),
        )
    }

    /// Retrieves a client configured for the `import` action
    pub fn import_client(&self) -> crate::errors::Result<AiClient<'_>> {
        AiClient::new(
            &self.models.import,
            self.catalog.get(&self.models.import).unwrap(),
            &self.models.fallback,
            self.catalog.get(&self.models.fallback),
        )
    }

    /// Retrieves a client configured for the `completion` action
    pub fn completion_client(&self) -> crate::errors::Result<AiClient<'_>> {
        AiClient::new(
            &self.models.completion,
            self.catalog.get(&self.models.completion).unwrap(),
            &self.models.fallback,
            self.catalog.get(&self.models.fallback),
        )
    }
}
impl AiModelConfig {
    pub fn provider(&self) -> &dyn AiProviderBase {
        match self {
            AiModelConfig::Openai(conf) => conf,
            AiModelConfig::Gemini(conf) => conf,
            AiModelConfig::Anthropic(conf) => conf,
            AiModelConfig::Ollama(conf) => conf,
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            data_dir: PathBuf::new(),
            check_updates: true,
            inline: true,
            search: SearchConfig::default(),
            logs: LogsConfig::default(),
            keybindings: KeyBindingsConfig::default(),
            theme: Theme::default(),
            gist: GistConfig::default(),
            tuning: SearchTuning::default(),
            ai: AiConfig::default(),
        }
    }
}
impl Default for SearchConfig {
    fn default() -> Self {
        Self {
            delay: 250,
            mode: SearchMode::Auto,
            user_only: false,
            exec_on_alias_match: false,
        }
    }
}
impl Default for LogsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            filter: String::from("info"),
        }
    }
}
impl Default for KeyBindingsConfig {
    fn default() -> Self {
        Self(BTreeMap::from([
            (KeyBindingAction::Quit, KeyBinding(vec![KeyEvent::from(KeyCode::Esc)])),
            (
                KeyBindingAction::Update,
                KeyBinding(vec![
                    KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
                    KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL),
                    KeyEvent::from(KeyCode::F(2)),
                ]),
            ),
            (
                KeyBindingAction::Delete,
                KeyBinding(vec![KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)]),
            ),
            (
                KeyBindingAction::Confirm,
                KeyBinding(vec![KeyEvent::from(KeyCode::Tab), KeyEvent::from(KeyCode::Enter)]),
            ),
            (
                KeyBindingAction::Execute,
                KeyBinding(vec![
                    KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL),
                    KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL),
                ]),
            ),
            (
                KeyBindingAction::AI,
                KeyBinding(vec![
                    KeyEvent::new(KeyCode::Char('i'), KeyModifiers::CONTROL),
                    KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
                ]),
            ),
            (
                KeyBindingAction::SearchMode,
                KeyBinding(vec![KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)]),
            ),
            (
                KeyBindingAction::SearchUserOnly,
                KeyBinding(vec![KeyEvent::new(KeyCode::Char('o'), KeyModifiers::CONTROL)]),
            ),
            (
                KeyBindingAction::VariableNext,
                KeyBinding(vec![KeyEvent::new(KeyCode::Tab, KeyModifiers::CONTROL)]),
            ),
            (
                KeyBindingAction::VariablePrev,
                KeyBinding(vec![
                    KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT),
                    KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT),
                ]),
            ),
        ]))
    }
}
impl Default for Theme {
    fn default() -> Self {
        let primary = ContentStyle::new();
        let highlight_primary = primary;

        let mut secondary = ContentStyle::new();
        secondary.attributes.set(Attribute::Dim);
        let highlight_secondary = ContentStyle::new();

        let mut accent = ContentStyle::new();
        accent.foreground_color = Some(Color::Yellow);
        let highlight_accent = accent;

        let mut comment = ContentStyle::new();
        comment.foreground_color = Some(Color::Green);
        comment.attributes.set(Attribute::Italic);
        let highlight_comment = comment;

        let mut error = ContentStyle::new();
        error.foreground_color = Some(Color::DarkRed);

        Self {
            primary,
            secondary,
            accent,
            comment,
            error,
            highlight: Some(Color::DarkGrey),
            highlight_symbol: String::from("» "),
            highlight_primary,
            highlight_secondary,
            highlight_accent,
            highlight_comment,
        }
    }
}
impl Default for SearchCommandsTextTuning {
    fn default() -> Self {
        Self {
            points: 600,
            command: 2.0,
            description: 1.0,
            auto: SearchCommandsTextAutoTuning::default(),
        }
    }
}
impl Default for SearchCommandsTextAutoTuning {
    fn default() -> Self {
        Self {
            prefix: 1.5,
            fuzzy: 1.0,
            relaxed: 0.5,
            root: 2.0,
        }
    }
}
impl Default for SearchUsageTuning {
    fn default() -> Self {
        Self { points: 100 }
    }
}
impl Default for SearchPathTuning {
    fn default() -> Self {
        Self {
            points: 300,
            exact: 1.0,
            ancestor: 0.5,
            descendant: 0.25,
            unrelated: 0.1,
        }
    }
}
impl Default for SearchVariableCompletionTuning {
    fn default() -> Self {
        Self { points: 200 }
    }
}
impl Default for SearchVariableContextTuning {
    fn default() -> Self {
        Self { points: 700 }
    }
}
fn default_ai_catalog() -> BTreeMap<String, AiModelConfig> {
    BTreeMap::from([
        (
            "main".to_string(),
            AiModelConfig::Gemini(GeminiModelConfig {
                model: "gemini-flash-latest".to_string(),
                url: default_gemini_url(),
                api_key_env: default_gemini_api_key_env(),
            }),
        ),
        (
            "fallback".to_string(),
            AiModelConfig::Gemini(GeminiModelConfig {
                model: "gemini-flash-lite-latest".to_string(),
                url: default_gemini_url(),
                api_key_env: default_gemini_api_key_env(),
            }),
        ),
    ])
}
impl Default for AiConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            models: AiModelsConfig::default(),
            prompts: AiPromptsConfig::default(),
            catalog: default_ai_catalog(),
        }
    }
}
impl Default for AiModelsConfig {
    fn default() -> Self {
        Self {
            suggest: "main".to_string(),
            fix: "main".to_string(),
            import: "main".to_string(),
            completion: "main".to_string(),
            fallback: "fallback".to_string(),
        }
    }
}
impl Default for AiPromptsConfig {
    fn default() -> Self {
        Self {
            suggest: String::from(
                r#"##OS_SHELL_INFO##
##WORKING_DIR##
### Instructions
You are an expert CLI assistant. Your task is to generate shell command templates based on the user's request.

Your entire response MUST be a single, valid JSON object conforming to the provided schema and nothing else.

### Shell Paradigm, Syntax, and Versioning
**This is the most important instruction.** Shells have fundamentally different syntaxes, data models, and features depending on their family and version. You MUST adhere strictly to these constraints.

1. **Recognize the Shell Paradigm:**
   - **POSIX / Text-Stream (bash, zsh, fish):** Operate on **text streams**. Use tools like `grep`, `sed`, `awk`.
   - **Object-Pipeline (PowerShell, Nushell):** Operate on **structured data (objects)**. You MUST use internal commands for filtering/selection. AVOID external text-processing tools.
   - **Legacy (cmd.exe):** Has unique syntax for loops (`FOR`), variables (`%VAR%`), and filtering (`findstr`).

2. **Generate Idiomatic Code:**
   - Use the shell's built-in features and standard library.
   - Follow the shell's naming and style conventions (e.g., `Verb-Noun` in PowerShell).
   - Leverage the shell's core strengths (e.g., object manipulation in Nushell).

3. **Ensure Syntactic Correctness:**
   - Pay close attention to variable syntax (`$var`, `$env:VAR`, `$env.VAR`, `%VAR%`).
   - Use the correct operators and quoting rules for the target shell.

4. **Pay Critical Attention to the Version:**
   - The shell version is a primary constraint, not a suggestion. This is especially true for shells with rapid development cycles like **Nushell**.
   - You **MUST** generate commands that are compatible with the user's specified version.
   - Be aware of **breaking changes**. If a command was renamed, replaced, or deprecated in the user's version, you MUST provide the modern, correct equivalent.

### Command Template Syntax
When creating the `command` template string, you must use the following placeholder syntax:

- **Standard Placeholder**: `{{variable-name}}`
  - Use for regular arguments that the user needs to provide.
  - _Example_: `echo "Hello, {{user-name}}!"`

- **Choice Placeholder**: `{{option1|option2}}`
  - Use when the user must choose from a specific set of options.
  - _Example_: `git reset {{--soft|--hard}} HEAD~1`

- **Function Placeholder**: `{{variable:function}}`
  - Use to apply a transformation function to the user's input. Multiple functions can be chained (e.g., `{{variable:snake:upper}}`).
  - Allowed functions: `kebab`, `snake`, `upper`, `lower`, `url`.
  - _Example_: For a user input of "My New Feature", `git checkout -b {{branch-name:kebab}}` would produce `git checkout -b my-new-feature`.

- **Secret/Ephemeral Placeholder**: `{{{...}}}`
  - Use triple curly braces for sensitive values (like API keys, passwords) or for ephemeral content (like a commit message or a description). 
    This syntax can wrap any of the placeholder types above.
  - _Example_: `export GITHUB_TOKEN={{{api-key}}}` or `git commit -m "{{{message}}}"`

### Suggestion Strategy
Your primary goal is to provide the most relevant and comprehensive set of command templates. Adhere strictly to the following principles when deciding how many suggestions to provide:

1. **Explicit Single Suggestion:**
   - If the user's request explicitly asks for **a single suggestion**, you **MUST** return a list containing exactly one suggestion object.
   - To cover variations within this single command, make effective use of choice placeholders (e.g., `git reset {{--soft|--hard}}`).

2. **Clear & Unambiguous Request:**
   - If the request is straightforward and has one primary, standard solution, provide a **single, well-formed suggestion**.

3. **Ambiguous or Multi-faceted Request:**
   - If a request is ambiguous, has multiple valid interpretations, or can be solved using several distinct tools or methods, you **MUST provide a comprehensive list of suggestions**.
   - Each distinct approach or interpretation **must be a separate suggestion object**.
   - **Be comprehensive and do not limit your suggestions**. For example, a request for "undo a git commit" could mean `git reset`, `git revert`, or `git checkout`. A request to "find files" could yield suggestions for `find`, `fd`, and `locate`. Provide all valid, distinct alternatives.
   - **Order the suggestions by relevance**, with the most common or recommended solution appearing first.
"#,
            ),
            fix: String::from(
                r#"##OS_SHELL_INFO##
##WORKING_DIR##
##SHELL_HISTORY##
### Instructions
You are an expert command-line assistant. Your mission is to analyze a failed shell command and its error output, 
diagnose the root cause, and provide a structured, actionable solution in a single JSON object.

### Output Schema
Your response MUST be a single, valid JSON object with no surrounding text or markdown. It must conform to the following structure:
- `summary`: A very brief, 2-5 word summary of the error category. Examples: "Command Not Found", "Permission Denied", "Invalid Argument", "Git Typo".
- `diagnosis`: A detailed, human-readable explanation of the root cause of the error. This section should explain *what* went wrong and *why*, based on the provided command and error message. It should not contain the solution.
- `proposal`: A human-readable description of the recommended next steps. This can be a description of a fix, diagnostic commands to run, or a suggested workaround.
- `fixed_command`: The corrected, valid, ready-to-execute command string. This field should *only* be populated if a direct command correction is the primary solution (e.g., fixing a typo). For complex issues requiring explanation or privilege changes, this should be an empty string.

### Core Rules
1. **JSON Only**: Your entire output must be a single, raw JSON object. Do not wrap it in code blocks or add any explanatory text.
2. **Holistic Analysis**: Analyze the command's context, syntax, and common user errors. Don't just parse the error message. Consider the user's likely intent.
3. **Strict Wrapping**: Hard-wrap all string values within the JSON to a maximum of 80 characters.
4. **`fixed_command` Logic**: Always populate `fixed_command` with the most likely command to resolve the error. Only leave this field as an empty string if the user's intent is unclear from the context.
"#,
            ),
            import: String::from(
                r#"### Instructions
You are an expert tool that extracts and generalizes shell command patterns from arbitrary text content. Your goal is to analyze the provided text, identify all unique command patterns, and present them as a list of suggestions.

Your entire response MUST be a single, valid JSON object conforming to the provided schema. Output nothing but the JSON object itself.

Refer to the syntax definitions, process, and example below to construct your response.

### Command Template Syntax
When creating the `command` template string, you must use the following placeholder syntax:

- **Standard Placeholder**: `{{variable-name}}`
  - Use for regular arguments that the user needs to provide.
  - _Example_: `echo "Hello, {{user-name}}!"`

- **Choice Placeholder**: `{{option1|option2}}`
  - Use when the user must choose from a specific set of options.
  - _Example_: `git reset {{--soft|--hard}} HEAD~1`

- **Function Placeholder**: `{{variable:function}}`
  - Use to apply a transformation function to the user's input. Multiple functions can be chained (e.g., `{{variable:snake:upper}}`).
  - Allowed functions: `kebab`, `snake`, `upper`, `lower`, `url`.
  - _Example_: For a user input of "My New Feature", `git checkout -b {{branch-name:kebab}}` would produce `git checkout -b my-new-feature`.

- **Secret/Ephemeral Placeholder**: `{{{...}}}`
  - Use triple curly braces for sensitive values (like API keys, passwords) or for ephemeral content (like a commit message or a description). 
    This syntax can wrap any of the placeholder types above.
  - _Example_: `export GITHUB_TOKEN={{{api-key}}}` or `git commit -m "{{{message}}}"`

### Core Process
1. **Extract & Generalize**: Scan the text to find all shell commands. Generalize each one into a template by replacing specific values with the appropriate placeholder type defined in the **Command Template Syntax** section.
2. **Deduplicate**: Consolidate multiple commands that follow the same pattern into a single, representative template. For example, `git checkout bugfix/some-bug` and `git checkout feature/login` must be merged into a single `git checkout {{feature|bugfix}}/{{{description:kebab}}}` suggestion.

### Output Generation
For each unique and deduplicated command pattern you identify:
- Create a suggestion object containing a `description` and a `command`.
- The `description` must be a clear, single-sentence explanation of the command's purpose.
- The `command` must be the final, generalized template string from the core process.
"#,
            ),
            completion: String::from(
                r#"##OS_SHELL_INFO##
### Instructions
You are an expert CLI assistant. Your task is to generate a single-line shell command that will be executed in the background to fetch a list of dynamic command-line completions for a given variable.

Your entire response MUST be a single, valid JSON object conforming to the provided schema and nothing else.

### Core Task
The command you create will be run non-interactively to generate a list of suggestions for the user. It must adapt to information that is already known (the "context").

### Command Template Syntax
To make the command context-aware, you must use a special syntax for optional parts of the command. Any segment of the command that depends on contextual information must be wrapped in double curly braces `{{...}}`.

- **Syntax**: `{{--parameter {{variable-name}}}}`
- **Rule**: The entire block, including the parameter and its variable, will only be included in the final command if the `variable-name` exists in the context. If the variable is not present, the entire block is omitted.
- **All-or-Nothing**: If a block contains multiple variables, all of them must be present in the context for the block to be included.

- **_Example_**:
  - **Template**: `kubectl get pods {{--context {{context}}}} {{-n {{namespace}}}}`
  - If the context provides a `namespace`, the executed command becomes: `kubectl get pods -n prod`
  - If the context provides both `namespace` and `context`, it becomes: `kubectl get pods --context my-cluster -n prod`
  - If the context is empty, it is simply: `kubectl get pods`

### Requirements
1. **JSON Only**: Your entire output must be a single, raw JSON object. Do not add any explanatory text.
2. **Context is Key**: Every variable like `{{variable-name}}` must be part of a surrounding conditional block `{{...}}`. The command cannot ask for new information.
3. **Produce a List**: The final command, after resolving the context, must print a list of strings to standard output, with each item on a new line. This list will be the source for the completions.
4. **Executable**: The command must be syntactically correct and executable.
"#,
            ),
        }
    }
}

/// Custom deserialization function for the BTreeMap in KeyBindingsConfig.
///
/// Behavior depends on whether compiled for test or not:
/// - In test (`#[cfg(test)]`): Requires all `KeyBindingAction` variants to be present; otherwise, errors. No merging.
/// - In non-test (`#[cfg(not(test))]`): Merges user-provided bindings with defaults.
fn deserialize_bindings_with_defaults<'de, D>(
    deserializer: D,
) -> Result<BTreeMap<KeyBindingAction, KeyBinding>, D::Error>
where
    D: Deserializer<'de>,
{
    // Deserialize the map as provided in the config.
    let user_provided_bindings = BTreeMap::<KeyBindingAction, KeyBinding>::deserialize(deserializer)?;

    #[cfg(test)]
    {
        use strum::IntoEnumIterator;
        // In test mode, all actions must be explicitly defined. No defaults are merged.
        for action_variant in KeyBindingAction::iter() {
            if !user_provided_bindings.contains_key(&action_variant) {
                return Err(D::Error::custom(format!(
                    "Missing key binding for action '{action_variant:?}'."
                )));
            }
        }
        Ok(user_provided_bindings)
    }
    #[cfg(not(test))]
    {
        // In non-test (production) mode, merge with defaults.
        // User-provided bindings override defaults for the actions they specify.
        let mut final_bindings = user_provided_bindings;
        let default_bindings = KeyBindingsConfig::default();

        for (action, default_binding) in default_bindings.0 {
            final_bindings.entry(action).or_insert(default_binding);
        }
        Ok(final_bindings)
    }
}

/// Deserializes a string or a vector of strings into a `Vec<KeyEvent>`.
///
/// This allows a key binding to be specified as a single string or a list of strings in the config file.
fn deserialize_key_events<'de, D>(deserializer: D) -> Result<Vec<KeyEvent>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StringOrVec {
        Single(String),
        Multiple(Vec<String>),
    }

    let strings = match StringOrVec::deserialize(deserializer)? {
        StringOrVec::Single(s) => vec![s],
        StringOrVec::Multiple(v) => v,
    };

    strings
        .iter()
        .map(String::as_str)
        .map(parse_key_event)
        .map(|r| r.map_err(D::Error::custom))
        .collect()
}

/// Deserializes a string into an optional [`Color`].
///
/// Supports color names, RGB (e.g., `rgb(255, 0, 100)`), hex (e.g., `#ff0064`), indexed colors (e.g., `6`), and "none"
/// for no color.
fn deserialize_color<'de, D>(deserializer: D) -> Result<Option<Color>, D::Error>
where
    D: Deserializer<'de>,
{
    parse_color(&String::deserialize(deserializer)?).map_err(D::Error::custom)
}

/// Deserializes a string into a [`ContentStyle`].
///
/// Supports color names and modifiers (e.g., "red", "bold", "italic blue", "underline dim green").
fn deserialize_style<'de, D>(deserializer: D) -> Result<ContentStyle, D::Error>
where
    D: Deserializer<'de>,
{
    parse_style(&String::deserialize(deserializer)?).map_err(D::Error::custom)
}

/// Parses a string representation of a key event into a [`KeyEvent`].
///
/// Supports modifiers like `ctrl-`, `alt-`, `shift-` and standard key names/characters.
fn parse_key_event(raw: &str) -> Result<KeyEvent, String> {
    let raw_lower = raw.to_ascii_lowercase();
    let (remaining, modifiers) = extract_key_modifiers(&raw_lower);
    parse_key_code_with_modifiers(remaining, modifiers)
}

/// Extracts key modifiers (ctrl, shift, alt) from the beginning of a key event string.
///
/// Returns the remaining string and the parsed modifiers.
fn extract_key_modifiers(raw: &str) -> (&str, KeyModifiers) {
    let mut modifiers = KeyModifiers::empty();
    let mut current = raw;

    loop {
        match current {
            rest if rest.starts_with("ctrl-") || rest.starts_with("ctrl+") => {
                modifiers.insert(KeyModifiers::CONTROL);
                current = &rest[5..];
            }
            rest if rest.starts_with("shift-") || rest.starts_with("shift+") => {
                modifiers.insert(KeyModifiers::SHIFT);
                current = &rest[6..];
            }
            rest if rest.starts_with("alt-") || rest.starts_with("alt+") => {
                modifiers.insert(KeyModifiers::ALT);
                current = &rest[4..];
            }
            _ => break,
        };
    }

    (current, modifiers)
}

/// Parses the remaining string after extracting modifiers into a [`KeyCode`]
fn parse_key_code_with_modifiers(raw: &str, mut modifiers: KeyModifiers) -> Result<KeyEvent, String> {
    let code = match raw {
        "esc" => KeyCode::Esc,
        "enter" => KeyCode::Enter,
        "left" => KeyCode::Left,
        "right" => KeyCode::Right,
        "up" => KeyCode::Up,
        "down" => KeyCode::Down,
        "home" => KeyCode::Home,
        "end" => KeyCode::End,
        "pageup" => KeyCode::PageUp,
        "pagedown" => KeyCode::PageDown,
        "backtab" => {
            modifiers.insert(KeyModifiers::SHIFT);
            KeyCode::BackTab
        }
        "backspace" => KeyCode::Backspace,
        "delete" => KeyCode::Delete,
        "insert" => KeyCode::Insert,
        "f1" => KeyCode::F(1),
        "f2" => KeyCode::F(2),
        "f3" => KeyCode::F(3),
        "f4" => KeyCode::F(4),
        "f5" => KeyCode::F(5),
        "f6" => KeyCode::F(6),
        "f7" => KeyCode::F(7),
        "f8" => KeyCode::F(8),
        "f9" => KeyCode::F(9),
        "f10" => KeyCode::F(10),
        "f11" => KeyCode::F(11),
        "f12" => KeyCode::F(12),
        "space" | "spacebar" => KeyCode::Char(' '),
        "hyphen" => KeyCode::Char('-'),
        "minus" => KeyCode::Char('-'),
        "tab" => KeyCode::Tab,
        c if c.len() == 1 => {
            let mut c = c.chars().next().expect("just checked");
            if modifiers.contains(KeyModifiers::SHIFT) {
                c = c.to_ascii_uppercase();
            }
            KeyCode::Char(c)
        }
        _ => return Err(format!("Unable to parse key binding: {raw}")),
    };
    Ok(KeyEvent::new(code, modifiers))
}

/// Parses a string into an optional [`Color`].
///
/// Handles named colors, RGB, hex, indexed colors, and "none".
fn parse_color(raw: &str) -> Result<Option<Color>, String> {
    let raw_lower = raw.to_ascii_lowercase();
    if raw.is_empty() || raw == "none" {
        Ok(None)
    } else {
        Ok(Some(parse_color_inner(&raw_lower)?))
    }
}

/// Parses a string into a [`ContentStyle`], including attributes and foreground color.
///
/// Examples: "red", "bold", "italic blue", "underline dim green".
fn parse_style(raw: &str) -> Result<ContentStyle, String> {
    let raw_lower = raw.to_ascii_lowercase();
    let (remaining, attributes) = extract_style_attributes(&raw_lower);
    let mut style = ContentStyle::new();
    style.attributes = attributes;
    if !remaining.is_empty() && remaining != "default" {
        style.foreground_color = Some(parse_color_inner(remaining)?);
    }
    Ok(style)
}

/// Extracts style attributes (bold, dim, italic, underline) from the beginning of a style string.
///
/// Returns the remaining string and the parsed attributes.
fn extract_style_attributes(raw: &str) -> (&str, Attributes) {
    let mut attributes = Attributes::none();
    let mut current = raw;

    loop {
        match current {
            rest if rest.starts_with("bold") => {
                attributes.set(Attribute::Bold);
                current = &rest[4..];
                if current.starts_with(' ') {
                    current = &current[1..];
                }
            }
            rest if rest.starts_with("dim") => {
                attributes.set(Attribute::Dim);
                current = &rest[3..];
                if current.starts_with(' ') {
                    current = &current[1..];
                }
            }
            rest if rest.starts_with("italic") => {
                attributes.set(Attribute::Italic);
                current = &rest[6..];
                if current.starts_with(' ') {
                    current = &current[1..];
                }
            }
            rest if rest.starts_with("underline") => {
                attributes.set(Attribute::Underlined);
                current = &rest[9..];
                if current.starts_with(' ') {
                    current = &current[1..];
                }
            }
            rest if rest.starts_with("underlined") => {
                attributes.set(Attribute::Underlined);
                current = &rest[10..];
                if current.starts_with(' ') {
                    current = &current[1..];
                }
            }
            _ => break,
        };
    }

    (current.trim(), attributes)
}

/// Parses the color part of a style string.
///
/// Handles named colors, rgb, hex, and ansi values.
fn parse_color_inner(raw: &str) -> Result<Color, String> {
    Ok(match raw {
        "black" => Color::Black,
        "red" => Color::Red,
        "green" => Color::Green,
        "yellow" => Color::Yellow,
        "blue" => Color::Blue,
        "magenta" => Color::Magenta,
        "cyan" => Color::Cyan,
        "gray" | "grey" => Color::Grey,
        "dark gray" | "darkgray" | "dark grey" | "darkgrey" => Color::DarkGrey,
        "dark red" | "darkred" => Color::DarkRed,
        "dark green" | "darkgreen" => Color::DarkGreen,
        "dark yellow" | "darkyellow" => Color::DarkYellow,
        "dark blue" | "darkblue" => Color::DarkBlue,
        "dark magenta" | "darkmagenta" => Color::DarkMagenta,
        "dark cyan" | "darkcyan" => Color::DarkCyan,
        "white" => Color::White,
        rgb if rgb.starts_with("rgb(") => {
            let rgb = rgb.trim_start_matches("rgb(").trim_end_matches(")").split(',');
            let rgb = rgb
                .map(|c| c.trim().parse::<u8>())
                .collect::<Result<Vec<u8>, _>>()
                .map_err(|_| format!("Unable to parse color: {raw}"))?;
            if rgb.len() != 3 {
                return Err(format!("Unable to parse color: {raw}"));
            }
            Color::Rgb {
                r: rgb[0],
                g: rgb[1],
                b: rgb[2],
            }
        }
        hex if hex.starts_with("#") => {
            let hex = hex.trim_start_matches("#");
            if hex.len() != 6 {
                return Err(format!("Unable to parse color: {raw}"));
            }
            let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| format!("Unable to parse color: {raw}"))?;
            let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| format!("Unable to parse color: {raw}"))?;
            let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| format!("Unable to parse color: {raw}"))?;
            Color::Rgb { r, g, b }
        }
        c => {
            if let Ok(c) = c.parse::<u8>() {
                Color::AnsiValue(c)
            } else {
                return Err(format!("Unable to parse color: {raw}"));
            }
        }
    })
}

/// Custom deserialization for the AI model catalog that merges user-defined models with default models.
///
/// User-defined models in the configuration file will override any defaults with the same name.
/// Any default models not defined by the user will be added to the final catalog.
fn deserialize_catalog_with_defaults<'de, D>(deserializer: D) -> Result<BTreeMap<String, AiModelConfig>, D::Error>
where
    D: Deserializer<'de>,
{
    #[allow(unused_mut)]
    // Deserialize the map as provided in the user's config
    let mut user_catalog = BTreeMap::<String, AiModelConfig>::deserialize(deserializer)?;

    // Get the default catalog and merge it in
    #[cfg(not(test))]
    for (key, default_model) in default_ai_catalog() {
        user_catalog.entry(key).or_insert(default_model);
    }

    Ok(user_catalog)
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;
    use strum::IntoEnumIterator;

    use super::*;

    #[test]
    fn test_default_config() -> Result<()> {
        let config_str = fs::read_to_string("default_config.toml").wrap_err("Couldn't read default config file")?;
        let config: Config = toml::from_str(&config_str).wrap_err("Couldn't parse default config file")?;

        assert_eq!(Config::default(), config);

        Ok(())
    }

    #[test]
    fn test_default_keybindings_complete() {
        let config = KeyBindingsConfig::default();

        for action in KeyBindingAction::iter() {
            assert!(
                config.0.contains_key(&action),
                "Missing default binding for action: {action:?}"
            );
        }
    }

    #[test]
    fn test_default_keybindings_no_conflicts() {
        let config = KeyBindingsConfig::default();

        let conflicts = config.find_conflicts();
        assert_eq!(conflicts.len(), 0, "Key binding conflicts: {conflicts:?}");
    }

    #[test]
    fn test_keybinding_matches() {
        let binding = KeyBinding(vec![
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL),
            KeyEvent::from(KeyCode::Enter),
        ]);

        // Should match exact events
        assert!(binding.matches(&KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL)));
        assert!(binding.matches(&KeyEvent::from(KeyCode::Enter)));

        // Should not match events with different modifiers
        assert!(!binding.matches(&KeyEvent::new(
            KeyCode::Char('a'),
            KeyModifiers::CONTROL | KeyModifiers::ALT
        )));

        // Should not match different key codes
        assert!(!binding.matches(&KeyEvent::from(KeyCode::Esc)));
    }

    #[test]
    fn test_simple_keys() {
        assert_eq!(
            parse_key_event("a").unwrap(),
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty())
        );

        assert_eq!(
            parse_key_event("enter").unwrap(),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::empty())
        );

        assert_eq!(
            parse_key_event("esc").unwrap(),
            KeyEvent::new(KeyCode::Esc, KeyModifiers::empty())
        );
    }

    #[test]
    fn test_with_modifiers() {
        assert_eq!(
            parse_key_event("ctrl-a").unwrap(),
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL)
        );

        assert_eq!(
            parse_key_event("alt-enter").unwrap(),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT)
        );

        assert_eq!(
            parse_key_event("shift-esc").unwrap(),
            KeyEvent::new(KeyCode::Esc, KeyModifiers::SHIFT)
        );
    }

    #[test]
    fn test_multiple_modifiers() {
        assert_eq!(
            parse_key_event("ctrl-alt-a").unwrap(),
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL | KeyModifiers::ALT)
        );

        assert_eq!(
            parse_key_event("ctrl-shift-enter").unwrap(),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        );
    }

    #[test]
    fn test_invalid_keys() {
        let res = parse_key_event("invalid-key");
        assert_eq!(res, Err(String::from("Unable to parse key binding: invalid-key")));
    }

    #[test]
    fn test_parse_color_none() {
        let color = parse_color("none").unwrap();
        assert_eq!(color, None);
    }

    #[test]
    fn test_parse_color_simple() {
        let color = parse_color("red").unwrap();
        assert_eq!(color, Some(Color::Red));
    }

    #[test]
    fn test_parse_color_rgb() {
        let color = parse_color("rgb(50, 25, 15)").unwrap();
        assert_eq!(color, Some(Color::Rgb { r: 50, g: 25, b: 15 }));
    }

    #[test]
    fn test_parse_color_rgb_out_of_range() {
        let res = parse_color("rgb(500, 25, 15)");
        assert_eq!(res, Err(String::from("Unable to parse color: rgb(500, 25, 15)")));
    }

    #[test]
    fn test_parse_color_rgb_invalid() {
        let res = parse_color("rgb(50, 25, 15, 5)");
        assert_eq!(res, Err(String::from("Unable to parse color: rgb(50, 25, 15, 5)")));
    }

    #[test]
    fn test_parse_color_hex() {
        let color = parse_color("#4287f5").unwrap();
        assert_eq!(color, Some(Color::Rgb { r: 66, g: 135, b: 245 }));
    }

    #[test]
    fn test_parse_color_hex_out_of_range() {
        let res = parse_color("#4287fg");
        assert_eq!(res, Err(String::from("Unable to parse color: #4287fg")));
    }

    #[test]
    fn test_parse_color_hex_invalid() {
        let res = parse_color("#4287f50");
        assert_eq!(res, Err(String::from("Unable to parse color: #4287f50")));
    }

    #[test]
    fn test_parse_color_index() {
        let color = parse_color("6").unwrap();
        assert_eq!(color, Some(Color::AnsiValue(6)));
    }

    #[test]
    fn test_parse_color_fail() {
        let res = parse_color("1234");
        assert_eq!(res, Err(String::from("Unable to parse color: 1234")));
    }

    #[test]
    fn test_parse_style_empty() {
        let style = parse_style("").unwrap();
        assert_eq!(style, ContentStyle::new());
    }

    #[test]
    fn test_parse_style_default() {
        let style = parse_style("default").unwrap();
        assert_eq!(style, ContentStyle::new());
    }

    #[test]
    fn test_parse_style_simple() {
        let style = parse_style("red").unwrap();
        assert_eq!(style.foreground_color, Some(Color::Red));
        assert_eq!(style.attributes, Attributes::none());
    }

    #[test]
    fn test_parse_style_only_modifier() {
        let style = parse_style("bold").unwrap();
        assert_eq!(style.foreground_color, None);
        let mut expected_attributes = Attributes::none();
        expected_attributes.set(Attribute::Bold);
        assert_eq!(style.attributes, expected_attributes);
    }

    #[test]
    fn test_parse_style_with_modifier() {
        let style = parse_style("italic red").unwrap();
        assert_eq!(style.foreground_color, Some(Color::Red));
        let mut expected_attributes = Attributes::none();
        expected_attributes.set(Attribute::Italic);
        assert_eq!(style.attributes, expected_attributes);
    }

    #[test]
    fn test_parse_style_multiple_modifier() {
        let style = parse_style("underline dim dark red").unwrap();
        assert_eq!(style.foreground_color, Some(Color::DarkRed));
        let mut expected_attributes = Attributes::none();
        expected_attributes.set(Attribute::Underlined);
        expected_attributes.set(Attribute::Dim);
        assert_eq!(style.attributes, expected_attributes);
    }
}