//! Build Tools Module
//!
//! This module contains all build-time tools and utilities,
//! consolidated from the former build-tools crate.

pub mod api;
pub mod build_tasks;
pub mod config_constants;
pub mod enhanced_page_scaffolding;
pub mod foundation_discovery;
pub mod import_generation;
pub mod page_scaffolding;
pub mod path_resolution;
pub mod route_analysis;
pub mod templates;
pub mod virtual_resolution;

// Re-export all public items (avoiding conflicting names)
pub use api::*;
// Re-export build_tasks without the conflicting path functions
pub use build_tasks::{
    embed_routes_config, generate_client_route_documentation, generate_component_documentation,
    generate_comprehensive_documentation, generate_content_types,
    generate_enhanced_client_documentation, generate_page_boilerplate, generate_page_components,
    generate_pages_from_templates, generate_resource_contributor_code, generate_resource_registry,
    generate_route_components, generate_route_table, generate_server_route_documentation,
    generate_server_routing, route_generation,
};
pub use import_generation::*;
pub use page_scaffolding::*;
// Re-export build-time manifest access functions
pub use path_resolution::{
    get_config_path, get_content_path, get_i18n_path, get_manifest_resolver,
    init_build_environment, ManifestError, ManifestResolver,
};
pub use route_analysis::*;
pub use virtual_resolution::*;

/// Generate all shared resources and documentation during build time
/// This is the main entry point called from build.rs scripts
pub fn generate_shared_resources() -> Result<(), Box<dyn std::error::Error>> {
    println!("🚀 Generating shared resources and site information...");

    // Get the OUT_DIR where generated files should go
    let out_dir = std::env::var("OUT_DIR")?;

    // Use manifest resolver
    let resolver = path_resolution::get_manifest_resolver()?;

    println!("🔍 Project root: {}", resolver.root().display());
    println!("🔍 OUT_DIR: {}", out_dir);

    // Generate configuration constants first (critical for WASM compatibility)
    match config_constants::generate_config_constants(&out_dir) {
        Ok(()) => {
            println!("✅ Configuration constants generated successfully");
        }
        Err(e) => {
            eprintln!("❌ Configuration constants generation failed: {}", e);
            return Err(format!("Configuration constants generation failed: {}", e).into());
        }
    }

    // Get paths from manifest resolver
    let project_root = resolver.root();
    let workspace_root = project_root.to_string_lossy().to_string();
    let content_root = rustelo_utils::manifest_content_path()
        .to_string_lossy()
        .to_string();
    let site_root = project_root.join("site").to_string_lossy().to_string();
    let info_path = project_root
        .join("site")
        .join("info")
        .to_string_lossy()
        .to_string();
    let templates_path = format!("{}/templates", site_root);

    // Set template path for the build
    std::env::set_var("SITE_TEMPLATES_PATH", &templates_path);
    println!("🎨 Template path: {}", templates_path);

    // Generate route components first (required for shared crate)
    match build_tasks::route_generation::generator::generate_route_components(&site_root, &out_dir)
    {
        Ok(()) => {
            println!("✅ Route components generated successfully");
        }
        Err(e) => {
            eprintln!("❌ Route generation failed: {}", e);
            return Err(format!("Route generation failed: {}", e).into());
        }
    }

    // Generate content types (also required for shared crate)
    match build_tasks::content_types::generate_content_types(&content_root, &out_dir) {
        Ok(()) => {
            println!("✅ Content types generated successfully");
        }
        Err(e) => {
            eprintln!("❌ Content types generation failed: {}", e);
            return Err(format!("Content types generation failed: {}", e).into());
        }
    }

    // Embed routes configuration (required for shared crate routing utils)
    match build_tasks::resource_discovery::embed_routes_config(&site_root, &out_dir) {
        Ok(()) => {
            println!("✅ Routes config embedded successfully");
        }
        Err(e) => {
            eprintln!("❌ Routes config embedding failed: {}", e);
            return Err(format!("Routes config embedding failed: {}", e).into());
        }
    }

    // Generate resource registry (required for shared crate resource loading)
    match build_tasks::resource_discovery::generate_resource_registry(&content_root, &out_dir) {
        Ok(()) => {
            println!("✅ Resource registry generated successfully");
        }
        Err(e) => {
            eprintln!("❌ Resource registry generation failed: {}", e);
            return Err(format!("Resource registry generation failed: {}", e).into());
        }
    }

    // Generate page components from routes (replacing generate_page! macro)
    match build_tasks::page_generation::generate_page_components(
        &build_tasks::route_generation::loader::load_routes_config(&site_root)?,
        &out_dir,
    ) {
        Ok(()) => {
            println!("✅ Page components generated successfully");
        }
        Err(e) => {
            eprintln!("❌ Page components generation failed: {}", e);
            return Err(format!("Page components generation failed: {}", e).into());
        }
    }

    // Generate comprehensive documentation with template system
    match build_tasks::comprehensive_analysis::generate_comprehensive_documentation(
        &site_root,      // content_root
        &info_path,      // codegen_path
        &workspace_root, // project_root
    ) {
        Ok(()) => {
            println!("📋 Documentation generation completed successfully");
        }
        Err(e) => {
            eprintln!("⚠️  Documentation generation error: {}", e);
            eprintln!("🔍 Debug info:");
            eprintln!("   - Content root: {}", content_root);
            eprintln!("   - Info path: {}", info_path);
            eprintln!("   - Templates path: {}", templates_path);
            eprintln!("   - Workspace root: {}", workspace_root);

            // Check if directories exist
            if !std::path::Path::new(&templates_path).exists() {
                eprintln!("❌ Templates directory does not exist: {}", templates_path);
            }
            if !std::path::Path::new(&content_root).exists() {
                eprintln!("❌ Content directory does not exist: {}", content_root);
            }

            return Err(e);
        }
    }

    println!("✅ Site information and shared resources generated successfully");
    Ok(())
}
