use std::env;
use std::fs;
use std::path::{Path, PathBuf};

// 仅 Unix/Linux 平台启用软链接 API
#[cfg(unix)]
use std::os::unix::fs::symlink;

fn main() {
    // 1. 读取环境变量，优雅处理缺失
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    let is_linux = target_os == "linux";
    let keyboard_enabled = env::var("CARGO_FEATURE_KEYBOARD").is_ok();

    // 无论分支是否执行，都监听自身变更
    println!("cargo:rerun-if-changed=build.rs");

    if !is_linux || !keyboard_enabled {
        return;
    }

    // 2. 统一用 PathBuf 处理路径，避免字符串拼接风险
    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR must be set by Cargo"));
    let lib_dir = out_dir.join("doe-x11-libs");

    // 确保目录存在
    fs::create_dir_all(&lib_dir).expect("Failed to create X11 lib dir");

    // 为 libXtst 创建运行时库软链接
    link_runtime_lib(&lib_dir, "libXtst.so.6", "libXtst.so");

    // 3. 统一 Linux 标准库搜索路径（去重、规范顺序）
    let search_paths = [
        lib_dir.as_path(),
        Path::new("/usr/lib/x86_64-linux-gnu"),
        Path::new("/usr/lib/aarch64-linux-gnu"),
        Path::new("/usr/lib/i386-linux-gnu"),
        Path::new("/lib/x86_64-linux-gnu"),
        Path::new("/usr/lib64"),
        Path::new("/lib64"),
        Path::new("/usr/lib"),
        Path::new("/lib"),
    ];

    // 输出链接搜索路径
    for path in search_paths {
        println!("cargo:rustc-link-search=native={}", path.display());
    }
}

/// 在指定目录创建运行时库 -> 开发库软链接（仅 Unix）
#[cfg(unix)]
fn link_runtime_lib(lib_dir: &Path, runtime_name: &str, link_name: &str) {
    let link_path = lib_dir.join(link_name);
    if link_path.exists() {
        return;
    }

    // Linux 通用系统库搜索路径
    let system_lib_paths = [
        "/lib/x86_64-linux-gnu",
        "/usr/lib/x86_64-linux-gnu",
        "/lib/aarch64-linux-gnu",
        "/usr/lib/aarch64-linux-gnu",
        "/lib/i386-linux-gnu",
        "/usr/lib/i386-linux-gnu",
        "/lib64",
        "/usr/lib64",
        "/lib",
        "/usr/lib",
    ];

    // 遍历查找运行时库
    for sys_lib_dir in &system_lib_paths {
        let runtime_path = Path::new(sys_lib_dir).join(runtime_name);
        if runtime_path.exists() {
            symlink(&runtime_path, &link_path)
                .unwrap_or_else(|e| eprintln!("cargo:warning=Create symlink failed: {}", e));
            return;
        }
    }

    // 未找到运行时库，输出警告
    eprintln!(
        "cargo:warning=Runtime library {} not found in system paths, linking may fail",
        runtime_name
    );
}

/// 非 Unix 平台空实现（避免编译报错）
#[cfg(not(unix))]
fn link_runtime_lib(_lib_dir: &Path, _runtime_name: &str, _link_name: &str) {}