use std::env;
use std::path::Path;
use std::process::Command;

pub fn open(file_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let editor = get_editor();

    println!("  Opening {} in {}...", file_path.display(), editor);
    println!("  Edit your resume, then save and quit to continue.\n");

    // VS Code returns immediately when you open a file
    // --wait tells it to block until the user closes the tab
    // every other editor (nvim, vim, nano) blocks by default
    let status = if editor.contains("code") {
        Command::new(&editor)
            .arg("--wait")
            .arg(file_path)
            .status()?
    } else {
        Command::new(&editor)
            .arg(file_path)
            .status()?
    };

    // .success() returns true if the exit code was 0
    if !status.success() {
        return Err(format!(
            "Editor '{}' exited with an error.\nTip: set your editor with: export EDITOR=nvim",
            editor
        ).into());
    }

    println!("\n  Editor closed. Continuing...\n");
    Ok(())
}

fn get_editor() -> String {
    // check $EDITOR environment variable first
    if let Ok(e) = env::var("EDITOR") {
        if !e.is_empty() {
            return e;
        }
    }

    // check $VISUAL as a second option
    if let Ok(e) = env::var("VISUAL") {
        if !e.is_empty() {
            return e;
        }
    }

    let candidates = [
        "nvim",     // neovim — our priority
        "vim",      // vim fallback
        "nano",     // simple terminal editor
        "vi",       // last resort unix editor
        "code",     // VS Code
        "notepad",  // Windows fallback
    ];

    for editor in &candidates {
        if Command::new(editor).arg("--version").output().is_ok() {
            return editor.to_string();
        }
    }

    // if nothing found, default to nvim and let it fail with a clear error
    "nvim".to_string()
}
