use std::future::Future;
use std::path::Path;
use std::path::PathBuf;

use crate::product::agent::CODEX_APPLY_PATCH_ARG1;
use clap::Parser;
#[cfg(unix)]
use std::os::unix::fs::symlink;
use tempfile::TempDir;

const LINUX_SANDBOX_ARG0: &str = "lha-linux-sandbox";
const APPLY_PATCH_ARG0: &str = "apply_patch";
const MISSPELLED_APPLY_PATCH_ARG0: &str = "applypatch";
const EXEC_ARG0: &str = "lha-exec";
const APP_SERVER_ARG0: &str = "lha-app-server";
const MCP_SERVER_ARG0: &str = "lha-mcp-server";
const STDIO_TO_UDS_ARG0: &str = "lha-stdio-to-uds";
const CODEX_RESPONSES_API_PROXY_ARG0: &str = "codex-responses-api-proxy";
#[cfg(any(test, debug_assertions))]
const TEST_STDIO_SERVER_ARG0: &str = "test_stdio_server";
#[cfg(any(test, debug_assertions))]
const TEST_STREAMABLE_HTTP_SERVER_ARG0: &str = "test_streamable_http_server";

pub fn arg0_dispatch() -> Option<TempDir> {
    // Determine if we were invoked via the special alias.
    let mut args = std::env::args_os();
    let argv0 = args.next().unwrap_or_default();
    let exe_name = Path::new(&argv0)
        .file_name()
        .and_then(|s| s.to_str())
        .map(normalize_exe_name)
        .unwrap_or_default();

    if exe_name == LINUX_SANDBOX_ARG0 {
        // Safety: [`run_main`] never returns.
        crate::product::linux_sandbox::run_main();
    } else if exe_name == APPLY_PATCH_ARG0 || exe_name == MISSPELLED_APPLY_PATCH_ARG0 {
        crate::product::apply_patch::main();
    } else if is_sensitive_early_alias(exe_name) {
        crate::product::process_hardening::pre_main_hardening();
        let args = crate::product::responses_api_proxy::Args::parse();
        exit_with_result(crate::product::responses_api_proxy::run_main(args));
    }

    let argv1 = args.next().unwrap_or_default();
    if argv1 == CODEX_APPLY_PATCH_ARG1 {
        let patch_arg = args.next().and_then(|s| s.to_str().map(str::to_owned));
        let exit_code = match patch_arg {
            Some(patch_arg) => {
                let mut stdout = std::io::stdout();
                let mut stderr = std::io::stderr();
                match crate::product::apply_patch::apply_patch(&patch_arg, &mut stdout, &mut stderr)
                {
                    Ok(()) => 0,
                    Err(_) => 1,
                }
            }
            None => {
                eprintln!("Error: {CODEX_APPLY_PATCH_ARG1} requires a UTF-8 PATCH argument.");
                1
            }
        };
        std::process::exit(exit_code);
    }

    // This modifies the environment, which is not thread-safe, so do this
    // before creating any threads/the Tokio runtime.
    load_dotenv();

    match prepend_path_entry_for_codex_aliases() {
        Ok(path_entry) => {
            dispatch_single_binary_alias(exe_name, Some(&path_entry));
            Some(path_entry)
        }
        Err(err) => {
            // It is possible that LHA will proceed successfully even if
            // updating the PATH fails, so warn the user and move on.
            eprintln!("WARNING: proceeding, even though we could not update PATH: {err}");
            dispatch_single_binary_alias(exe_name, None);
            None
        }
    }
}

fn normalize_exe_name(name: &str) -> &str {
    name.strip_suffix(".exe").unwrap_or(name)
}

fn dispatch_single_binary_alias(exe_name: &str, _path_entry: Option<&TempDir>) {
    match exe_name {
        EXEC_ARG0 => {
            let cli = crate::product::exec_cli::parse_with_config_overrides();
            exit_after_block_on(async move {
                crate::product::exec_cli::run_main(cli, linux_sandbox_exe()).await
            });
        }
        APP_SERVER_ARG0 => {
            exit_after_block_on(async move {
                let loader_overrides = crate::product::agent::config_loader::LoaderOverrides {
                    managed_config_path: managed_config_path_from_debug_env(),
                    ..Default::default()
                };
                crate::product::app_server::run_main(
                    linux_sandbox_exe(),
                    crate::product::common::CliConfigOverrides::default(),
                    loader_overrides,
                    false,
                )
                .await
                .map_err(anyhow::Error::from)
            });
        }
        MCP_SERVER_ARG0 => {
            exit_after_block_on(async move {
                crate::product::mcp_server::run_main(
                    linux_sandbox_exe(),
                    crate::product::common::CliConfigOverrides::default(),
                )
                .await
                .map_err(anyhow::Error::from)
            });
        }
        STDIO_TO_UDS_ARG0 => {
            let Some(socket_path) = std::env::args_os().nth(1) else {
                eprintln!("Error: {STDIO_TO_UDS_ARG0} requires a SOCKET_PATH argument.");
                std::process::exit(1);
            };
            exit_with_result(crate::product::stdio_to_uds::run(Path::new(&socket_path)));
        }
        #[cfg(any(test, debug_assertions))]
        TEST_STDIO_SERVER_ARG0 => {
            exit_after_block_on(async {
                crate::product::rmcp_client::test_stdio_server::run_main().await
            });
        }
        #[cfg(any(test, debug_assertions))]
        TEST_STREAMABLE_HTTP_SERVER_ARG0 => {
            exit_after_block_on(async {
                crate::product::rmcp_client::test_streamable_http_server::run_main().await
            });
        }
        _ => {}
    }
}

fn is_sensitive_early_alias(exe_name: &str) -> bool {
    exe_name == CODEX_RESPONSES_API_PROXY_ARG0
}

fn linux_sandbox_exe() -> Option<PathBuf> {
    if cfg!(target_os = "linux") {
        std::env::current_exe().ok()
    } else {
        None
    }
}

fn managed_config_path_from_debug_env() -> Option<PathBuf> {
    #[cfg(debug_assertions)]
    {
        if let Ok(value) = std::env::var("CODEX_APP_SERVER_MANAGED_CONFIG_PATH") {
            return if value.is_empty() {
                None
            } else {
                Some(PathBuf::from(value))
            };
        }
    }

    None
}

fn exit_after_block_on<F>(future: F) -> !
where
    F: Future<Output = anyhow::Result<()>>,
{
    let result = tokio::runtime::Runtime::new().and_then(|runtime| {
        runtime
            .block_on(future)
            .map_err(|err| std::io::Error::other(format!("{err:?}")))
    });
    exit_with_result(result.map_err(anyhow::Error::from));
}

fn exit_with_result(result: anyhow::Result<()>) -> ! {
    match result {
        Ok(()) => std::process::exit(0),
        Err(err) => {
            eprintln!("{err:?}");
            std::process::exit(1);
        }
    }
}

/// While we want to deploy the LHA CLI as a single executable for simplicity,
/// we also want to expose some of its functionality as distinct CLIs, so we use
/// the "arg0 trick" to determine which CLI to dispatch. This effectively allows
/// us to simulate deploying multiple executables as a single binary on Mac and
/// Linux (but not Windows).
///
/// When the current executable is invoked through the hard-link or alias named
/// `lha-linux-sandbox` we *directly* execute
/// [`crate::product::linux_sandbox::run_main`] (which never returns). Otherwise we:
///
/// 1.  Load `.env` values from `~/.lha/.env` before creating any threads.
/// 2.  Construct a Tokio multi-thread runtime.
/// 3.  Derive the path to the current executable (so children can re-invoke the
///     sandbox) when running on Linux.
/// 4.  Execute the provided async `main_fn` inside that runtime, forwarding any
///     error. Note that `main_fn` receives `codex_linux_sandbox_exe:
///     Option<PathBuf>`, as an argument, which is generally needed as part of
///     constructing [`crate::product::agent::config::Config`].
///
/// This function should be used to wrap any `main()` function in binary crates
/// in this workspace that depends on these helper CLIs.
pub fn arg0_dispatch_or_else<F, Fut>(main_fn: F) -> anyhow::Result<()>
where
    F: FnOnce(Option<PathBuf>) -> Fut,
    Fut: Future<Output = anyhow::Result<()>>,
{
    // Retain the TempDir so it exists for the lifetime of the invocation of
    // this executable. Admittedly, we could invoke `keep()` on it, but it
    // would be nice to avoid leaving temporary directories behind, if possible.
    let _path_entry = arg0_dispatch();

    // Regular invocation – create a Tokio runtime and execute the provided
    // async entry-point.
    let runtime = tokio::runtime::Runtime::new()?;
    runtime.block_on(async move {
        let codex_linux_sandbox_exe: Option<PathBuf> = if cfg!(target_os = "linux") {
            std::env::current_exe().ok()
        } else {
            None
        };

        main_fn(codex_linux_sandbox_exe).await
    })
}

const ILLEGAL_ENV_VAR_PREFIX: &str = "CODEX_";

/// Load env vars from ~/.lha/.env.
///
/// Security: Do not allow `.env` files to create or modify any variables
/// with names starting with `CODEX_`.
fn load_dotenv() {
    if let Ok(lha_home) = crate::product::agent::config::find_lha_home()
        && let Ok(iter) = dotenvy::from_path_iter(lha_home.join(".env"))
    {
        set_filtered(iter);
    }
}

/// Helper to set vars from a dotenvy iterator while filtering out `CODEX_` keys.
fn set_filtered<I>(iter: I)
where
    I: IntoIterator<Item = Result<(String, String), dotenvy::Error>>,
{
    for (key, value) in iter.into_iter().flatten() {
        if !key.to_ascii_uppercase().starts_with(ILLEGAL_ENV_VAR_PREFIX) {
            // It is safe to call set_var() because our process is
            // single-threaded at this point in its execution.
            unsafe { std::env::set_var(&key, &value) };
        }
    }
}

/// Creates a temporary directory with either:
///
/// - UNIX: `apply_patch` symlink to the current executable
/// - WINDOWS: `apply_patch.bat` batch script to invoke the current executable
///   with the "secret" --codex-run-as-apply-patch flag.
///
/// This temporary directory is prepended to the PATH environment variable so
/// that `apply_patch` can be on the PATH without requiring the user to
/// install a separate `apply_patch` executable, simplifying the deployment of
/// LHA CLI.
/// Note: In debug builds the temp-dir guard is disabled to ease local testing.
///
/// IMPORTANT: This function modifies the PATH environment variable, so it MUST
/// be called before multiple threads are spawned.
pub fn prepend_path_entry_for_codex_aliases() -> std::io::Result<TempDir> {
    let lha_home = crate::product::agent::config::find_lha_home()?;
    #[cfg(not(debug_assertions))]
    {
        // Guard against placing helpers in system temp directories outside debug builds.
        let temp_root = std::env::temp_dir();
        if lha_home.starts_with(&temp_root) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!(
                    "Refusing to create helper binaries under temporary dir {temp_root:?} (lha_home: {lha_home:?})"
                ),
            ));
        }
    }

    std::fs::create_dir_all(&lha_home)?;
    // Use a LHA_HOME-scoped temp root to avoid cluttering the top-level directory.
    let temp_root = lha_home.join("tmp").join("path");
    std::fs::create_dir_all(&temp_root)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        // Ensure only the current user can access the temp directory.
        std::fs::set_permissions(&temp_root, std::fs::Permissions::from_mode(0o700))?;
    }

    let temp_dir = tempfile::Builder::new()
        .prefix("lha-arg0")
        .tempdir_in(&temp_root)?;
    let path = temp_dir.path();

    for filename in &[
        APPLY_PATCH_ARG0,
        MISSPELLED_APPLY_PATCH_ARG0,
        #[cfg(target_os = "linux")]
        LINUX_SANDBOX_ARG0,
    ] {
        let exe = std::env::current_exe()?;

        #[cfg(unix)]
        {
            let link = path.join(filename);
            symlink(&exe, &link)?;
        }

        #[cfg(windows)]
        {
            let batch_script = path.join(format!("{filename}.bat"));
            std::fs::write(
                &batch_script,
                format!(
                    r#"@echo off
"{}" {CODEX_APPLY_PATCH_ARG1} %*
"#,
                    exe.display()
                ),
            )?;
        }
    }

    #[cfg(unix)]
    const PATH_SEPARATOR: &str = ":";

    #[cfg(windows)]
    const PATH_SEPARATOR: &str = ";";

    let path_element = path.display();
    let updated_path_env_var = match std::env::var("PATH") {
        Ok(existing_path) => {
            format!("{path_element}{PATH_SEPARATOR}{existing_path}")
        }
        Err(_) => {
            format!("{path_element}")
        }
    };

    unsafe {
        std::env::set_var("PATH", updated_path_env_var);
    }

    Ok(temp_dir)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn codex_responses_proxy_is_sensitive_early_alias() {
        assert!(is_sensitive_early_alias("codex-responses-api-proxy"));
    }
}
