//! `keg docs` command — Open Kegani documentation in browser

use anyhow::Result;
use console::{style, Emoji};
use std::process::Command;

/// Open Kegani documentation in browser
pub fn open_docs(section: &str) -> Result<()> {
    println!();
    println!("{} {}", Emoji("📚", ""), style("Opening Kegani Documentation").bold());
    println!();

    let url = match section {
        "api" => "https://docs.rs/kegani/latest/kegani/",
        "guide" => "https://kegani.dev/guide",
        "crates" => "https://crates.io/crates/kegani",
        "github" => "https://github.com/kegani/kegani",
        "examples" => "https://github.com/kegani/kegani/examples",
        _ => {
            println!("  {} Unknown section '{}'. Using guide.", style("⚠").yellow(), section);
            "https://kegani.dev/guide"
        }
    };

    println!("  {} {}", style("→").cyan(), style(url).underlined().cyan());
    println!();

    // Try to open in browser
    let open_result: Option<std::process::ExitStatus> =
        if cfg!(target_os = "macos") {
            Command::new("open").arg(url).status().ok()
        } else if cfg!(target_os = "linux") {
            Command::new("xdg-open").arg(url).status().ok()
        } else if cfg!(target_os = "windows") {
            Command::new("start").arg(url).status().ok()
        } else {
            None
        };

    match open_result {
        Some(status) if status.success() => {
            println!("  {} {}", style("✓").green(), style("Opened in browser").green());
        }
        _ => {
            println!("  {} Could not open browser automatically.", style("ℹ").dim());
            println!("  {} Copy this URL manually: {}", style("→").cyan(), url);
        }
    }

    Ok(())
}
