use std::path::Path;
use std::process::Command;

fn main() {
    // Verify that required directories exist at build time
    let required_dirs = vec!["static", "templates", "node_modules"];

    let mut missing_dirs = Vec::new();

    for dir in &required_dirs {
        if !Path::new(dir).exists() {
            missing_dirs.push(*dir);
        }
    }

    if !missing_dirs.is_empty() {
        println!("cargo:warning=Missing required directories:");
        for dir in &missing_dirs {
            println!("cargo:warning=  - {}", dir);
        }

        if missing_dirs.contains(&"node_modules") {
            println!("cargo:warning=Run 'npm install' to install frontend dependencies");
        }
    }

    // Verify critical files
    let required_files = vec![
        "templates/term.html",
        "static/terminal.js",
        "static/terminado-addon.js",
        "static/styles.css",
    ];

    let mut missing_files = Vec::new();

    for file in &required_files {
        if !Path::new(file).exists() {
            missing_files.push(*file);
        }
    }

    if !missing_files.is_empty() {
        println!("cargo:warning=Missing required files:");
        for file in &missing_files {
            println!("cargo:warning=  - {}", file);
        }
    }

    // Build mdBook documentation
    build_documentation();

    // Tell cargo to rerun if these directories change
    println!("cargo:rerun-if-changed=static/");
    println!("cargo:rerun-if-changed=templates/");
    println!("cargo:rerun-if-changed=package.json");
    println!("cargo:rerun-if-changed=package-lock.json");
    println!("cargo:rerun-if-changed=docs/");
}

fn build_documentation() {
    let docs_dir = Path::new("docs");
    let static_docs_dir = Path::new("static/docs");

    // If static/docs already exists (e.g., from Docker COPY), we're done
    if static_docs_dir.exists() {
        println!("cargo:warning=Documentation already present in static/docs");
        return;
    }

    if !docs_dir.exists() {
        println!("cargo:warning=Documentation directory not found, skipping docs build");
        return;
    }

    // Check if mdbook is installed
    let mdbook_check = Command::new("mdbook").arg("--version").output();

    if mdbook_check.is_err() {
        println!("cargo:warning=mdbook not found. Install with: cargo install mdbook");
        println!("cargo:warning=Skipping documentation build");
        println!("cargo:warning=Documentation will be available if pre-built in static/docs");
        return;
    }

    // Note: mdbook-catppuccin preprocessor is deprecated
    // Catppuccin theme is now applied via CSS file in docs/theme/
    // No need to check for mdbook-catppuccin installation

    // Build the documentation
    println!("cargo:warning=Building documentation with mdbook...");
    let build_result = Command::new("mdbook")
        .arg("build")
        .current_dir("docs")
        .status();

    match build_result {
        Ok(status) if status.success() => {
            println!("cargo:warning=Documentation built successfully");

            // Copy docs to static directory for serving
            if Path::new("docs/book").exists() {
                // Ensure static directory exists
                let _ = std::fs::create_dir_all("static");

                let copy_result = if cfg!(target_os = "windows") {
                    Command::new("xcopy")
                        .args(["/E", "/I", "/Y", "docs\\book", "static\\docs"])
                        .status()
                } else {
                    Command::new("cp")
                        .args(["-r", "docs/book", "static/docs"])
                        .status()
                };

                match copy_result {
                    Ok(status) if status.success() => {
                        println!("cargo:warning=Documentation copied to static/docs");
                    }
                    _ => {
                        println!("cargo:warning=Failed to copy documentation to static directory");
                    }
                }
            }
        }
        Ok(_) => {
            println!("cargo:warning=mdbook build failed");
        }
        Err(e) => {
            println!("cargo:warning=Failed to run mdbook: {}", e);
        }
    }
}
