//! Build-time Environment and Manifest Access
//!
//! This module provides build-time specific utilities that handle environment
//! setup and provide convenient access to the manifest system.

use std::sync::Once;

static INIT: Once = Once::new();

/// Initialize environment loading - call this at the start of build scripts
///
/// This ensures .env files are loaded before manifest resolution, which is
/// critical for build scripts that need environment variables.
pub fn init_build_environment() {
    INIT.call_once(|| {
        // Try to load .env from workspace root or current directory
        let _ = dotenv::dotenv();

        // Also try common locations relative to build script
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
        if !manifest_dir.is_empty() {
            let workspace_root = std::path::Path::new(&manifest_dir)
                .parent()
                .and_then(|p| p.parent());

            if let Some(root) = workspace_root {
                let env_file = root.join(".env");
                if env_file.exists() {
                    let _ = dotenv::from_path(env_file);
                }
            }
        }
    });
}

/// Re-export types from manifest system for convenience
pub use rustelo_utils::{ManifestError, ManifestResolver};

/// Convenience function to create a manifest resolver for build-time use
///
/// Automatically calls init_build_environment() first to ensure .env is loaded.
pub fn get_manifest_resolver() -> Result<ManifestResolver, Box<dyn std::error::Error>> {
    init_build_environment();
    Ok(ManifestResolver::load()?)
}

// Re-export the manifest path functions directly - no need for wrappers
pub use rustelo_utils::{
    i18n_path as get_i18n_path, manifest_config_path as get_config_path,
    manifest_content_path as get_content_path,
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_environment_init() {
        // Test that environment initialization doesn't panic
        init_build_environment();

        // Test that we can create a manifest resolver after init
        if let Ok(_resolver) = get_manifest_resolver() {
            // Success - manifest was found
        } else {
            // Expected in test environment without manifest file
        }
    }

    #[test]
    fn test_path_functions_available() {
        // Test that path functions are available (may fail without manifest)
        // This just tests the re-export works, not the actual functionality
        let _content_fn = get_content_path as fn() -> std::path::PathBuf;
        let _config_fn = get_config_path as fn() -> std::path::PathBuf;
        let _i18n_fn = get_i18n_path as fn() -> std::path::PathBuf;
    }
}
