fn main() {
    build_record_daemon();
    tauri_build::build()
}

/// Build the record-daemon in release mode and place it in the binaries/
/// directory with the target-triple suffix that Tauri's `externalBin` feature
/// expects.
///
/// The resulting binary is copied to:
///   src-tauri/binaries/record-daemon-<target-triple>[.exe]
///
/// This runs as part of `cargo build`, so the daemon is always available when
/// the Tauri bundler needs it.  Because record-daemon lives in a separate
/// Cargo workspace, invoking `cargo build` from here does not conflict with
/// the parent build's lock.
fn build_record_daemon() {
    use std::env;
    use std::fs;
    use std::path::PathBuf;
    use std::process::Command;

    let target = env::var("TARGET").unwrap();
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    // Resolve the record-daemon crate root (../../record-daemon/ from src-tauri/)
    let daemon_dir = manifest_dir
        .parent()
        .expect("CARGO_MANIFEST_DIR has no parent")
        .parent()
        .expect("parent of CARGO_MANIFEST_DIR has no parent")
        .join("record-daemon");

    let daemon_manifest = daemon_dir.join("Cargo.toml");
    if !daemon_manifest.exists() {
        eprintln!(
            "cargo:warning=record-daemon not found at {}, skipping daemon build",
            daemon_manifest.display()
        );
        return;
    }

    // Build the daemon in release mode for the same target triple.
    // Passing --target ensures the output lands in a predictable directory
    // and supports cross-compilation.
    let status = Command::new("cargo")
        .args([
            "build",
            "--release",
            "--manifest-path",
        ])
        .arg(&daemon_manifest)
        .arg("--target")
        .arg(&target)
        .status()
        .expect("Failed to execute cargo build for record-daemon");

    if !status.success() {
        panic!("Failed to build record-daemon in release mode");
    }

    // Locate the built binary.
    // When --target is specified, cargo places output in target/<triple>/release/.
    let src_name = if target.contains("windows") {
        "record-daemon.exe"
    } else {
        "record-daemon"
    };
    let src_binary = daemon_dir
        .join("target")
        .join(&target)
        .join("release")
        .join(src_name);

    if !src_binary.exists() {
        panic!(
            "record-daemon binary not found at {} after successful build",
            src_binary.display()
        );
    }

    // Copy to src-tauri/binaries/record-daemon-<target-triple>[.exe]
    let binaries_dir = manifest_dir.join("binaries");
    fs::create_dir_all(&binaries_dir).expect("Failed to create binaries directory");

    let dst_name = if target.contains("windows") {
        format!("record-daemon-{}.exe", target)
    } else {
        format!("record-daemon-{}", target)
    };
    let dst_binary = binaries_dir.join(&dst_name);

    fs::copy(&src_binary, &dst_binary).expect("Failed to copy record-daemon binary");
    fs::copy(daemon_dir
        .join("target")
        .join(&target)
        .join("release")
        .join("obs.dll"), binaries_dir.join("obs.dll")).expect("Failed to copy record-daemon dummy obs.dll");
    println!(
        "cargo:warning=Bundled record-daemon → {}",
        dst_binary.display()
    );
}
