use crate::ui::nerd_font::NerdFont;
use anyhow::Result;
use clap::Subcommand;

mod clone;
mod fuzzy;
mod github;
mod install;
mod menu;
mod package;
mod setup;

pub use clone::{clone_or_pull_repository, ensure_workspace_dir};
pub use fuzzy::select_repository;
pub use github::fetch_instantos_repos;
pub use install::handle_install;

#[derive(Subcommand, Debug, Clone)]
pub enum DevCommands {
    Clone,
    Install,
    /// Setup development environment (Arch live ISO)
    Setup,
    /// Interactive dev menu (guided workflows)
    Menu,
}

pub async fn handle_dev_command(command: DevCommands, debug: bool) -> Result<()> {
    match command {
        DevCommands::Clone => handle_clone_internal(debug).await,
        DevCommands::Install => handle_install(debug).await,
        DevCommands::Setup => setup::handle_setup(debug).await,
        DevCommands::Menu => menu::dev_menu(debug).await,
    }
}

async fn handle_clone_internal(debug: bool) -> Result<()> {
    if debug {
        eprintln!(
            "{} Fetching instantOS repositories...",
            char::from(NerdFont::Search)
        );
    }

    let workspace_dir = ensure_workspace_dir()?;

    let pb =
        crate::common::progress::create_spinner("Fetching repositories from GitHub...".to_string());

    let repos = fetch_instantos_repos()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to fetch repositories: {}", e))?;

    crate::common::progress::finish_spinner_with_success(
        pb,
        format!("Found {} repositories", repos.len()),
    );

    if debug {
        eprintln!("{} Available repositories:", char::from(NerdFont::List));
        for repo in &repos {
            eprintln!("  - {} ({})", repo.name, repo.full_name);
        }
    }

    let selected = select_repository(repos, &workspace_dir)
        .map_err(|e| anyhow::anyhow!("Failed to select repository: {}", e))?;

    if debug {
        eprintln!(
            "{} Selected repository: {}",
            char::from(NerdFont::SourceBranch),
            selected.repo.name
        );
    }

    clone_or_pull_repository(&selected.repo, &selected.local_path, debug)?;

    Ok(())
}
