Skip to main content

git_comma/
setup.rs

1use crate::config::{home_config_path, Config, ConfigError};
2use crate::openrouter::{ApiError, Client};
3use crate::ui;
4use colored::Colorize;
5
6fn print_splash_banner() {
7    let banner = r#"
8 ▄   ▄▄▄▄
9 ▀██████▀                           ▄███████▄
10   ██           ▄        ▄         ██   ▀█▄ ▀█
11   ██     ▄███▄ ███▄███▄ ███▄███▄ ██  ▄█▀██  ██
12   ██     ██ ██ ██ ██ ██ ██ ██ ██ ██  ██ ██ ▄█
13   ▀█████▄▀███▀▄██ ██ ▀█▄██ ██ ▀█ ▀█▄  ▀▀▀▀▀▀
14                                    ▀██████▀▀
15"#;
16    println!("{}", banner.cyan().bold());
17}
18
19fn prompt_api_key(is_first_run: bool, existing_key: Option<&str>) -> String {
20    loop {
21        let mut prompt_text = "Enter OpenRouter API Key (sk-or-v1-...):".to_string();
22        if !is_first_run {
23            prompt_text.push_str(" (Leave blank to keep existing)");
24        }
25
26        let password = inquire::Password::new(&prompt_text)
27            .with_display_mode(inquire::PasswordDisplayMode::Masked)
28            .with_help_message("API key at https://openrouter.ai/keys")
29            .prompt()
30            .expect("User cancelled");
31
32        if password.is_empty() {
33            if is_first_run {
34                ui::error_message("API key is required on first run. Please enter your key.");
35                continue;
36            } else if let Some(key) = existing_key {
37                return key.to_string();
38            } else {
39                ui::error_message("No existing API key found. Please enter your key.");
40                continue;
41            }
42        }
43        break password;
44    }
45}
46
47pub fn run_setup_flow(is_first_run: bool) -> Result<Config, ConfigError> {
48    print_splash_banner();
49
50    let existing_key = if !is_first_run {
51        home_config_path()
52            .ok()
53            .and_then(|path| Config::load_from_path(&path).ok())
54            .map(|c| c.api_key)
55    } else {
56        None
57    };
58
59    let api_key = prompt_api_key(is_first_run, existing_key.as_deref());
60    let mut client = Client::new(api_key.clone());
61
62    let models = loop {
63        ui::fetching_models_message();
64        match client.fetch_models() {
65            Ok(m) => break m,
66            Err(ApiError::Unauthorized) => {
67                ui::error_message("Invalid API Key. Make sure you entered the correct key.");
68                let new_key = prompt_api_key(true, None);
69                client = Client::new(new_key);
70                continue;
71            }
72            Err(ApiError::RateLimited) => {
73                ui::rate_limited_message();
74                std::thread::sleep(std::time::Duration::from_secs(2));
75                continue;
76            }
77            Err(ApiError::EmptyResponse) => {
78                ui::error_message("No models available. Please try again.");
79                continue;
80            }
81            Err(ApiError::Forbidden) => {
82                return Err(ConfigError::ApiError(
83                    "API key doesn't have access. Check permissions on OpenRouter.".into(),
84                ));
85            }
86            Err(e) => {
87                return Err(ConfigError::ApiError(format!(
88                    "Failed to fetch models: {}. Please try again.",
89                    e
90                )));
91            }
92        }
93    };
94
95    let model_ids: Vec<String> = models.iter().map(|m| m.id.clone()).collect();
96    ui::models_loaded(model_ids.len());
97
98    let selection = ui::model_select_prompt(&model_ids);
99    let model_id = if selection == "[ Type Manual Model ID... ]" {
100        ui::manual_model_prompt()
101    } else {
102        selection
103    };
104
105    let config = Config {
106        api_key,
107        model_id,
108    };
109
110    let path = home_config_path()?;
111    config.save(&path)?;
112
113    ui::save_confirmation();
114    Ok(config)
115}