//! Template-based page generation functionality

use super::types::RoutesConfig;
use crate::build::build_tasks::page_templates::{
    generate_page_from_template, load_templates, write_generated_page, TemplateContext,
    TemplateParams,
};
use std::collections::HashMap;
use std::path::Path;

/// Generate page implementations from templates for routes marked with auto_generate = true
pub fn generate_pages_from_templates(
    routes_config: &RoutesConfig,
    out_dir: &str,
) -> Result<(), String> {
    let templates = load_templates();
    let mut generated_count = 0;

    for route in &routes_config.routes {
        if route.enabled && route.auto_generate.unwrap_or(false) {
            if let Some(template_name) = &route.template {
                if let Some(template) = templates.get(template_name) {
                    // Check if page already exists (don't override custom implementations)
                    let default_page_component = format!("{}Page", route.component);
                    let page_component = route
                        .page_component
                        .as_ref()
                        .unwrap_or(&default_page_component);
                    let module_name = page_component
                        .strip_suffix("Page")
                        .unwrap_or(page_component)
                        .to_lowercase();

                    let existing_page_path = format!("crates/pages/src/{}/mod.rs", module_name);

                    if Path::new(&existing_page_path).exists() {
                        println!(
                            "cargo:warning=Skipping generation for {} - custom implementation exists at {}",
                            page_component, existing_page_path
                        );
                        continue;
                    }

                    // Extract i18n patterns from route configuration
                    let i18n_patterns =
                        route.i18n_patterns.as_ref().cloned().unwrap_or_else(|| {
                            // Default pattern based on component name
                            vec![format!("{}-", module_name)]
                        });

                    // Convert template_params from TOML values to TemplateParams
                    let template_params = convert_toml_to_template_params(&route.template_params);

                    // Create template context
                    let context =
                        TemplateContext::new(&route.component, &i18n_patterns, &template_params);

                    // Generate page from template
                    match generate_page_from_template(template, &context) {
                        Ok(generated_page) => {
                            match write_generated_page(&generated_page, out_dir) {
                                Ok(()) => {
                                    generated_count += 1;
                                    println!(
                                        "cargo:warning=Generated page: {} using template '{}'",
                                        page_component, template_name
                                    );
                                }
                                Err(e) => {
                                    eprintln!(
                                        "Warning: Failed to write generated page {}: {}",
                                        page_component, e
                                    );
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!(
                                "Warning: Failed to generate page {} from template '{}': {}",
                                page_component, template_name, e
                            );
                        }
                    }
                } else {
                    eprintln!(
                        "Warning: Template '{}' not found for route {} - skipping generation",
                        template_name, route.path
                    );
                }
            } else {
                eprintln!(
                    "Warning: Route {} marked for auto_generate but no template specified",
                    route.path
                );
            }
        }
    }

    if generated_count > 0 {
        println!(
            "cargo:warning=Successfully generated {} pages from templates",
            generated_count
        );
    }

    Ok(())
}

/// Convert TOML values to TemplateParams structure
fn convert_toml_to_template_params(
    toml_params: &Option<HashMap<String, toml::Value>>,
) -> TemplateParams {
    let mut params = TemplateParams::default();

    if let Some(toml_map) = toml_params {
        // Extract known template parameters
        if let Some(toml::Value::String(content_type)) = toml_map.get("default_content_type") {
            params.default_content_type = Some(content_type.clone());
        }

        if let Some(toml::Value::String(form_action)) = toml_map.get("form_action") {
            params.form_action = Some(form_action.clone());
        }

        if let Some(toml::Value::Boolean(has_sidebar)) = toml_map.get("has_sidebar") {
            params.has_sidebar = Some(*has_sidebar);
        }

        if let Some(toml::Value::Integer(max_items)) = toml_map.get("max_items") {
            params.max_items = Some(*max_items as u32);
        }

        if let Some(toml::Value::Boolean(show_pagination)) = toml_map.get("show_pagination") {
            params.show_pagination = Some(*show_pagination);
        }
    }

    params
}
