//! Build script for rustelo_core_lib
//!
//! Detects when resources are provided by website implementations using
//! environment variables set by the website build system (PAP-compliant)

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let out_dir = env::var("OUT_DIR")?;
    let out_dir_path = Path::new(&out_dir);
    let resource_registry_path = out_dir_path.join("resource_registry.rs");

    // Check multiple locations for resource_registry.rs
    let mut found_resources = false;

    // 1. First check: Generated in OUT_DIR (by website-server/build.rs)
    if resource_registry_path.exists() {
        println!("cargo:rustc-cfg=has_generated_resources");
        println!("cargo:warning=✅ Found generated resources in OUT_DIR");
        found_resources = true;
    }

    // 2. Second check: Environment variable pointing to resource registry (set by
    //    website build system)
    // This allows website-server/build.rs to tell us where resources are without
    // needing manifest access
    if !found_resources {
        if let Ok(resource_path) = env::var("RUSTELO_RESOURCE_REGISTRY_PATH") {
            let candidate = Path::new(&resource_path);
            if candidate.exists() {
                println!("cargo:rustc-cfg=has_generated_resources");
                println!(
                    "cargo:warning=✅ Found generated resources via \
                     RUSTELO_RESOURCE_REGISTRY_PATH: {}",
                    candidate.display()
                );

                // Copy to OUT_DIR for caching
                if let Ok(content) = std::fs::read_to_string(candidate) {
                    let _ = std::fs::write(&resource_registry_path, content);
                }
                found_resources = true;
            }
        }
    }

    // 3. Try manifest system as fallback (only works if manifest can be found)
    if !found_resources {
        if let Ok(manifest) = rustelo_utils::ManifestResolver::load() {
            let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_string());
            let target_arch = if target.contains("wasm") {
                "wasm32-unknown-unknown"
            } else {
                "aarch64-apple-darwin"
            };

            // Check configured build cache location per manifest
            let build_output = manifest
                .root()
                .join("target/site_build/devtools/build-cache");
            let candidate =
                build_output.join(format!("core-lib/{}/resource_registry.rs", target_arch));
            if candidate.exists() {
                println!("cargo:rustc-cfg=has_generated_resources");
                println!(
                    "cargo:warning=✅ Found generated resources via manifest at: {}",
                    candidate.display()
                );

                if let Ok(content) = std::fs::read_to_string(candidate) {
                    let _ = std::fs::write(&resource_registry_path, content);
                }
                found_resources = true;
            }
        }
    }

    // 4. Final fallback: Standalone mode
    if !found_resources {
        println!("cargo:warning=Building without generated resources (standalone mode)");
    }

    Ok(())
}
