use anyhow::Result;
use owo_colors::OwoColorize;

use crate::client;
use crate::config::ResolvedConfig;
use crate::output::OutputFormat;
use crate::style::Styles;

pub async fn run(
    config: &ResolvedConfig,
    base_url: Option<&str>,
    format: OutputFormat,
) -> Result<()> {
    let sp = client::spinner_for("Checking API status...", format);

    let c = client::public_client(config, base_url)?;

    // Use get_tickers as a health check (public, lightweight)
    match c.get_tickers().await {
        Ok(tickers) => {
            sp.finish_and_clear();

            let api_url = crate::auth::resolve_base_url(base_url, config).to_string();
            let market_count = tickers.len();

            // Check authentication
            let auth_status = if config.api_secret.is_some() {
                match client::authenticated_client(config, None, base_url) {
                    Ok(ac) => match ac.get_balances().await {
                        Ok(_) => Some(true),
                        Err(_) => Some(false),
                    },
                    Err(_) => Some(false),
                }
            } else {
                None
            };

            match format {
                OutputFormat::Json => {
                    let mut obj = serde_json::json!({
                        "api_reachable": true,
                        "api_url": api_url,
                        "markets": market_count,
                    });
                    match auth_status {
                        Some(true) => obj["authenticated"] = serde_json::json!(true),
                        Some(false) => obj["authenticated"] = serde_json::json!(false),
                        None => obj["authenticated"] = serde_json::json!(null),
                    }
                    crate::output::print_json(&obj);
                }
                OutputFormat::Table => {
                    let s = Styles::new();
                    println!(
                        "{} API is {} ({}) — {} markets active",
                        "✓".style(s.green),
                        "reachable".style(s.green),
                        api_url.style(s.dim),
                        market_count
                    );
                    match auth_status {
                        Some(true) => println!(
                            "{} Authenticated {}",
                            "✓".style(s.green),
                            "(API key valid)".style(s.dim)
                        ),
                        Some(false) => {
                            println!("{} Authentication failed", "✗".style(s.red));
                            println!();
                            println!("  Try these steps:");
                            println!(
                                "  1. Run {} to re-enter your API key",
                                "bpx setup".style(s.bold)
                            );
                            println!(
                                "  2. Check your key is active at {}",
                                "backpack.exchange/settings/api-keys".style(s.bold)
                            );
                            println!(
                                "  3. Make sure you copied the secret key, not the public key"
                            );
                        }
                        None => {
                            println!(
                                "{} Not authenticated. Run {} or set {} to configure.",
                                "–".style(s.yellow),
                                "bpx setup".style(s.bold),
                                "BPX_API_SECRET".style(s.bold),
                            );
                        }
                    }
                }
            }
        }
        Err(e) => {
            sp.finish_and_clear();
            anyhow::bail!("Network error: API unreachable: {e}");
        }
    }

    Ok(())
}
