uira-core 0.1.1

Shared types, events, protocol definitions, and configuration loading for Uira
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
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uira_memory::MemoryConfig;

#[path = "../schema/keybinds.rs"]
pub mod keybinds;
#[path = "../schema/theme.rs"]
pub mod theme;
pub use keybinds::KeybindsConfig;

/// Main Uira configuration
///
/// Configuration is loaded from (in priority order):
/// 1. `uira.jsonc` - JSON with comments
/// 2. `uira.json` - Standard JSON
/// 3. `uira.yml` / `uira.yaml` - YAML format
///
/// Also checks hidden variants (`.uira.*`) and `~/.config/uira/` for global config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiraConfig {
    /// TUI theme name (default, dark, light, dracula, nord)
    #[serde(default = "default_tui_theme")]
    pub theme: String,

    /// Optional per-color theme overrides using hex values (e.g. "#282a36")
    #[serde(default)]
    pub theme_colors: ThemeColorOverrides,

    /// Typos command settings (AI-assisted typo checking)
    #[serde(default)]
    pub typos: TyposSettings,

    /// Diagnostics command settings (AI-assisted lint/type error fixing)
    #[serde(default)]
    pub diagnostics: DiagnosticsSettings,

    /// Comments command settings (AI-assisted comment removal/preservation)
    #[serde(default)]
    pub comments: CommentsSettings,

    /// OpenCode server settings
    #[serde(default)]
    pub opencode: OpencodeSettings,

    /// MCP (Model Context Protocol) settings
    #[serde(default)]
    pub mcp: McpSettings,

    /// Agent settings
    #[serde(default)]
    pub agents: AgentSettings,

    /// Git hooks configuration
    #[serde(default)]
    pub hooks: HooksConfig,

    /// AI hooks for typos checking and other workflows
    #[serde(default)]
    pub ai_hooks: Option<AiHooksConfig>,

    /// Score-based verification goals
    #[serde(default)]
    pub goals: GoalsConfig,

    /// Context compaction settings
    #[serde(default)]
    pub compaction: CompactionSettings,

    /// Permission rules for tool execution
    #[serde(default)]
    pub permissions: PermissionsSettings,

    /// Skills settings for loading SKILL.md files
    #[serde(default)]
    pub skills: SkillsSettings,

    /// Gateway settings for WebSocket control plane
    #[serde(default)]
    pub gateway: GatewaySettings,

    /// Channel settings for multi-channel messaging
    #[serde(default)]
    pub channels: ChannelSettings,

    /// Provider-specific settings
    #[serde(default)]
    pub providers: ProvidersSettings,

    /// TUI keybindings configuration
    #[serde(default)]
    pub keybinds: KeybindsConfig,

    #[serde(default)]
    pub sidebar: SidebarConfig,


    /// Whether to show the startup logo in the chat view (default: true)
    #[serde(default = "default_true")]
    pub show_logo: bool,
    #[serde(default)]
    pub memory: MemoryConfig,
}

impl Default for UiraConfig {
    fn default() -> Self {
        Self {
            theme: default_tui_theme(),
            theme_colors: ThemeColorOverrides::default(),
            typos: TyposSettings::default(),
            diagnostics: DiagnosticsSettings::default(),
            comments: CommentsSettings::default(),
            opencode: OpencodeSettings::default(),
            mcp: McpSettings::default(),
            agents: AgentSettings::default(),
            hooks: HooksConfig::default(),
            ai_hooks: None,
            goals: GoalsConfig::default(),
            compaction: CompactionSettings::default(),
            permissions: PermissionsSettings::default(),
            skills: SkillsSettings::default(),
            gateway: GatewaySettings::default(),
            channels: ChannelSettings::default(),
            providers: ProvidersSettings::default(),
            keybinds: KeybindsConfig::default(),
            sidebar: SidebarConfig::default(),
            show_logo: true,
            memory: MemoryConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SidebarConfig {
    #[serde(default = "default_true")]
    pub show_context: bool,

    #[serde(default = "default_true")]
    pub show_mcp: bool,

    #[serde(default = "default_true")]
    pub show_todos: bool,

    #[serde(default = "default_true")]
    pub show_files: bool,
}

impl Default for SidebarConfig {
    fn default() -> Self {
        Self {
            show_context: true,
            show_mcp: true,
            show_todos: true,
            show_files: true,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ThemeColorOverrides {
    #[serde(default)]
    pub bg: Option<String>,

    #[serde(default)]
    pub fg: Option<String>,

    #[serde(default)]
    pub accent: Option<String>,

    #[serde(default)]
    pub error: Option<String>,

    #[serde(default)]
    pub warning: Option<String>,

    #[serde(default)]
    pub success: Option<String>,

    #[serde(default)]
    pub borders: Option<String>,
}

fn default_tui_theme() -> String {
    "default".to_string()
}

fn default_true() -> bool {
    true
}

// ============================================================================
// OpenCode Configuration
// ============================================================================

/// OpenCode server settings
///
/// Configuration for connecting to OpenCode server for agent-based model routing.
///
/// # Example
///
/// ```yaml
/// opencode:
///   host: 127.0.0.1
///   port: 4096
///   timeout_secs: 120
///   auto_start: true
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpencodeSettings {
    /// Server host (default: 127.0.0.1)
    #[serde(default = "default_opencode_host")]
    pub host: String,

    /// Server port (default: 4096)
    #[serde(default = "default_opencode_port")]
    pub port: u16,

    /// Request timeout in seconds (default: 120)
    #[serde(default = "default_opencode_timeout")]
    pub timeout_secs: u64,

    /// Auto-start OpenCode server (default: true)
    #[serde(default = "default_opencode_auto_start")]
    pub auto_start: bool,
}

impl Default for OpencodeSettings {
    fn default() -> Self {
        Self {
            host: default_opencode_host(),
            port: default_opencode_port(),
            timeout_secs: default_opencode_timeout(),
            auto_start: default_opencode_auto_start(),
        }
    }
}

fn default_opencode_host() -> String {
    "127.0.0.1".to_string()
}

fn default_opencode_port() -> u16 {
    4096
}

fn default_opencode_timeout() -> u64 {
    120
}

fn default_opencode_auto_start() -> bool {
    true
}

// ============================================================================
// Typos Configuration
// ============================================================================

/// Typos command settings for AI-assisted typo checking
///
/// Configuration for the `uira typos --ai` command.
/// The AI workflow uses an embedded agent with full tool access.
///
/// # Example
///
/// ```yaml
/// typos:
///   ai:
///     model: "anthropic/claude-sonnet-4-20250514"
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TyposSettings {
    /// AI settings for typos checking
    #[serde(default)]
    pub ai: TyposAiSettings,
}

/// AI settings for typos command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TyposAiSettings {
    /// Model identifier (e.g., "anthropic/claude-sonnet-4-20250514")
    #[serde(default = "default_typos_model")]
    pub model: String,
}

impl Default for TyposAiSettings {
    fn default() -> Self {
        Self {
            model: default_typos_model(),
        }
    }
}

impl TyposAiSettings {
    /// Parse model string into (provider, model) tuple
    pub fn parse_model(&self) -> (String, String) {
        if let Some((provider, model)) = self.model.split_once('/') {
            (provider.to_string(), model.to_string())
        } else {
            ("anthropic".to_string(), self.model.clone())
        }
    }
}

fn default_typos_model() -> String {
    format!("anthropic/{}", crate::DEFAULT_ANTHROPIC_MODEL)
}

// ============================================================================
// Diagnostics Configuration
// ============================================================================

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiagnosticsSettings {
    #[serde(default)]
    pub ai: DiagnosticsAiSettings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticsAiSettings {
    #[serde(default = "default_diagnostics_model")]
    pub model: String,

    #[serde(default = "default_diagnostics_severity")]
    pub severity: String,

    #[serde(default = "default_diagnostics_confidence")]
    pub confidence_threshold: f64,

    #[serde(default = "default_diagnostics_languages")]
    pub languages: Vec<String>,
}

impl Default for DiagnosticsAiSettings {
    fn default() -> Self {
        Self {
            model: default_diagnostics_model(),
            severity: default_diagnostics_severity(),
            confidence_threshold: default_diagnostics_confidence(),
            languages: default_diagnostics_languages(),
        }
    }
}

impl DiagnosticsAiSettings {
    pub fn parse_model(&self) -> (String, String) {
        if let Some((provider, model)) = self.model.split_once('/') {
            (provider.to_string(), model.to_string())
        } else {
            ("anthropic".to_string(), self.model.clone())
        }
    }
}

fn default_diagnostics_model() -> String {
    format!("anthropic/{}", crate::DEFAULT_ANTHROPIC_MODEL)
}

fn default_diagnostics_severity() -> String {
    "error".to_string()
}

fn default_diagnostics_confidence() -> f64 {
    0.8
}

fn default_diagnostics_languages() -> Vec<String> {
    vec![
        "js".to_string(),
        "ts".to_string(),
        "tsx".to_string(),
        "jsx".to_string(),
    ]
}

// ============================================================================
// Comments Configuration
// ============================================================================

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CommentsSettings {
    #[serde(default)]
    pub ai: CommentsAiSettings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommentsAiSettings {
    #[serde(default = "default_comments_model")]
    pub model: String,

    #[serde(default = "default_comments_pragma")]
    pub pragma_format: String,

    #[serde(default = "default_comments_docstrings")]
    pub include_docstrings: bool,
}

impl Default for CommentsAiSettings {
    fn default() -> Self {
        Self {
            model: default_comments_model(),
            pragma_format: default_comments_pragma(),
            include_docstrings: default_comments_docstrings(),
        }
    }
}

impl CommentsAiSettings {
    pub fn parse_model(&self) -> (String, String) {
        if let Some((provider, model)) = self.model.split_once('/') {
            (provider.to_string(), model.to_string())
        } else {
            ("anthropic".to_string(), self.model.clone())
        }
    }
}

fn default_comments_model() -> String {
    format!("anthropic/{}", crate::DEFAULT_ANTHROPIC_MODEL)
}

fn default_comments_pragma() -> String {
    "@uira-allow".to_string()
}

fn default_comments_docstrings() -> bool {
    false
}

/// MCP (Model Context Protocol) settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpSettings {
    /// Enabled MCP servers
    #[serde(default, deserialize_with = "deserialize_mcp_servers")]
    pub servers: Vec<NamedMcpServerConfig>,
}

impl McpSettings {
    pub fn get(&self, name: &str) -> Option<&McpServerConfig> {
        self.servers
            .iter()
            .find(|server| server.name == name)
            .map(|server| &server.config)
    }

    pub fn contains_key(&self, name: &str) -> bool {
        self.get(name).is_some()
    }
}

/// Individual MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Command to run the server
    pub command: String,

    /// Arguments for the command
    #[serde(default)]
    pub args: Vec<String>,

    /// Environment variables
    #[serde(default)]
    pub env: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NamedMcpServerConfig {
    pub name: String,
    #[serde(flatten)]
    pub config: McpServerConfig,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum McpServersRepr {
    List(Vec<NamedMcpServerConfig>),
    Map(HashMap<String, McpServerConfig>),
}

fn deserialize_mcp_servers<'de, D>(deserializer: D) -> Result<Vec<NamedMcpServerConfig>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let repr = McpServersRepr::deserialize(deserializer)?;
    let mut servers = match repr {
        McpServersRepr::List(list) => list,
        McpServersRepr::Map(map) => map
            .into_iter()
            .map(|(name, config)| NamedMcpServerConfig { name, config })
            .collect(),
    };

    servers.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(servers)
}

/// Agent settings - a map of agent names to their configurations
///
/// In YAML/JSON:
/// ```yaml
/// agents:
///   explore:
///     model: "opencode/gpt-5-nano"
///   librarian:
///     model: "opencode/big-pickle"
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentSettings {
    #[serde(flatten)]
    pub agents: HashMap<String, AgentConfig>,
}

/// Individual agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent model override (uses ai.model if not specified)
    pub model: Option<String>,

    /// Agent-specific settings
    #[serde(default)]
    pub settings: HashMap<String, serde_json::Value>,
}

/// Git hooks configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HooksConfig {
    /// Pre-commit hook configuration
    #[serde(default)]
    pub pre_commit: Option<HookConfig>,

    /// Post-commit hook configuration
    #[serde(default)]
    pub post_commit: Option<HookConfig>,

    /// Pre-push hook configuration
    #[serde(default)]
    pub pre_push: Option<HookConfig>,
}

/// Individual hook configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookConfig {
    /// Run commands in parallel
    #[serde(default)]
    pub parallel: bool,

    /// Commands to execute
    #[serde(default)]
    pub commands: Vec<HookCommand>,
}

/// Individual hook command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookCommand {
    /// Command name
    pub name: String,

    /// Command to run
    pub run: String,

    /// Glob pattern for files to match
    #[serde(default)]
    pub glob: Option<String>,

    /// Stop execution on failure
    #[serde(default)]
    pub on_fail: Option<String>,
}

/// AI hooks configuration for typos checking and other workflows
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiHooksConfig {
    /// Pre-check hook
    #[serde(default)]
    pub pre_check: Option<Vec<AiHookCommand>>,

    /// Post-check hook
    #[serde(default)]
    pub post_check: Option<Vec<AiHookCommand>>,

    /// Pre-AI hook
    #[serde(default)]
    pub pre_ai: Option<Vec<AiHookCommand>>,

    /// Post-AI hook
    #[serde(default)]
    pub post_ai: Option<Vec<AiHookCommand>>,

    /// Pre-fix hook
    #[serde(default)]
    pub pre_fix: Option<Vec<AiHookCommand>>,

    /// Post-fix hook
    #[serde(default)]
    pub post_fix: Option<Vec<AiHookCommand>>,
}

/// AI hook command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiHookCommand {
    /// Glob matcher for files
    #[serde(default)]
    pub matcher: Option<String>,

    /// Command to run
    pub run: String,

    /// Stop execution on failure
    #[serde(default)]
    pub on_fail: Option<String>,
}

// ============================================================================
// Goal Verification Configuration
// ============================================================================

/// Goal configuration for score-based verification
///
/// Goals define measurable success criteria that can be checked during
/// agent loops (ralph, ultrawork). Each goal runs a command that outputs
/// a score (0-100), and the goal passes when the score meets the target.
///
/// # Example
///
/// ```yaml
/// goals:
///   - name: pixel-match
///     workspace: .uira/goals/pixel-match/
///     command: bun run check.ts
///     target: 99.9
///
///   - name: test-coverage
///     command: bun run coverage --json | jq '.total'
///     target: 80
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalConfig {
    /// Unique name for this goal
    pub name: String,

    /// Working directory for the command (relative to project root)
    /// If specified, the command runs inside this directory.
    /// Useful for isolating goal-specific files (reference images, scripts, etc.)
    #[serde(default)]
    pub workspace: Option<String>,

    /// Command to execute that outputs a score (0-100) to stdout
    /// The command must:
    /// - Exit with code 0 on success
    /// - Print a single number (0-100) to stdout
    /// - Use stderr for logging/debug output
    pub command: String,

    /// Target score threshold (0-100) to consider the goal passed
    pub target: f64,

    /// Optional timeout in seconds for the command (default: 60)
    #[serde(default = "default_goal_timeout")]
    pub timeout_secs: u64,

    /// Whether this goal is enabled (default: true)
    #[serde(default = "default_goal_enabled")]
    pub enabled: bool,

    /// Optional description of what this goal measures
    #[serde(default)]
    pub description: Option<String>,
}

fn default_goal_timeout() -> u64 {
    60
}

fn default_goal_enabled() -> bool {
    true
}

/// Goals configuration section
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalsConfig {
    /// List of goal definitions
    #[serde(default)]
    pub goals: Vec<GoalConfig>,

    /// Check interval in seconds for continuous verification (default: 30)
    #[serde(default = "default_check_interval")]
    pub check_interval_secs: u64,

    /// Maximum iterations before giving up (default: 100)
    #[serde(default = "default_max_iterations")]
    pub max_iterations: u32,

    /// Whether to run goals automatically at end of each iteration (default: true)
    #[serde(default = "default_auto_verify")]
    pub auto_verify: bool,
}

impl Default for GoalsConfig {
    fn default() -> Self {
        Self {
            goals: Vec::new(),
            check_interval_secs: default_check_interval(),
            max_iterations: default_max_iterations(),
            auto_verify: default_auto_verify(),
        }
    }
}

fn default_check_interval() -> u64 {
    30
}

fn default_max_iterations() -> u32 {
    100
}

fn default_auto_verify() -> bool {
    true
}

// ============================================================================
// Compaction Configuration
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompactionSettings {
    #[serde(default = "default_compaction_enabled")]
    pub enabled: bool,

    #[serde(default = "default_compaction_threshold")]
    pub threshold: f64,

    #[serde(default = "default_protected_tokens")]
    pub protected_tokens: usize,

    #[serde(default = "default_compaction_strategy")]
    pub strategy: String,

    #[serde(default)]
    pub summarization_model: Option<String>,
}

impl Default for CompactionSettings {
    fn default() -> Self {
        Self {
            enabled: default_compaction_enabled(),
            threshold: default_compaction_threshold(),
            protected_tokens: default_protected_tokens(),
            strategy: default_compaction_strategy(),
            summarization_model: None,
        }
    }
}

fn default_compaction_enabled() -> bool {
    true
}

fn default_compaction_threshold() -> f64 {
    0.8
}

fn default_protected_tokens() -> usize {
    40_000
}

fn default_compaction_strategy() -> String {
    "summarize".to_string()
}

// ============================================================================
// Providers Configuration
// ============================================================================

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProvidersSettings {
    #[serde(default)]
    pub anthropic: AnthropicProviderSettings,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnthropicProviderSettings {
    #[serde(default)]
    pub payload_log: PayloadLogSettings,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PayloadLogSettings {
    #[serde(default)]
    pub enabled: bool,

    #[serde(default)]
    pub path: Option<String>,
}

// ============================================================================
// Permissions Configuration
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PermissionsSettings {
    #[serde(default)]
    pub rules: Vec<PermissionRuleConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionRuleConfig {
    #[serde(default)]
    pub name: Option<String>,

    pub permission: String,

    pub pattern: String,

    pub action: PermissionActionConfig,

    #[serde(default)]
    pub comment: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PermissionActionConfig {
    #[default]
    Allow,
    Deny,
    Ask,
}

// Default value functions

// ============================================================================
// Skills Configuration
// ============================================================================

/// Skills settings for loading SKILL.md instruction files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillsSettings {
    /// Whether skills loading is enabled
    #[serde(default)]
    pub enabled: bool,

    /// Directories to scan for SKILL.md files
    #[serde(default = "default_skills_paths")]
    pub paths: Vec<String>,

    /// List of active skill names to load
    #[serde(default)]
    pub active: Vec<String>,
}

impl Default for SkillsSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            paths: default_skills_paths(),
            active: Vec::new(),
        }
    }
}

fn default_skills_paths() -> Vec<String> {
    vec!["~/.uira/skills".to_string(), ".uira/skills".to_string()]
}

// ============================================================================
// Gateway Configuration
// ============================================================================

/// Gateway settings for the WebSocket control plane
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewaySettings {
    /// Whether the gateway is enabled
    #[serde(default)]
    pub enabled: bool,

    /// Host to bind the gateway server
    #[serde(default = "default_gateway_host")]
    pub host: String,

    /// Port to bind the gateway server
    #[serde(default = "default_gateway_port")]
    pub port: u16,

    /// Maximum number of concurrent sessions
    #[serde(default = "default_max_sessions")]
    pub max_sessions: usize,

    /// Default model for gateway sessions
    #[serde(default = "default_gateway_model")]
    pub model: String,

    /// Default provider for gateway sessions
    #[serde(default = "default_gateway_provider")]
    pub provider: String,

    /// Default orchestrator agent for new sessions.
    ///
    /// Controls which primary agent personality is used:
    /// - "balanced" (default): Delegates heavily, asks before acting
    /// - "autonomous": Deep worker that completes tasks without asking
    /// - "orchestrator": Conductor that never writes code, only delegates
    ///
    /// Can be overridden per-session via SessionConfig.
    #[serde(default = "default_gateway_agent")]
    pub default_agent: String,

    /// Optional authentication token for gateway access
    #[serde(default)]
    pub auth_token: Option<String>,

    /// Idle timeout in seconds before a session is cleaned up
    #[serde(default = "default_idle_timeout")]
    pub idle_timeout_secs: Option<u64>,

    /// Working directory for gateway-spawned sessions
    #[serde(default)]
    pub working_directory: Option<String>,
}

impl Default for GatewaySettings {
    fn default() -> Self {
        Self {
            enabled: false,
            host: default_gateway_host(),
            port: default_gateway_port(),
            max_sessions: default_max_sessions(),
            model: default_gateway_model(),
            provider: default_gateway_provider(),
            default_agent: default_gateway_agent(),
            auth_token: None,
            idle_timeout_secs: default_idle_timeout(),
            working_directory: None,
        }
    }
}

fn default_gateway_host() -> String {
    "127.0.0.1".to_string()
}

fn default_gateway_port() -> u16 {
    18790
}

fn default_max_sessions() -> usize {
    10
}

fn default_gateway_model() -> String {
    crate::DEFAULT_ANTHROPIC_MODEL.to_string()
}

fn default_gateway_provider() -> String {
    "anthropic".to_string()
}

fn default_gateway_agent() -> String {
    "balanced".to_string()
}

fn default_idle_timeout() -> Option<u64> {
    Some(1800)
}

// ============================================================================
// Channel Configuration
// ============================================================================

/// Channel settings for multi-channel messaging
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ChannelSettings {
    #[serde(default)]
    pub telegram: Option<TelegramChannelConfig>,

    #[serde(default)]
    pub telegram_accounts: Vec<TelegramChannelConfig>,

    #[serde(default)]
    pub slack: Option<SlackChannelConfig>,

    #[serde(default)]
    pub slack_accounts: Vec<SlackChannelConfig>,

    #[serde(default)]
    pub discord: Option<DiscordChannelConfig>,

    #[serde(default)]
    pub discord_accounts: Vec<DiscordChannelConfig>,
}

fn default_account_id() -> String {
    "default".to_string()
}

fn default_stream_mode() -> String {
    "partial".to_string()
}

fn default_stream_throttle_ms() -> u64 {
    300
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelegramChannelConfig {
    #[serde(default = "default_account_id")]
    pub account_id: String,

    pub bot_token: String,

    #[serde(default)]
    pub allowed_users: Vec<String>,

    #[serde(default)]
    pub active_skills: Vec<String>,

    /// Streaming mode: "off" disables streaming, "partial" enables progressive message editing
    /// Default: "partial"
    #[serde(default = "default_stream_mode")]
    pub stream_mode: String,

    /// Minimum interval between message edits in milliseconds.
    /// Default: 300
    #[serde(default = "default_stream_throttle_ms")]
    pub stream_throttle_ms: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlackChannelConfig {
    #[serde(default = "default_account_id")]
    pub account_id: String,

    pub bot_token: String,

    pub app_token: String,

    #[serde(default)]
    pub allowed_channels: Vec<String>,

    #[serde(default)]
    pub active_skills: Vec<String>,
}

fn default_discord_max_message_length() -> usize {
    2000
}

fn default_discord_max_lines_per_message() -> usize {
    17
}

fn default_group_policy() -> String {
    "open".to_string()
}

fn default_dm_policy() -> String {
    "pairing".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscordDmConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,

    #[serde(default = "default_dm_policy")]
    pub policy: String,

    #[serde(default)]
    pub allow_from: Vec<String>,

    #[serde(default)]
    pub group_enabled: bool,

    #[serde(default)]
    pub group_channels: Vec<String>,
}

impl Default for DiscordDmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            policy: default_dm_policy(),
            allow_from: Vec::new(),
            group_enabled: false,
            group_channels: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscordGuildChannelConfig {
    #[serde(default = "default_true")]
    pub allow: bool,

    #[serde(default)]
    pub require_mention: bool,

    #[serde(default)]
    pub skills: Option<Vec<String>>,

    #[serde(default = "default_true")]
    pub enabled: bool,

    #[serde(default)]
    pub users: Vec<String>,

    #[serde(default)]
    pub roles: Vec<String>,

    #[serde(default)]
    pub system_prompt: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscordGuildEntry {
    #[serde(default)]
    pub slug: Option<String>,

    #[serde(default)]
    pub require_mention: bool,

    #[serde(default)]
    pub reaction_notifications: Option<String>,

    #[serde(default)]
    pub users: Vec<String>,

    #[serde(default)]
    pub roles: Vec<String>,

    #[serde(default)]
    pub channels: HashMap<String, DiscordGuildChannelConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscordActionConfig {
    #[serde(default = "default_true")]
    pub reactions: bool,
    #[serde(default = "default_true")]
    pub stickers: bool,
    #[serde(default = "default_true")]
    pub polls: bool,
    #[serde(default = "default_true")]
    pub permissions: bool,
    #[serde(default = "default_true")]
    pub messages: bool,
    #[serde(default = "default_true")]
    pub threads: bool,
    #[serde(default = "default_true")]
    pub pins: bool,
    #[serde(default = "default_true")]
    pub search: bool,
    #[serde(default = "default_true")]
    pub member_info: bool,
    #[serde(default = "default_true")]
    pub role_info: bool,
    #[serde(default = "default_true")]
    pub roles: bool,
    #[serde(default = "default_true")]
    pub channel_info: bool,
    #[serde(default = "default_true")]
    pub events: bool,
    #[serde(default = "default_true")]
    pub moderation: bool,
    #[serde(default = "default_true")]
    pub emoji_uploads: bool,
    #[serde(default = "default_true")]
    pub sticker_uploads: bool,
    #[serde(default = "default_true")]
    pub channels: bool,
    #[serde(default)]
    pub presence: bool,
}

impl Default for DiscordActionConfig {
    fn default() -> Self {
        Self {
            reactions: true,
            stickers: true,
            polls: true,
            permissions: true,
            messages: true,
            threads: true,
            pins: true,
            search: true,
            member_info: true,
            role_info: true,
            roles: true,
            channel_info: true,
            events: true,
            moderation: true,
            emoji_uploads: true,
            sticker_uploads: true,
            channels: true,
            presence: false,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscordIntentsConfig {
    #[serde(default)]
    pub presence: bool,
    #[serde(default)]
    pub guild_members: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscordComponentsConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscordChannelConfig {
    #[serde(default = "default_account_id")]
    pub account_id: String,

    pub bot_token: String,

    #[serde(default = "default_true")]
    pub enabled: bool,

    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub proxy: Option<String>,

    #[serde(default)]
    pub allow_bots: bool,

    #[serde(default = "default_group_policy")]
    pub group_policy: String,

    #[serde(default = "default_discord_max_message_length")]
    pub text_chunk_limit: usize,

    #[serde(default = "default_discord_max_lines_per_message")]
    pub max_lines_per_message: usize,

    #[serde(default = "default_stream_mode")]
    pub stream_mode: String,

    #[serde(default = "default_stream_throttle_ms")]
    pub stream_throttle_ms: u64,

    #[serde(default)]
    pub history_limit: Option<usize>,

    #[serde(default)]
    pub dm_history_limit: Option<usize>,

    #[serde(default)]
    pub allowed_users: Vec<String>,

    #[serde(default)]
    pub active_skills: Vec<String>,

    #[serde(default)]
    pub dm: Option<DiscordDmConfig>,

    #[serde(default)]
    pub guilds: HashMap<String, DiscordGuildEntry>,

    #[serde(default)]
    pub actions: Option<DiscordActionConfig>,

    #[serde(default)]
    pub intents: Option<DiscordIntentsConfig>,

    #[serde(default)]
    pub components: Option<DiscordComponentsConfig>,

    #[serde(default)]
    pub activity: Option<String>,

    #[serde(default)]
    pub status: Option<String>,

    #[serde(default)]
    pub activity_type: Option<u8>,

    #[serde(default)]
    pub activity_url: Option<String>,
}

// ============================================================================
// Memory Configuration
// ============================================================================



// ============================================================================
// Keybindings Configuration
// ============================================================================

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

    #[test]
    fn test_deserialize_hook_config() {
        let yaml = r#"
parallel: true
commands:
  - name: fmt
    run: cargo fmt --check
  - name: clippy
    run: cargo clippy -- -D warnings
    glob: "**/*.rs"
"#;
        let hook: HookConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(hook.parallel);
        assert_eq!(hook.commands.len(), 2);
        assert_eq!(hook.commands[0].name, "fmt");
        assert_eq!(hook.commands[1].glob, Some("**/*.rs".to_string()));
    }

    #[test]
    fn test_deserialize_full_config() {
        let yaml = r#"
hooks:
  pre_commit:
    parallel: true
    commands:
      - name: fmt
        run: cargo fmt --check
  post_commit:
    parallel: false
    commands:
      - name: auto-push
        run: git push origin HEAD
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.hooks.pre_commit.is_some());
        assert!(config.hooks.post_commit.is_some());
    }

    #[test]
    fn test_deserialize_goal_config() {
        let yaml = r#"
name: pixel-match
workspace: .uira/goals/pixel-match/
command: bun run check.ts
target: 99.9
"#;
        let goal: GoalConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(goal.name, "pixel-match");
        assert_eq!(goal.workspace, Some(".uira/goals/pixel-match/".to_string()));
        assert_eq!(goal.command, "bun run check.ts");
        assert!((goal.target - 99.9).abs() < 0.01);
        assert_eq!(goal.timeout_secs, 60);
        assert!(goal.enabled);
    }

    #[test]
    fn test_deserialize_goals_config() {
        let yaml = r#"
goals:
  - name: pixel-match
    workspace: .uira/goals/pixel-match/
    command: bun run check.ts
    target: 99.9
  - name: test-coverage
    command: "bun run coverage --json | jq '.total'"
    target: 80
    enabled: false
check_interval_secs: 15
max_iterations: 50
"#;
        let config: GoalsConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.goals.len(), 2);
        assert_eq!(config.goals[0].name, "pixel-match");
        assert_eq!(config.goals[1].name, "test-coverage");
        assert!(!config.goals[1].enabled);
        assert_eq!(config.check_interval_secs, 15);
        assert_eq!(config.max_iterations, 50);
    }

    #[test]
    fn test_deserialize_config_with_goals() {
        let yaml = r#"
typos:
  ai:
    model: anthropic/claude-sonnet-4-20250514

goals:
  goals:
    - name: lighthouse-perf
      command: ./scripts/lighthouse-check.sh
      target: 90
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.goals.goals.len(), 1);
        assert_eq!(config.goals.goals[0].name, "lighthouse-perf");
        assert!((config.goals.goals[0].target - 90.0).abs() < 0.01);
    }

    #[test]
    fn test_goal_config_defaults() {
        let yaml = r#"
name: simple
command: echo 100
target: 100
"#;
        let goal: GoalConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(goal.timeout_secs, 60);
        assert!(goal.enabled);
        assert!(goal.workspace.is_none());
        assert!(goal.description.is_none());
    }

    #[test]
    fn test_goals_config_defaults() {
        let config = GoalsConfig::default();
        assert!(config.goals.is_empty());
        assert_eq!(config.check_interval_secs, 30);
        assert_eq!(config.max_iterations, 100);
        assert!(config.auto_verify);
    }

    #[test]
    fn test_diagnostics_settings_defaults() {
        let settings = DiagnosticsSettings::default();
        assert_eq!(settings.ai.model, "anthropic/claude-sonnet-4-20250514");
        assert_eq!(settings.ai.severity, "error");
        assert!((settings.ai.confidence_threshold - 0.8).abs() < 0.01);
        assert_eq!(settings.ai.languages, vec!["js", "ts", "tsx", "jsx"]);
    }

    #[test]
    fn test_diagnostics_settings_parse() {
        let yaml = r#"
ai:
  model: openai/gpt-4o
  severity: warning
  confidence_threshold: 0.9
  languages:
    - ts
    - rust
"#;
        let settings: DiagnosticsSettings = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(settings.ai.model, "openai/gpt-4o");
        assert_eq!(settings.ai.severity, "warning");
        assert!((settings.ai.confidence_threshold - 0.9).abs() < 0.01);
        assert_eq!(settings.ai.languages, vec!["ts", "rust"]);

        let (provider, model) = settings.ai.parse_model();
        assert_eq!(provider, "openai");
        assert_eq!(model, "gpt-4o");
    }

    #[test]
    fn test_comments_settings_defaults() {
        let settings = CommentsSettings::default();
        assert_eq!(settings.ai.model, "anthropic/claude-sonnet-4-20250514");
        assert_eq!(settings.ai.pragma_format, "@uira-allow");
        assert!(!settings.ai.include_docstrings);
    }

    #[test]
    fn test_comments_settings_parse() {
        let yaml = r#"
ai:
  model: anthropic/claude-opus-4
  pragma_format: "@allow-comment"
  include_docstrings: true
"#;
        let settings: CommentsSettings = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(settings.ai.model, "anthropic/claude-opus-4");
        assert_eq!(settings.ai.pragma_format, "@allow-comment");
        assert!(settings.ai.include_docstrings);
    }

    #[test]
    fn test_full_config_with_diagnostics_comments() {
        let yaml = r#"
typos:
  ai:
    model: anthropic/claude-sonnet-4-20250514

diagnostics:
  ai:
    severity: error
    languages:
      - ts
      - tsx

comments:
  ai:
    include_docstrings: true
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.diagnostics.ai.severity, "error");
        assert_eq!(config.diagnostics.ai.languages, vec!["ts", "tsx"]);
        assert!(config.comments.ai.include_docstrings);
    }

    #[test]
    fn test_permissions_settings_defaults() {
        let settings = PermissionsSettings::default();
        assert!(settings.rules.is_empty());
    }

    #[test]
    fn test_permissions_settings_parse() {
        let yaml = r#"
rules:
  - permission: "file:read"
    pattern: "**"
    action: allow
  - permission: "file:write"
    pattern: "src/**"
    action: allow
    name: "allow-src-writes"
  - permission: "shell:execute"
    pattern: "**"
    action: ask
"#;
        let settings: PermissionsSettings = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(settings.rules.len(), 3);
        assert_eq!(settings.rules[0].permission, "file:read");
        assert_eq!(settings.rules[0].action, PermissionActionConfig::Allow);
        assert_eq!(settings.rules[1].name, Some("allow-src-writes".to_string()));
        assert_eq!(settings.rules[2].action, PermissionActionConfig::Ask);
    }

    #[test]
    fn test_full_config_with_permissions() {
        let yaml = r#"
permissions:
  rules:
    - permission: "file:write"
      pattern: "**/.env*"
      action: deny
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.permissions.rules.len(), 1);
        assert_eq!(
            config.permissions.rules[0].action,
            PermissionActionConfig::Deny
        );
    }

    #[test]
    fn test_mcp_servers_deserialize_from_list() {
        let yaml = r#"
mcp:
   servers:
     - name: filesystem
       command: npx -y @anthropic/mcp-server-filesystem /tmp
     - name: github
       command: npx -y @anthropic/mcp-server-github
       env:
         GITHUB_TOKEN: ${GITHUB_TOKEN}
"#;

        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.mcp.servers.len(), 2);
        assert!(config.mcp.contains_key("filesystem"));
        assert!(config.mcp.contains_key("github"));
        assert_eq!(
            config.mcp.get("filesystem").unwrap().command,
            "npx -y @anthropic/mcp-server-filesystem /tmp"
        );
    }

    #[test]
    fn test_mcp_servers_deserialize_from_map_legacy_format() {
        let yaml = r#"
mcp:
   servers:
     context7:
       command: npx
       args: ["-y", "@upstash/context7-mcp"]
     exa:
       command: npx
       args: ["-y", "exa-mcp-server"]
"#;

        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.mcp.servers.len(), 2);
        assert!(config.mcp.contains_key("context7"));
        assert!(config.mcp.contains_key("exa"));
        assert_eq!(
            config.mcp.get("context7").unwrap().args,
            vec!["-y".to_string(), "@upstash/context7-mcp".to_string()]
        );
    }

    #[test]
    fn test_tui_theme_defaults() {
        let config = UiraConfig::default();
        assert_eq!(config.theme, "default");
        assert!(config.theme_colors.bg.is_none());
        assert!(config.theme_colors.accent.is_none());
    }

    #[test]
    fn test_tui_theme_parsing() {
        let yaml = r##"
theme: dracula
theme_colors:
    accent: "#ff79c6"
    borders: "#6272a4"
"##;

        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(config.theme, "dracula");
        assert_eq!(config.theme_colors.accent, Some("#ff79c6".to_string()));
        assert_eq!(config.theme_colors.borders, Some("#6272a4".to_string()));
    }

    #[test]
    fn test_sidebar_config_defaults() {
        let config = UiraConfig::default();
        assert!(config.sidebar.show_context);
        assert!(config.sidebar.show_mcp);
        assert!(config.sidebar.show_todos);
        assert!(config.sidebar.show_files);
    }

    #[test]
    fn test_sidebar_config_deserialization() {
        let yaml = r#"
sidebar:
  show_context: true
  show_mcp: false
  show_todos: true
  show_files: true
"#;

        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.sidebar.show_context);
        assert!(!config.sidebar.show_mcp);
        assert!(config.sidebar.show_todos);
        assert!(config.sidebar.show_files);
    }

    #[test]
    fn test_memory_settings_defaults() {
        let settings = MemoryConfig::default();
        assert!(!settings.enabled);
        assert!(settings.storage_path.contains("memory.db"));
        assert_eq!(settings.embedding_model, "text-embedding-3-small");
        assert_eq!(settings.embedding_dimension, 1536);
        assert_eq!(settings.embedding_api_key_env, "OPENAI_API_KEY");
        assert!(settings.auto_recall);
        assert!(settings.auto_capture);
        assert_eq!(settings.max_recall_results, 5);
        assert!(settings.container_tag.starts_with("project-") || settings.container_tag == "default");
    }

    #[test]
    fn test_full_config_with_memory() {
        let yaml = r#"
memory:
  enabled: true
  storage_path: "/tmp/test-memory.db"
  embedding_model: "text-embedding-3-large"
  embedding_dimension: 3072
  max_recall_results: 10
  container_tag: "project-x"
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.memory.enabled);
        assert_eq!(config.memory.storage_path, "/tmp/test-memory.db");
        assert_eq!(config.memory.embedding_model, "text-embedding-3-large");
        assert_eq!(config.memory.embedding_dimension, 3072);
        assert_eq!(config.memory.max_recall_results, 10);
        assert_eq!(config.memory.container_tag, "project-x");
        assert!(config.memory.auto_recall);
        assert!(config.memory.auto_capture);
    }

    #[test]
    fn test_sidebar_config_partial_deserialization_uses_defaults() {
        let yaml = r#"
sidebar:
  show_mcp: false
"#;

        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.sidebar.show_context);
        assert!(!config.sidebar.show_mcp);
        assert!(config.sidebar.show_todos);
        assert!(config.sidebar.show_files);
    }

    #[test]
    fn test_skills_settings_defaults() {
        let settings = SkillsSettings::default();
        assert!(!settings.enabled);
        assert_eq!(settings.paths.len(), 2);
        assert!(settings.active.is_empty());
    }

    #[test]
    fn test_gateway_settings_defaults() {
        let settings = GatewaySettings::default();
        assert!(!settings.enabled);
        assert_eq!(settings.host, "127.0.0.1");
        assert_eq!(settings.port, 18790);
        assert_eq!(settings.max_sessions, 10);
        assert_eq!(settings.model, "claude-sonnet-4-20250514");
        assert_eq!(settings.provider, "anthropic");
        assert_eq!(settings.default_agent, "balanced");
        assert!(settings.auth_token.is_none());
        assert_eq!(settings.idle_timeout_secs, Some(1800));
        assert!(settings.working_directory.is_none());
    }

    #[test]
    fn test_channel_settings_defaults() {
        let settings = ChannelSettings::default();
        assert!(settings.telegram.is_none());
        assert!(settings.slack.is_none());
    }

    #[test]
    fn test_full_config_with_skills() {
        let yaml = r#"
skills:
  enabled: true
  paths:
    - "~/.uira/skills"
    - "./project-skills"
  active:
    - coding-agent
    - debugger
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.skills.enabled);
        assert_eq!(config.skills.paths.len(), 2);
        assert_eq!(config.skills.active, vec!["coding-agent", "debugger"]);
    }

    #[test]
    fn test_full_config_with_gateway() {
        let yaml = r#"
gateway:
  enabled: true
  host: "0.0.0.0"
  port: 9000
  max_sessions: 20
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(config.gateway.enabled);
        assert_eq!(config.gateway.host, "0.0.0.0");
        assert_eq!(config.gateway.port, 9000);
        assert_eq!(config.gateway.max_sessions, 20);
    }

    #[test]
    fn test_full_config_with_channels() {
        let yaml = r#"
channels:
  telegram:
    bot_token: "123456:ABC-DEF"
    allowed_users:
      - "user123"
  slack:
    bot_token: "xoxb-test"
    app_token: "xapp-test"
    allowed_channels:
      - "C12345"
"#;
        let config: UiraConfig = serde_yaml_ng::from_str(yaml).unwrap();
        let tg = config.channels.telegram.unwrap();
        assert_eq!(tg.bot_token, "123456:ABC-DEF");
        assert_eq!(tg.allowed_users, vec!["user123"]);
        let slack = config.channels.slack.unwrap();
        assert_eq!(slack.bot_token, "xoxb-test");
        assert_eq!(slack.app_token, "xapp-test");
        assert_eq!(slack.allowed_channels, vec!["C12345"]);
    }
}