1use crate::config::{home_config_path, Config, ConfigError};
2use crate::openrouter::{ApiError, Client};
3use crate::ui;
4
5pub fn run_first_startup() -> Config {
6 ui::welcome_message();
7
8 let mut api_key = ui::api_key_prompt();
9
10 let config = loop {
11 ui::fetching_models_message();
12
13 let client = Client::new(api_key.clone());
14 match client.fetch_models() {
15 Ok(models) => {
16 let model_ids: Vec<String> = models.iter().map(|m| m.id.clone()).collect();
17 ui::models_loaded(model_ids.len());
18
19 let selection = ui::model_select_prompt(&model_ids);
20 let model_id = if selection == "[ Ketik Manual ID Model... ]" {
21 ui::manual_model_prompt()
22 } else {
23 selection
24 };
25
26 break Config { api_key, model_id };
27 }
28 Err(ApiError::Unauthorized) => {
29 ui::error_message("Invalid API Key. Make sure you entered the correct key.");
30 api_key = ui::api_key_prompt();
31 }
32 Err(ApiError::Forbidden) => {
33 ui::error_message(
34 "API Key doesn't have access. Check permissions on OpenRouter.",
35 );
36 }
37 Err(ApiError::RateLimited) => {
38 ui::rate_limited_message();
39 }
40 Err(ApiError::EmptyResponse) => {
41 ui::error_message("No models available from OpenRouter. Please try again.");
42 }
43 Err(e) => {
44 ui::error_message(&format!("Failed to fetch models: {}. Please try again.", e));
45 }
46 }
47 };
48
49 let path = home_config_path();
50 if let Err(e) = config.save(&path) {
51 eprintln!("Warning: Failed to save config: {}. Continuing anyway...", e);
52 }
53
54 ui::save_confirmation();
55
56 config
57}
58
59pub fn reconfigure_model_silent(api_key: &str) -> Result<String, ConfigError> {
60 let client = Client::new(api_key.to_string());
61
62 let models = loop {
63 match client.fetch_models() {
64 Ok(m) => break m,
65 Err(ApiError::Unauthorized) => {
66 return Err(ConfigError::Unauthorized);
67 }
68 Err(ApiError::RateLimited) => {
69 std::thread::sleep(std::time::Duration::from_secs(2));
70 continue;
71 }
72 Err(e) => {
73 return Err(ConfigError::ApiError(e.to_string()));
74 }
75 }
76 };
77
78 let model_ids: Vec<String> = models.iter().map(|m| m.id.clone()).collect();
79 let selection = ui::model_select_prompt(&model_ids);
80 let model_id = if selection == "[ Ketik Manual ID Model... ]" {
81 ui::manual_model_prompt()
82 } else {
83 selection
84 };
85
86 Ok(model_id)
87}