use std::env;
use std::fs;
use std::path::Path;

fn main() {
    // Skip build script execution during docs.rs documentation generation
    // to prevent issues with asset processing and file system access
    if env::var("DOCS_RS").is_ok() {
        println!("cargo:warning=Skipping build script during docs.rs documentation generation");
        return;
    }

    println!("cargo:rerun-if-changed=src/");
    // Only watch parent directory if not building documentation
    println!("cargo:rerun-if-changed=scss/");

    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("theme_chalk_info.rs");

    // Create a file that embeds theme-chalk information
    let theme_info = r#"
// This file is auto-generated by build.rs
pub const THEME_CHALK_VERSION: &str = "1.0.0";
pub const THEME_CHALK_CSS_PATH: &str = "dist/theme-chalk.css";

/// Returns the path to the compiled theme-chalk CSS file
pub fn get_css_path() -> &'static str {
    "dist/theme-chalk.css"
}

/// Returns the version of theme-chalk being used
pub fn get_version() -> &'static str {
    "1.0.0"
}

"#;

    if let Err(e) = fs::write(&dest_path, theme_info) {
        // Gracefully handle write errors during documentation builds
        println!("cargo:warning=Failed to write theme info file: {}", e);
        return;
    }
    
    if let Ok(target) = env::var("TARGET") {
        println!("cargo:rustc-env=TARGET={}", target);
    }
}
