//! IDE integration command implementation.

use anyhow::Result;
use hx_config::{HieYamlStatus, Project, check_hie_yaml, find_project_root, write_hie_yaml};
use hx_toolchain::Toolchain;
use hx_ui::Output;

use crate::cli::IdeCommands;

/// Run the ide command.
pub async fn run(command: IdeCommands, output: &Output) -> Result<i32> {
    match command {
        IdeCommands::Setup { force } => setup(force, output).await,
        IdeCommands::Status => status(output).await,
    }
}

/// Generate or update hie.yaml.
async fn setup(force: bool, output: &Output) -> Result<i32> {
    let project_root = find_project_root(".")?;
    let project = Project::load(&project_root)?;

    output.status("Configuring", "IDE integration");

    let status = check_hie_yaml(&project);

    match status {
        HieYamlStatus::Exists if !force => {
            output.warn("hie.yaml already exists (not generated by hx)");
            output.info("Use --force to overwrite");
            return Ok(1);
        }
        HieYamlStatus::UpToDate if !force => {
            output.status("Up to date", "hie.yaml is current");
            return Ok(0);
        }
        _ => {}
    }

    // Write the hie.yaml
    write_hie_yaml(&project)?;

    if project.is_workspace() {
        output.status(
            "Generated",
            &format!("hie.yaml for {} packages", project.workspace_packages.len()),
        );

        // List the packages
        for pkg in &project.workspace_packages {
            output.list_item(&pkg.name, &pkg.path.display().to_string());
        }
    } else {
        output.status("Generated", "hie.yaml");
    }

    output.info("HLS should now work correctly with your project");
    output.info("Restart your IDE/LSP client to apply changes");

    Ok(0)
}

/// Show IDE/HLS configuration status.
async fn status(output: &Output) -> Result<i32> {
    let project_root = find_project_root(".")?;
    let project = Project::load(&project_root)?;

    output.header("IDE Status");

    // Check hie.yaml
    let hie_status = check_hie_yaml(&project);
    match hie_status {
        HieYamlStatus::Missing => {
            output.list_item("hie.yaml", "not found");
            if project.is_workspace() || project.has_cabal_project {
                output.warn("Consider running `hx ide setup` for multi-package support");
            }
        }
        HieYamlStatus::Exists => {
            output.list_item("hie.yaml", "found (custom configuration)");
        }
        HieYamlStatus::UpToDate => {
            output.list_item("hie.yaml", "up to date (generated by hx)");
        }
        HieYamlStatus::Outdated => {
            output.list_item("hie.yaml", "outdated");
            output.warn("Run `hx ide setup --force` to regenerate");
        }
    }

    // Check HLS
    let toolchain = Toolchain::detect().await;

    if toolchain.hls.status.is_found() {
        let version = toolchain
            .hls
            .status
            .version()
            .map(|v| v.to_string())
            .unwrap_or_else(|| "installed".to_string());
        output.list_item("hls", &version);

        // Check compatibility with GHC
        if let (Some(hls_ver), Some(ghc_ver)) = (
            toolchain.hls.status.version(),
            toolchain.ghc.status.version(),
        ) {
            let hls_str = hls_ver.to_string();
            let ghc_str = ghc_ver.to_string();

            if hx_config::is_hls_compatible(&hls_str, &ghc_str) {
                output.list_item(
                    "compatibility",
                    &format!("HLS {} + GHC {} ✓", hls_str, ghc_str),
                );
            } else {
                output.list_item(
                    "compatibility",
                    &format!("HLS {} + GHC {} (may have issues)", hls_str, ghc_str),
                );

                if let Some(recommended) = hx_config::recommended_hls_for_ghc(&ghc_str) {
                    output.info(&format!(
                        "Recommended HLS for GHC {}: {}",
                        ghc_str, recommended
                    ));
                }
            }
        }
    } else {
        output.list_item("hls", "not found");
        output.warn("Install HLS for IDE features: ghcup install hls");
    }

    // Project info
    if project.is_workspace() {
        output.list_item("project type", "workspace");
        output.list_item("packages", &project.package_count().to_string());
    } else {
        output.list_item("project type", "single package");
    }

    Ok(0)
}
