codive-core 0.1.0

Core types, traits, and utilities for Codive
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
//! Configuration types for the Agent system
//!
//! This module defines configuration structures that control agent behavior.
//! All configs have sensible defaults and can be loaded from files or environment.
//!
//! # Design Principles
//!
//! 1. **Sensible Defaults** - Should work out of the box
//! 2. **Optional Fields** - Only require what's essential
//! 3. **Serializable** - Can be loaded from TOML/JSON/YAML
//! 4. **Type Safe** - Invalid configs won't compile
//!
//! # Loading Configuration
//!
//! Configuration is loaded from multiple sources with the following priority:
//! 1. Environment variables (highest priority)
//! 2. Config file (if specified or found)
//! 3. Default values (lowest priority)
//!
//! ## Config File Discovery
//!
//! If no config file is specified, the following locations are searched:
//! 1. `./agent.toml` (current directory)
//! 2. `~/.config/agent/config.toml` (user config directory)
//!
//! ## Environment Variables
//!
//! The following environment variables are supported:
//! - `ANTHROPIC_API_KEY` - API key for Anthropic
//! - `OPENAI_API_KEY` - API key for OpenAI
//! - `AGENT_MODEL` - Override the default model
//! - `AGENT_PROVIDER` - Override the default provider
//!
//! # Example
//!
//! ```rust,ignore
//! use codive_core::config::AppConfig;
//!
//! // Load from default locations with env var overrides
//! let config = AppConfig::load(None)?;
//!
//! // Load from specific file
//! let config = AppConfig::load(Some("./my-config.toml"))?;
//! ```

use codive_prompts::{EnvironmentContext, PromptComposer, PromptStore};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

// ============================================================================
// Provider Registry
// ============================================================================

/// Information about a supported LLM provider
#[derive(Debug, Clone, Copy)]
pub struct ProviderInfo {
    /// Provider name (e.g., "anthropic", "openai", "gemini")
    pub name: &'static str,
    /// Environment variable for API key
    pub env_var: &'static str,
    /// Default model for this provider
    pub default_model: &'static str,
}

/// Registry of supported providers in priority order.
/// When auto-detecting, the first provider with an available API key is used.
/// Models are selected for best coding performance (as of Jan 2026).
pub const PROVIDERS: &[ProviderInfo] = &[
    ProviderInfo {
        name: "anthropic",
        env_var: "ANTHROPIC_API_KEY",
        default_model: "claude-opus-4-5-20251101", // Opus 4.5 - best coding model
    },
    ProviderInfo {
        name: "openai",
        env_var: "OPENAI_API_KEY",
        default_model: "gpt-5.2-2025-12-11", // GPT-5.2 - latest and best OpenAI model
    },
    ProviderInfo {
        name: "gemini",
        env_var: "GEMINI_API_KEY",
        default_model: "gemini-2.5-pro", // Gemini 2.5 Pro - stable with adaptive thinking
    },
];

/// Get provider info by name
pub fn get_provider(name: &str) -> Option<&'static ProviderInfo> {
    PROVIDERS.iter().find(|p| p.name == name)
}

/// Detect the best available provider based on API keys.
/// Returns the first provider that has an API key set in the environment.
pub fn detect_provider() -> Option<&'static ProviderInfo> {
    PROVIDERS
        .iter()
        .find(|p| std::env::var(p.env_var).is_ok())
}

// ============================================================================
// ModelConfig
// ============================================================================

/// Configuration for the LLM model
///
/// Controls which provider and model to use, along with generation parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    /// Provider name (e.g., "anthropic", "openai")
    #[serde(default = "default_provider")]
    pub provider: String,

    /// Model identifier (e.g., "claude-3-opus-20240229", "gpt-4")
    #[serde(default = "default_model")]
    pub model: String,

    /// Maximum tokens to generate per response
    #[serde(default = "default_max_tokens")]
    pub max_tokens: u32,

    /// Temperature for sampling (0.0 = deterministic, 1.0 = creative)
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// Optional API key (if not set, reads from environment)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,

    /// Optional API base URL (for custom endpoints)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_base: Option<String>,
}

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

fn default_model() -> String {
    "claude-opus-4-5-20251101".to_string()
}

fn default_max_tokens() -> u32 {
    4096
}

fn default_temperature() -> f32 {
    0.0
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            provider: default_provider(),
            model: default_model(),
            max_tokens: default_max_tokens(),
            temperature: default_temperature(),
            api_key: None,
            api_base: None,
        }
    }
}

impl ModelConfig {
    /// Create a new model config with the given provider and model
    pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            provider: provider.into(),
            model: model.into(),
            ..Default::default()
        }
    }

    /// Set the maximum tokens
    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = max_tokens;
        self
    }

    /// Set the temperature
    pub fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = temperature;
        self
    }

    /// Set the API key
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Set the API base URL
    pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
        self.api_base = Some(api_base.into());
        self
    }
}

// ============================================================================
// VerificationConfig
// ============================================================================

/// Configuration for AI-driven code verification
///
/// When enabled, the system prompt instructs the AI to automatically verify
/// code changes by running appropriate build/test commands for the project type.
/// The AI detects the project type and figures out the right commands to run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationConfig {
    /// Whether AI-driven verification is enabled in the system prompt
    /// When true, the AI is instructed to verify code changes before reporting success
    #[serde(default = "default_verification_enabled")]
    pub enabled: bool,
}

fn default_verification_enabled() -> bool {
    true // Enabled by default for better code quality
}

impl Default for VerificationConfig {
    fn default() -> Self {
        Self {
            enabled: default_verification_enabled(),
        }
    }
}

impl VerificationConfig {
    /// Create a new verification config
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable verification
    pub fn enabled(mut self) -> Self {
        self.enabled = true;
        self
    }

    /// Disable verification
    pub fn disabled(mut self) -> Self {
        self.enabled = false;
        self
    }
}

// ============================================================================
// AgentConfig
// ============================================================================

/// Configuration for an agent instance
///
/// Defines the agent's identity, behavior, and capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent name (used in logging and identification)
    #[serde(default = "default_agent_name")]
    pub name: String,

    /// Human-readable description of the agent
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// System prompt - instructions for the model
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,

    /// Model configuration
    #[serde(default)]
    pub model: ModelConfig,

    /// List of enabled tool names
    #[serde(default)]
    pub tools: Vec<String>,

    /// Maximum steps (tool calls) per conversation turn
    #[serde(default = "default_max_steps")]
    pub max_steps: u32,

    /// Maximum conversation history length (messages to keep)
    #[serde(default = "default_max_history")]
    pub max_history: usize,

    /// Whether to allow parallel tool calls
    #[serde(default = "default_parallel_tools")]
    pub parallel_tool_calls: bool,

    /// Verification configuration for auto-build/test
    #[serde(default)]
    pub verification: VerificationConfig,
}

fn default_agent_name() -> String {
    "agent".to_string()
}

fn default_max_steps() -> u32 {
    50
}

fn default_max_history() -> usize {
    100
}

fn default_parallel_tools() -> bool {
    true
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            name: default_agent_name(),
            description: None,
            system_prompt: None,
            model: ModelConfig::default(),
            tools: Vec::new(),
            max_steps: default_max_steps(),
            max_history: default_max_history(),
            parallel_tool_calls: default_parallel_tools(),
            verification: VerificationConfig::default(),
        }
    }
}

impl AgentConfig {
    /// Create a new agent config with the given name
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

    /// Set the agent name
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set the description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the system prompt
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// Set the model configuration
    pub fn with_model(mut self, model: ModelConfig) -> Self {
        self.model = model;
        self
    }

    /// Set enabled tools
    pub fn with_tools(mut self, tools: Vec<String>) -> Self {
        self.tools = tools;
        self
    }

    /// Add a single tool to enabled tools
    pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
        self.tools.push(tool.into());
        self
    }

    /// Set maximum steps
    pub fn with_max_steps(mut self, max_steps: u32) -> Self {
        self.max_steps = max_steps;
        self
    }

    /// Set maximum history length
    pub fn with_max_history(mut self, max_history: usize) -> Self {
        self.max_history = max_history;
        self
    }

    /// Set whether to allow parallel tool calls
    pub fn with_parallel_tool_calls(mut self, parallel: bool) -> Self {
        self.parallel_tool_calls = parallel;
        self
    }

    /// Set verification configuration
    pub fn with_verification(mut self, verification: VerificationConfig) -> Self {
        self.verification = verification;
        self
    }

    /// Build the system prompt using the PromptStore
    ///
    /// This composes the system prompt from multiple layers:
    /// 1. Base prompt (agent identity)
    /// 2. Provider-specific instructions (based on model)
    /// 3. Environment context (working dir, git status, date)
    /// 4. Verification instructions (if enabled)
    ///
    /// If a custom system_prompt is set, it takes precedence.
    pub fn build_system_prompt(&self, store: &PromptStore) -> String {
        // Custom prompt override takes precedence
        if let Some(ref custom) = self.system_prompt {
            return custom.clone();
        }

        PromptComposer::new(store)
            .with_base()
            .with_provider_auto(&self.model.model)
            .with_current_environment()
            .with_verification_if(self.verification.enabled)
            .compose()
    }

    /// Build system prompt with custom environment context
    pub fn build_system_prompt_with_env(
        &self,
        store: &PromptStore,
        env: EnvironmentContext,
    ) -> String {
        if let Some(ref custom) = self.system_prompt {
            return custom.clone();
        }

        PromptComposer::new(store)
            .with_base()
            .with_provider_auto(&self.model.model)
            .with_environment(env)
            .with_verification_if(self.verification.enabled)
            .compose()
    }
}


// ============================================================================
// PromptConfig
// ============================================================================

/// Configuration for prompt management
///
/// Controls where prompt overrides are loaded from.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptConfig {
    /// Optional directory for prompt overrides
    /// If not set, uses default location (~/.config/agent/prompts)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overrides_dir: Option<PathBuf>,
}

impl Default for PromptConfig {
    fn default() -> Self {
        Self { overrides_dir: None }
    }
}

impl PromptConfig {
    /// Create a new prompt config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the overrides directory
    pub fn with_overrides_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.overrides_dir = Some(dir.into());
        self
    }

    /// Build a PromptStore from this config
    pub fn build_store(&self) -> PromptStore {
        // Try to load overrides from configured or default directory
        let overrides_dir = self
            .overrides_dir
            .clone()
            .or_else(codive_prompts::default_overrides_dir);

        if let Some(dir) = overrides_dir {
            if dir.exists() {
                match PromptStore::new().with_overrides_dir(&dir) {
                    Ok(store) => return store,
                    Err(e) => {
                        tracing::warn!("Failed to load prompt overrides from {:?}: {}", dir, e);
                    }
                }
            }
        }

        PromptStore::new()
    }
}

// ============================================================================
// ServerConfig
// ============================================================================

/// Configuration for the server component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// Host to bind to
    #[serde(default = "default_host")]
    pub host: String,

    /// Port to listen on
    #[serde(default = "default_port")]
    pub port: u16,

    /// Whether to enable CORS
    #[serde(default = "default_cors")]
    pub cors_enabled: bool,
}

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

fn default_port() -> u16 {
    3000
}

fn default_cors() -> bool {
    true
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            cors_enabled: default_cors(),
        }
    }
}

impl ServerConfig {
    /// Get the full address string
    pub fn address(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

// ============================================================================
// McpConfig
// ============================================================================

/// Configuration for MCP (Model Context Protocol) servers
///
/// MCP allows the agent to connect to external tool providers that implement
/// the MCP protocol. Servers can be local (via stdio) or remote (via HTTP).
///
/// # Example Configuration
///
/// ```toml
/// [[mcp.servers]]
/// name = "filesystem"
/// transport = "stdio"
/// command = "npx"
/// args = ["-y", "@anthropic/mcp-server-filesystem", "/home/user"]
///
/// [[mcp.servers]]
/// name = "api"
/// transport = "http"
/// url = "https://mcp.example.com/api"
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpConfig {
    /// List of MCP server configurations
    #[serde(default)]
    pub servers: Vec<McpServerConfig>,
}

impl McpConfig {
    /// Create a new empty MCP config
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if any MCP servers are configured
    pub fn has_servers(&self) -> bool {
        !self.servers.is_empty()
    }
}

/// Configuration for a single MCP server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Unique name for this server (used as tool prefix)
    pub name: String,

    /// Transport type (stdio or http)
    #[serde(default)]
    pub transport: McpTransport,

    // Stdio transport options
    /// Command to execute (for stdio transport)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,

    /// Arguments to pass to the command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,

    /// Environment variables to set (supports ${VAR} expansion)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<HashMap<String, String>>,

    // HTTP transport options
    /// URL for HTTP transport
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Custom headers for HTTP transport (supports ${VAR} expansion)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}

/// Transport type for MCP communication
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum McpTransport {
    /// Stdio transport (spawn child process)
    #[default]
    Stdio,
    /// HTTP transport (remote server)
    Http,
}

// ============================================================================
// ConfigError
// ============================================================================

/// Errors that can occur when loading configuration
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// Config file not found at specified path
    #[error("Config file not found: {path}")]
    FileNotFound { path: PathBuf },

    /// Failed to read config file
    #[error("Failed to read config file: {message}")]
    ReadError { message: String },

    /// Failed to parse config file
    #[error("Failed to parse config file: {message}")]
    ParseError { message: String },

    /// Invalid configuration value
    #[error("Invalid configuration: {message}")]
    InvalidConfig { message: String },
}

impl ConfigError {
    /// Create a read error
    pub fn read_error(message: impl Into<String>) -> Self {
        Self::ReadError {
            message: message.into(),
        }
    }

    /// Create a parse error
    pub fn parse_error(message: impl Into<String>) -> Self {
        Self::ParseError {
            message: message.into(),
        }
    }
}

// ============================================================================
// TuiConfig
// ============================================================================

/// Configuration for the TUI (Terminal User Interface)
///
/// Controls visual appearance and behavior preferences.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TuiConfig {
    /// Theme name (github_dark, dracula, nord, catppuccin_mocha, high_contrast, light)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Whether to auto-show file preview when files are changed
    #[serde(default = "default_preview_auto_show")]
    pub preview_auto_show: bool,

    /// Whether the sidebar is visible by default
    #[serde(default = "default_sidebar_visible")]
    pub sidebar_visible: bool,
}

fn default_theme() -> String {
    "github_dark".to_string()
}

fn default_preview_auto_show() -> bool {
    true
}

fn default_sidebar_visible() -> bool {
    true
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            preview_auto_show: default_preview_auto_show(),
            sidebar_visible: default_sidebar_visible(),
        }
    }
}

impl TuiConfig {
    /// Create a new TUI config with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the theme
    pub fn with_theme(mut self, theme: impl Into<String>) -> Self {
        self.theme = theme.into();
        self
    }

    /// Set preview auto-show
    pub fn with_preview_auto_show(mut self, auto_show: bool) -> Self {
        self.preview_auto_show = auto_show;
        self
    }
}

// ============================================================================
// AppConfig
// ============================================================================

/// Top-level application configuration
///
/// This combines all configuration sections into a single struct
/// that can be loaded from a configuration file.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AppConfig {
    /// Agent configuration
    #[serde(default)]
    pub agent: AgentConfig,

    /// Server configuration
    #[serde(default)]
    pub server: ServerConfig,

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

    /// TUI configuration
    #[serde(default)]
    pub tui: TuiConfig,

    /// Prompt configuration
    #[serde(default)]
    pub prompts: PromptConfig,
}

impl AppConfig {
    /// Create a new app config with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Load configuration from file with environment variable overrides
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path to config file. If None, searches default locations.
    ///
    /// # Config File Discovery
    ///
    /// When no path is specified, searches in order:
    /// 1. `./agent.toml`
    /// 2. `~/.config/agent/config.toml`
    ///
    /// If no config file is found, returns defaults with env var overrides.
    pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
        let mut config = if let Some(p) = path {
            // Load from specified path
            Self::load_from_file(p)?
        } else if let Some(p) = Self::discover_config_file() {
            // Load from discovered path
            Self::load_from_file(&p)?
        } else {
            // Use defaults
            Self::default()
        };

        // Apply environment variable overrides
        config.apply_env_overrides();

        Ok(config)
    }

    /// Load configuration from a specific file
    pub fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
        if !path.exists() {
            return Err(ConfigError::FileNotFound {
                path: path.to_path_buf(),
            });
        }

        let content =
            std::fs::read_to_string(path).map_err(|e| ConfigError::read_error(e.to_string()))?;

        Self::parse_toml(&content)
    }

    /// Parse configuration from TOML string
    pub fn parse_toml(content: &str) -> Result<Self, ConfigError> {
        toml::from_str(content).map_err(|e| ConfigError::parse_error(e.to_string()))
    }

    /// Discover config file in standard locations
    ///
    /// Searches in order:
    /// 1. `./agent.toml` (current directory)
    /// 2. `~/.config/agent/config.toml` (user config)
    pub fn discover_config_file() -> Option<PathBuf> {
        // Check current directory first
        let local_config = PathBuf::from("agent.toml");
        if local_config.exists() {
            return Some(local_config);
        }

        // Check user config directory
        if let Some(config_dir) = dirs::config_dir() {
            let user_config = config_dir.join("agent").join("config.toml");
            if user_config.exists() {
                return Some(user_config);
            }
        }

        None
    }

    /// Apply environment variable overrides to the configuration
    ///
    /// Supported environment variables:
    /// - `ANTHROPIC_API_KEY` - API key for Anthropic provider
    /// - `OPENAI_API_KEY` - API key for OpenAI provider
    /// - `GEMINI_API_KEY` - API key for Gemini provider
    /// - `AGENT_MODEL` - Override the model
    /// - `AGENT_PROVIDER` - Override the provider
    /// - `AGENT_MAX_TOKENS` - Override max tokens
    /// - `AGENT_HOST` - Override server host
    /// - `AGENT_PORT` - Override server port
    ///
    /// If no provider is explicitly set (via config or AGENT_PROVIDER), the system
    /// auto-detects the provider based on available API keys in priority order:
    /// Anthropic > OpenAI > Gemini
    pub fn apply_env_overrides(&mut self) {
        // Track if provider/model were explicitly set
        let explicit_provider = std::env::var("AGENT_PROVIDER").ok();
        let explicit_model = std::env::var("AGENT_MODEL").ok();

        // Check if provider was explicitly configured in config file
        // (i.e., differs from default)
        let provider_from_config = self.agent.model.provider != "anthropic";

        // Apply explicit overrides first
        if let Some(provider) = explicit_provider {
            self.agent.model.provider = provider;
        }
        if let Some(model) = explicit_model {
            self.agent.model.model = model;
        }

        // Auto-detect provider if not explicitly configured
        // Only auto-detect if:
        // 1. No AGENT_PROVIDER env var
        // 2. Provider in config is still default ("anthropic")
        // 3. Model in config is still default
        if !provider_from_config
            && std::env::var("AGENT_PROVIDER").is_err()
            && std::env::var("AGENT_MODEL").is_err()
        {
            if let Some(detected) = detect_provider() {
                self.agent.model.provider = detected.name.to_string();
                self.agent.model.model = detected.default_model.to_string();
            }
        }

        // Other overrides
        if let Ok(max_tokens) = std::env::var("AGENT_MAX_TOKENS") {
            if let Ok(tokens) = max_tokens.parse() {
                self.agent.model.max_tokens = tokens;
            }
        }

        // Server overrides
        if let Ok(host) = std::env::var("AGENT_HOST") {
            self.server.host = host;
        }
        if let Ok(port) = std::env::var("AGENT_PORT") {
            if let Ok(p) = port.parse() {
                self.server.port = p;
            }
        }
    }

    /// Get the API key for the current provider from config or environment
    ///
    /// Checks in order:
    /// 1. Config file api_key
    /// 2. Provider-specific env var (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY)
    pub fn api_key(&self) -> Option<String> {
        // First check config
        if let Some(ref key) = self.agent.model.api_key {
            return Some(key.clone());
        }

        // Then check environment based on provider using registry
        get_provider(&self.agent.model.provider)
            .and_then(|p| std::env::var(p.env_var).ok())
    }

    /// Set the agent configuration
    pub fn with_agent(mut self, agent: AgentConfig) -> Self {
        self.agent = agent;
        self
    }

    /// Set the server configuration
    pub fn with_server(mut self, server: ServerConfig) -> Self {
        self.server = server;
        self
    }

    /// Set the MCP configuration
    pub fn with_mcp(mut self, mcp: McpConfig) -> Self {
        self.mcp = mcp;
        self
    }

    /// Save configuration to a TOML file
    pub fn save_to_file(&self, path: &Path) -> Result<(), ConfigError> {
        let content =
            toml::to_string_pretty(self).map_err(|e| ConfigError::parse_error(e.to_string()))?;

        std::fs::write(path, content).map_err(|e| ConfigError::read_error(e.to_string()))
    }

    /// Get the default config file path in user config directory
    pub fn default_config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|p| p.join("agent").join("config.toml"))
    }
}

// ============================================================================
// RUST CONCEPTS EXPLAINED (for learning)
// ============================================================================
//
// 1. `#[derive(Default)]`
//    - Auto-implements the Default trait
//    - Requires all fields to implement Default
//    - Use `impl Default` manually when you need custom defaults
//
// 2. `#[serde(default)]`
//    - Uses Default::default() when field is missing in input
//    - `#[serde(default = "function")]` - use custom default function
//    - Allows config files to omit optional fields
//
// 3. `#[serde(skip_serializing_if = "Option::is_none")]`
//    - Don't include None values in serialized output
//    - Keeps config files clean
//
// 4. Builder pattern with `with_*` methods
//    - `mut self` - takes ownership, modifies, returns
//    - Allows chaining: `Config::new().with_x(1).with_y(2)`
//    - Ergonomic API for complex construction
//
// 5. `impl Into<String>` parameters
//    - Accepts &str, String, Cow<str>, etc.
//    - More flexible than just `String`
//    - `.into()` converts to the target type
//
// 6. Default functions
//    - Serde requires a function that returns T
//    - Can't use closures, must be named functions
//    - `fn default_x() -> Type { value }`
//
// 7. `Option<T>` for optional fields
//    - `Some(value)` or `None`
//    - `.as_deref()` - converts Option<String> to Option<&str>
//    - `.unwrap_or()` - provide fallback value
//
// **📚 Read:**
// - [Default trait](https://doc.rust-lang.org/std/default/trait.Default.html)
// - [Serde field attributes](https://serde.rs/field-attrs.html)

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_model_config_defaults() {
        let config = ModelConfig::default();
        assert_eq!(config.provider, "anthropic");
        assert_eq!(config.model, "claude-opus-4-5-20251101");
        assert_eq!(config.max_tokens, 4096);
        assert_eq!(config.temperature, 0.0);
        assert!(config.api_key.is_none());
    }

    #[test]
    fn test_model_config_builder() {
        let config = ModelConfig::new("openai", "gpt-4")
            .with_max_tokens(2000)
            .with_temperature(0.7)
            .with_api_key("sk-test");

        assert_eq!(config.provider, "openai");
        assert_eq!(config.model, "gpt-4");
        assert_eq!(config.max_tokens, 2000);
        assert_eq!(config.temperature, 0.7);
        assert_eq!(config.api_key, Some("sk-test".to_string()));
    }

    #[test]
    fn test_agent_config_defaults() {
        let config = AgentConfig::default();
        assert_eq!(config.name, "agent");
        assert!(config.description.is_none());
        assert!(config.system_prompt.is_none());
        assert!(config.tools.is_empty());
        assert_eq!(config.max_steps, 50);
        assert!(config.parallel_tool_calls);
    }

    #[test]
    fn test_agent_config_builder() {
        let config = AgentConfig::new("my-agent")
            .with_description("A test agent")
            .with_system_prompt("You are helpful")
            .with_tool("bash")
            .with_tool("read_file")
            .with_max_steps(10);

        assert_eq!(config.name, "my-agent");
        assert_eq!(config.description, Some("A test agent".to_string()));
        assert_eq!(config.system_prompt, Some("You are helpful".to_string()));
        assert_eq!(config.tools, vec!["bash", "read_file"]);
        assert_eq!(config.max_steps, 10);
    }

    #[test]
    fn test_build_system_prompt() {
        let store = PromptStore::new();

        // Custom prompt should be returned as-is
        let config_with = AgentConfig::default().with_system_prompt("Custom prompt");
        assert_eq!(config_with.build_system_prompt(&store), "Custom prompt");

        // Default config has verification enabled, so should include verification instructions
        let config_default = AgentConfig::default();
        let prompt = config_default.build_system_prompt(&store);
        // Should contain base prompt content
        assert!(prompt.contains("AI"));
        assert!(prompt.contains("Verification"));

        // With verification disabled, should not contain verification
        let config_no_verify = AgentConfig::default()
            .with_verification(VerificationConfig::new().disabled());
        let prompt = config_no_verify.build_system_prompt(&store);
        assert!(!prompt.contains("Verification"));
    }

    #[test]
    fn test_server_config_defaults() {
        let config = ServerConfig::default();
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 3000);
        assert!(config.cors_enabled);
    }

    #[test]
    fn test_server_config_address() {
        let config = ServerConfig::default();
        assert_eq!(config.address(), "127.0.0.1:3000");
    }

    #[test]
    fn test_app_config_defaults() {
        let config = AppConfig::default();
        assert_eq!(config.agent.name, "agent");
        assert_eq!(config.server.port, 3000);
    }

    #[test]
    fn test_model_config_serialization() {
        let config = ModelConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"provider\":\"anthropic\""));
        assert!(json.contains("\"model\":\"claude-opus-4-5-20251101\""));

        // api_key should be skipped when None
        assert!(!json.contains("api_key"));
    }

    #[test]
    fn test_model_config_deserialization_with_defaults() {
        // Minimal JSON - should fill in defaults
        let json = r#"{"provider": "openai"}"#;
        let config: ModelConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.provider, "openai");
        // These should be defaults
        assert_eq!(config.model, "claude-opus-4-5-20251101");
        assert_eq!(config.max_tokens, 4096);
    }

    #[test]
    fn test_agent_config_serialization_roundtrip() {
        let original = AgentConfig::new("test")
            .with_description("Test agent")
            .with_tool("bash");

        let json = serde_json::to_string(&original).unwrap();
        let restored: AgentConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(original.name, restored.name);
        assert_eq!(original.description, restored.description);
        assert_eq!(original.tools, restored.tools);
    }

    #[test]
    fn test_empty_json_uses_all_defaults() {
        let json = "{}";
        let config: AppConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.agent.name, "agent");
        assert_eq!(config.agent.model.provider, "anthropic");
        assert_eq!(config.server.port, 3000);
    }

    // =========================================================================
    // TOML Parsing Tests
    // =========================================================================

    #[test]
    fn test_parse_toml_empty() {
        let toml = "";
        let config = AppConfig::parse_toml(toml).unwrap();
        assert_eq!(config.agent.name, "agent");
        assert_eq!(config.server.port, 3000);
    }

    #[test]
    fn test_parse_toml_full() {
        let toml = r#"
[agent]
name = "my-agent"
description = "A custom agent"
max_steps = 25

[agent.model]
provider = "openai"
model = "gpt-4"
max_tokens = 2000
temperature = 0.5

[server]
host = "0.0.0.0"
port = 8080
cors_enabled = false
"#;
        let config = AppConfig::parse_toml(toml).unwrap();

        assert_eq!(config.agent.name, "my-agent");
        assert_eq!(config.agent.description, Some("A custom agent".to_string()));
        assert_eq!(config.agent.max_steps, 25);
        assert_eq!(config.agent.model.provider, "openai");
        assert_eq!(config.agent.model.model, "gpt-4");
        assert_eq!(config.agent.model.max_tokens, 2000);
        assert_eq!(config.agent.model.temperature, 0.5);
        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port, 8080);
        assert!(!config.server.cors_enabled);
    }

    #[test]
    fn test_parse_toml_partial() {
        let toml = r#"
[agent]
name = "partial-agent"

[server]
port = 4000
"#;
        let config = AppConfig::parse_toml(toml).unwrap();

        // Specified values
        assert_eq!(config.agent.name, "partial-agent");
        assert_eq!(config.server.port, 4000);

        // Defaults
        assert_eq!(config.agent.model.provider, "anthropic");
        assert_eq!(config.server.host, "127.0.0.1");
    }

    #[test]
    fn test_parse_toml_with_tools() {
        let toml = r#"
[agent]
name = "tool-agent"
tools = ["bash", "read_file", "write_file"]
"#;
        let config = AppConfig::parse_toml(toml).unwrap();

        assert_eq!(config.agent.tools, vec!["bash", "read_file", "write_file"]);
    }

    #[test]
    fn test_parse_toml_invalid() {
        let toml = "this is not valid toml [[[";
        let result = AppConfig::parse_toml(toml);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConfigError::ParseError { .. }
        ));
    }

    #[test]
    fn test_toml_serialization_roundtrip() {
        let original =
            AppConfig::default().with_agent(AgentConfig::new("test-agent").with_tool("bash"));

        let toml_str = toml::to_string_pretty(&original).unwrap();
        let restored = AppConfig::parse_toml(&toml_str).unwrap();

        assert_eq!(original.agent.name, restored.agent.name);
        assert_eq!(original.agent.tools, restored.agent.tools);
    }

    // =========================================================================
    // Config Loading Tests
    // =========================================================================

    #[test]
    fn test_load_nonexistent_file() {
        let result = AppConfig::load_from_file(Path::new("/nonexistent/path/config.toml"));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConfigError::FileNotFound { .. }
        ));
    }

    #[test]
    fn test_load_with_no_config_uses_defaults() {
        // When no config file exists and none specified, should use defaults
        let config = AppConfig::load(None).unwrap();
        assert_eq!(config.agent.name, "agent");
    }

    #[test]
    fn test_config_error_display() {
        let err = ConfigError::FileNotFound {
            path: PathBuf::from("/test/path"),
        };
        assert!(err.to_string().contains("/test/path"));

        let err = ConfigError::parse_error("invalid syntax");
        assert!(err.to_string().contains("invalid syntax"));
    }

    #[test]
    fn test_save_and_load_config() {
        use std::fs;

        let temp_dir = std::env::temp_dir();
        let config_path = temp_dir.join("agent_test_config.toml");

        // Create and save config
        let original =
            AppConfig::default().with_agent(AgentConfig::new("saved-agent").with_max_steps(30));

        original.save_to_file(&config_path).unwrap();

        // Load it back
        let loaded = AppConfig::load_from_file(&config_path).unwrap();

        assert_eq!(loaded.agent.name, "saved-agent");
        assert_eq!(loaded.agent.max_steps, 30);

        // Cleanup
        fs::remove_file(&config_path).ok();
    }

    #[test]
    fn test_default_config_path() {
        let path = AppConfig::default_config_path();
        // Should return Some on most systems
        if let Some(p) = path {
            assert!(p.to_string_lossy().contains("agent"));
            assert!(p.to_string_lossy().contains("config.toml"));
        }
    }

    // =========================================================================
    // Environment Variable Tests
    // =========================================================================

    #[test]
    fn test_api_key_from_config() {
        let config = AppConfig::default().with_agent(
            AgentConfig::default().with_model(ModelConfig::default().with_api_key("config-key")),
        );

        assert_eq!(config.api_key(), Some("config-key".to_string()));
    }

    #[test]
    fn test_env_override_model() {
        // Save current env
        let old_model = std::env::var("AGENT_MODEL").ok();

        // Set env var
        std::env::set_var("AGENT_MODEL", "test-model-from-env");

        let mut config = AppConfig::default();
        config.apply_env_overrides();

        assert_eq!(config.agent.model.model, "test-model-from-env");

        // Restore env
        if let Some(old) = old_model {
            std::env::set_var("AGENT_MODEL", old);
        } else {
            std::env::remove_var("AGENT_MODEL");
        }
    }

    #[test]
    fn test_env_override_port() {
        let old_port = std::env::var("AGENT_PORT").ok();

        std::env::set_var("AGENT_PORT", "9999");

        let mut config = AppConfig::default();
        config.apply_env_overrides();

        assert_eq!(config.server.port, 9999);

        if let Some(old) = old_port {
            std::env::set_var("AGENT_PORT", old);
        } else {
            std::env::remove_var("AGENT_PORT");
        }
    }
}