use atuin_client::settings::Tmux;
use atuin_dotfiles::store::{AliasStore, var::VarStore};
use eyre::Result;

fn print_tmux_config(tmux: &Tmux) {
    if tmux.enabled {
        println!("export ATUIN_TMUX_POPUP_WIDTH='{}'", tmux.width);
        println!("export ATUIN_TMUX_POPUP_HEIGHT='{}'", tmux.height);
    } else {
        println!("export ATUIN_TMUX_POPUP=false");
    }
}

pub fn init_static(disable_up_arrow: bool, disable_ctrl_r: bool, disable_ai: bool, tmux: &Tmux) {
    let base = include_str!("../../../shell/atuin.zsh");

    print_tmux_config(tmux);
    println!("{base}");

    if std::env::var("ATUIN_NOBIND").is_err() {
        const BIND_CTRL_R: &str = r"bindkey -M emacs '^r' atuin-search
bindkey -M viins '^r' atuin-search-viins
bindkey -M vicmd '/' atuin-search";

        const BIND_UP_ARROW: &str = r"bindkey -M emacs '^[[A' atuin-up-search
bindkey -M vicmd '^[[A' atuin-up-search-vicmd
bindkey -M viins '^[[A' atuin-up-search-viins
bindkey -M emacs '^[OA' atuin-up-search
bindkey -M vicmd '^[OA' atuin-up-search-vicmd
bindkey -M viins '^[OA' atuin-up-search-viins
bindkey -M vicmd 'k' atuin-up-search-vicmd";

        if !disable_ctrl_r {
            println!("{BIND_CTRL_R}");
        }
        if !disable_up_arrow {
            println!("{BIND_UP_ARROW}");
        }

        #[cfg(feature = "ai")]
        if !disable_ai {
            let bind_ai = atuin_ai::commands::init::generate_zsh_integration();

            println!("{bind_ai}");
        }
    }
}

pub async fn init(
    aliases: AliasStore,
    vars: VarStore,
    disable_up_arrow: bool,
    disable_ctrl_r: bool,
    disable_ai: bool,
    tmux: &Tmux,
) -> Result<()> {
    init_static(disable_up_arrow, disable_ctrl_r, disable_ai, tmux);

    let aliases = atuin_dotfiles::shell::zsh::alias_config(&aliases).await;
    let vars = atuin_dotfiles::shell::zsh::var_config(&vars).await;

    println!("{aliases}");
    println!("{vars}");

    Ok(())
}
