//! Page generation logic using shared crate infrastructure

use std::path::PathBuf;

use anyhow::{Context, Result};
use chrono::Utc;
use rustelo_core_types::i18n::{discover_available_languages, get_default_language};
use rustelo_core_types::ContentConfig;

use crate::manager::config::RouteConfig;
use crate::manager::{PageConfig, PageTemplate};

/// Core page generator that integrates with Rustelo's infrastructure
pub struct PageGenerator {
    /// Project root path
    project_root: PathBuf,
    /// Content configuration from shared crate
    content_config: ContentConfig,
    /// Available languages discovered from locales
    available_languages: Vec<String>,
}

impl PageGenerator {
    /// Create a new page generator
    pub fn new(project_root: PathBuf) -> Result<Self> {
        let content_config = ContentConfig::from_env();
        let discovered_languages = discover_available_languages();
        let available_languages = if discovered_languages.is_empty() {
            vec![get_default_language()]
        } else {
            discovered_languages
                .iter()
                .map(|lang| lang.code.clone())
                .collect()
        };

        Ok(Self {
            project_root,
            content_config,
            available_languages,
        })
    }

    /// Get available languages
    pub fn available_languages(&self) -> &[String] {
        &self.available_languages
    }

    /// Get routes directory path using environment config
    pub fn get_routes_dir(&self) -> PathBuf {
        let routes_path =
            std::env::var("CONTENT_ROUTES_PATH").unwrap_or_else(|_| "content/routes".to_string());
        self.project_root.join(routes_path)
    }

    /// Get pages source directory path using environment config
    pub fn get_pages_src_dir(&self) -> PathBuf {
        let pages_path =
            std::env::var("PAGES_SRC_PATH").unwrap_or_else(|_| "crates/pages/src".to_string());
        self.project_root.join(pages_path)
    }

    /// Get locales directory path using shared content config
    pub fn get_locales_dir(&self) -> PathBuf {
        self.content_config.locales_path.clone()
    }

    /// Check if a page already exists
    pub fn page_exists(&self, module_name: &str) -> bool {
        let page_dir = self.get_pages_src_dir().join(module_name);
        page_dir.exists() && page_dir.join("mod.rs").exists()
    }

    /// Check if a route file exists for the module
    pub fn route_file_exists(&self, module_name: &str) -> bool {
        crate::manager::config::route_file_exists(&self.project_root, module_name)
    }

    /// Generate a new route configuration file
    pub fn generate_route_file(&self, config: &PageConfig) -> Result<PathBuf> {
        let routes_dir = self.get_routes_dir();
        std::fs::create_dir_all(&routes_dir).with_context(|| {
            format!(
                "Failed to create routes directory: {}",
                routes_dir.display()
            )
        })?;

        let filename = crate::manager::config::generate_route_filename(
            &self.project_root,
            &config.module_name,
        );
        let route_file_path = routes_dir.join(&filename);

        let route_config = RouteConfig::from_page_config(config);
        route_config
            .save_to_file(&route_file_path)
            .with_context(|| format!("Failed to save route file: {}", route_file_path.display()))?;

        Ok(route_file_path)
    }

    /// Generate page scaffolding files if auto_scaffold is enabled
    pub fn generate_page_files(&self, config: &PageConfig) -> Result<Vec<PathBuf>> {
        if !config.auto_scaffold {
            return Ok(vec![]);
        }

        let mut generated_files = vec![];

        // Create page directory
        let page_dir = self.get_pages_src_dir().join(&config.module_name);
        std::fs::create_dir_all(&page_dir)
            .with_context(|| format!("Failed to create page directory: {}", page_dir.display()))?;

        // Generate mod.rs
        let mod_file = page_dir.join("mod.rs");
        let mod_content = self.generate_mod_rs(config)?;
        std::fs::write(&mod_file, mod_content)
            .with_context(|| format!("Failed to write mod.rs: {}", mod_file.display()))?;
        generated_files.push(mod_file);

        // Generate unified.rs
        let unified_file = page_dir.join("unified.rs");
        let unified_content = self.generate_unified_rs(config)?;
        std::fs::write(&unified_file, unified_content)
            .with_context(|| format!("Failed to write unified.rs: {}", unified_file.display()))?;
        generated_files.push(unified_file);

        // Generate FTL files for selected languages
        let ftl_files = self.generate_ftl_files(config)?;
        generated_files.extend(ftl_files);

        Ok(generated_files)
    }

    /// Generate FTL translation files using shared config
    fn generate_ftl_files(&self, config: &PageConfig) -> Result<Vec<PathBuf>> {
        let mut generated_files = vec![];
        let locales_dir = self.get_locales_dir();

        // Create manager subdirectory for our FTL files at
        // content/locales/{lang}/manager/
        for lang in &config.languages {
            let lang_dir = locales_dir.join(lang).join("manager");
            std::fs::create_dir_all(&lang_dir).with_context(|| {
                format!("Failed to create FTL directory: {}", lang_dir.display())
            })?;

            let ftl_file = lang_dir.join(format!("{}.ftl", config.module_name));
            let ftl_content = self.generate_ftl_content(config, lang)?;

            std::fs::write(&ftl_file, ftl_content)
                .with_context(|| format!("Failed to write FTL file: {}", ftl_file.display()))?;

            generated_files.push(ftl_file);
        }

        Ok(generated_files)
    }

    /// Generate mod.rs content
    fn generate_mod_rs(&self, config: &PageConfig) -> Result<String> {
        let patterns_str = config
            .i18n_patterns
            .iter()
            .map(|p| format!("\"{}\"", p))
            .collect::<Vec<_>>()
            .join(", ");

        let content = format!(
            r#"//! Auto-generated scaffold for {} page
//! Generated at: {} by manager
//! Template: {}
//! TODO: Customize this implementation as needed


pub mod unified;
pub use unified::*;

// TODO: Generate page implementation for {}
// Patterns: {}
"#,
            config.name,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            config.template.as_str(),
            config.name,
            patterns_str
        );

        Ok(content)
    }

    /// Generate unified.rs content
    fn generate_unified_rs(&self, config: &PageConfig) -> Result<String> {
        let primary_pattern = config
            .i18n_patterns
            .first()
            .map(|p| p.trim_end_matches('-'))
            .unwrap_or(&config.module_name);

        let view_content = match config.template {
            PageTemplate::HeroPage => self.generate_hero_template(primary_pattern),
            PageTemplate::FormPage => self.generate_form_template(primary_pattern),
            PageTemplate::ContentList => self.generate_content_list_template(primary_pattern),
            PageTemplate::BasicPage => self.generate_basic_template(primary_pattern),
        };

        let content = format!(
            r#"//! Auto-generated scaffold for {} page
//! Generated at: {} by manager
//! Template: {}
//! TODO: Replace this implementation with your actual page logic

use leptos::prelude::*;
use rustelo_core_types::i18n::create_content_provider;

#[component]
pub fn Unified{}Page(
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
) -> impl IntoView {{
    let content = create_content_provider(lang_content);

{}
}}
"#,
            config.name,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            config.template.as_str(),
            config.name,
            view_content
        );

        Ok(content)
    }

    /// Generate basic page template
    fn generate_basic_template(&self, prefix: &str) -> String {
        format!(
            r#"    view! {{
        <div class="ds-bg-page">
            <section class="relative py-ds-4 ds-container ds-rounded-lg ds-shadow-lg">
                <div class="mx-auto max-w-4xl text-center">
                    <h1 class="text-balance text-4xl font-bold tracking-tight ds-text sm:text-6xl mb-ds-4">
                        {{content.t("manager-{}-title")}}
                    </h1>
                    <rustelo_components_leptos::HtmlContent
                        content={{content.t("manager-{}-description")}}
                        class="mt-ds-6 ds-body ds-text-secondary max-w-2xl mx-auto".to_string()
                    />
                </div>

                <div class="mt-8 p-4 border-2 border-dashed border-yellow-500 bg-yellow-50 dark:bg-yellow-900/20 rounded">
                    <p class="text-yellow-700 dark:text-yellow-400 text-center">
                        "⚠️ This is an auto-generated scaffold. Please implement your actual page content."
                    </p>
                </div>
            </section>
        </div>
    }}"#,
            prefix, prefix
        )
    }

    /// Generate hero page template
    fn generate_hero_template(&self, prefix: &str) -> String {
        format!(
            r#"    view! {{
        <div class="ds-bg-page">
            <section class="relative py-ds-4 ds-container ds-rounded-lg ds-shadow-lg">
                <div class="mx-auto max-w-4xl text-center">
                    <h1 class="text-balance text-4xl font-bold tracking-tight ds-text sm:text-6xl mb-ds-4">
                        {{content.t("manager-{}-hero-title")}}
                    </h1>
                    <rustelo_components_leptos::HtmlContent
                        content={{content.t("manager-{}-hero-subtitle")}}
                        class="mt-ds-6 ds-body ds-text-secondary max-w-2xl mx-auto".to_string()
                    />

                    <div class="flex flex-col sm:flex-row gap-4 justify-center mt-8">
                        <a href={{content.t("manager-{}-cta-primary-url")}} class="no-underline ds-btn-primary">
                            {{content.t("manager-{}-cta-primary-text")}}
                        </a>
                        <a href={{content.t("manager-{}-cta-secondary-url")}} class="no-underline ds-btn-secondary">
                            {{content.t("manager-{}-cta-secondary-text")}}
                        </a>
                    </div>
                </div>

                <div class="mt-8 p-4 border-2 border-dashed border-blue-500 bg-blue-50 dark:bg-blue-900/20 rounded">
                    <p class="text-blue-700 dark:text-blue-400 text-center">
                        "🦸 This is a hero page scaffold. Customize the CTAs and content above."
                    </p>
                </div>
            </section>
        </div>
    }}"#,
            prefix, prefix, prefix, prefix, prefix, prefix
        )
    }

    /// Generate form page template
    fn generate_form_template(&self, prefix: &str) -> String {
        format!(
            r#"    view! {{
        <div class="ds-bg-page">
            <section class="relative py-ds-4 ds-container ds-rounded-lg ds-shadow-lg">
                <div class="mx-auto max-w-2xl">
                    <h1 class="text-balance text-4xl font-bold tracking-tight ds-text text-center mb-ds-4">
                        {{content.t("manager-{}-form-title")}}
                    </h1>
                    <rustelo_components_leptos::HtmlContent
                        content={{content.t("manager-{}-form-description")}}
                        class="mt-ds-6 ds-body ds-text-secondary text-center mb-8".to_string()
                    />

                    <form class="space-y-6">
                        <div>
                            <label class="block ds-body font-medium ds-text mb-2">
                                {{content.t("manager-{}-field-name")}}
                            </label>
                            <input type="text" class="ds-input w-full" placeholder={{content.t("manager-{}-field-name-placeholder")}} />
                        </div>

                        <div>
                            <label class="block ds-body font-medium ds-text mb-2">
                                {{content.t("manager-{}-field-email")}}
                            </label>
                            <input type="email" class="ds-input w-full" placeholder={{content.t("manager-{}-field-email-placeholder")}} />
                        </div>

                        <div>
                            <label class="block ds-body font-medium ds-text mb-2">
                                {{content.t("manager-{}-field-message")}}
                            </label>
                            <textarea class="ds-input w-full h-32" placeholder={{content.t("manager-{}-field-message-placeholder")}}></textarea>
                        </div>

                        <button type="submit" class="ds-btn-primary w-full">
                            {{content.t("manager-{}-submit-button")}}
                        </button>
                    </form>
                </div>

                <div class="mt-8 p-4 border-2 border-dashed border-green-500 bg-green-50 dark:bg-green-900/20 rounded max-w-2xl mx-auto">
                    <p class="text-green-700 dark:text-green-400 text-center">
                        "📝 This is a form page scaffold. Add your form handling logic."
                    </p>
                </div>
            </section>
        </div>
    }}"#,
            prefix, prefix, prefix, prefix, prefix, prefix, prefix, prefix, prefix
        )
    }

    /// Generate content list template
    fn generate_content_list_template(&self, prefix: &str) -> String {
        let template = format!(
            "    view! {{
        <div class=\"ds-bg-page\">
            <section class=\"relative py-ds-4 ds-container ds-rounded-lg ds-shadow-lg\">
                <div class=\"mx-auto max-w-6xl\">
                    <h1 class=\"text-balance text-4xl font-bold tracking-tight ds-text text-center \
             mb-ds-4\">
                        {{{{content.t(\"manager-{}-list-title\")}}}}
                    </h1>
                    <rustelo_components_leptos::HtmlContent
                        content={{{{content.t(\"manager-{}-list-description\")}}}}
                        class=\"mt-ds-6 ds-body ds-text-secondary text-center mb-12\".to_string()
                    />

                    // Filter section
                    <div class=\"mb-8 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg\">
                        <div class=\"flex flex-col sm:flex-row gap-4 items-center\">
                            <input
                                type=\"text\"
                                class=\"ds-input flex-1\"
                                placeholder={{{{content.t(\"manager-{}-search-placeholder\")}}}}
                            />
                            <select class=\"ds-input min-w-32\">
                                <option>{{{{content.t(\"manager-{}-filter-all\")}}}}</option>
                                <option>{{{{content.t(\"manager-{}-filter-featured\")}}}}</option>
                            </select>
                        </div>
                    </div>

                    // Content grid
                    <div class=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6\">
                        // Sample cards - replace with dynamic content
                        <div class=\"ds-card p-6\">
                            <h3 class=\"ds-heading-3 \
             mb-4\">{{{{content.t(\"manager-{}-sample-title-1\")}}}}</h3>
                            <p class=\"ds-body ds-text-secondary \
             mb-4\">{{{{content.t(\"manager-{}-sample-description-1\")}}}}</p>
                            <a href=\"#\" \
             class=\"ds-btn-secondary\">{{{{content.t(\"manager-{}-read-more\")}}}}</a>
                        </div>

                        <div class=\"ds-card p-6\">
                            <h3 class=\"ds-heading-3 \
             mb-4\">{{{{content.t(\"manager-{}-sample-title-2\")}}}}</h3>
                            <p class=\"ds-body ds-text-secondary \
             mb-4\">{{{{content.t(\"manager-{}-sample-description-2\")}}}}</p>
                            <a href=\"#\" \
             class=\"ds-btn-secondary\">{{{{content.t(\"manager-{}-read-more\")}}}}</a>
                        </div>

                        <div class=\"ds-card p-6\">
                            <h3 class=\"ds-heading-3 \
             mb-4\">{{{{content.t(\"manager-{}-sample-title-3\")}}}}</h3>
                            <p class=\"ds-body ds-text-secondary \
             mb-4\">{{{{content.t(\"manager-{}-sample-description-3\")}}}}</p>
                            <a href=\"#\" \
             class=\"ds-btn-secondary\">{{{{content.t(\"manager-{}-read-more\")}}}}</a>
                        </div>
                    </div>
                </div>

                <div class=\"mt-8 p-4 border-2 border-dashed border-purple-500 bg-purple-50 \
             dark:bg-purple-900/20 rounded max-w-6xl mx-auto\">
                    <p class=\"text-purple-700 dark:text-purple-400 text-center\">
                        \"This is a content list scaffold. Replace sample cards with dynamic \
             content loading.\"
                    </p>
                </div>
            </section>
        </div>
    }}",
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix,
            prefix
        );
        template
    }

    /// Generate FTL translation content
    fn generate_ftl_content(&self, config: &PageConfig, lang: &str) -> Result<String> {
        let prefix = config
            .i18n_patterns
            .first()
            .map(|p| p.trim_end_matches('-'))
            .unwrap_or(&config.module_name);

        let content = match config.template {
            PageTemplate::BasicPage => self.generate_basic_ftl(prefix, lang),
            PageTemplate::HeroPage => self.generate_hero_ftl(prefix, lang),
            PageTemplate::FormPage => self.generate_form_ftl(prefix, lang),
            PageTemplate::ContentList => self.generate_content_list_ftl(prefix, lang),
        };

        Ok(content)
    }

    /// Get localized template content based on language (language-agnostic)
    fn get_localized_templates(&self, lang: &str, template_type: &str) -> (String, String) {
        // Use environment variables or configuration files for translations
        // Fallback to English if no translation is available
        match template_type {
            "basic" => {
                let title_key = format!("PAGE_GEN_BASIC_TITLE_{}", lang.to_uppercase());
                let desc_key = format!("PAGE_GEN_BASIC_DESC_{}", lang.to_uppercase());

                let title = std::env::var(&title_key).unwrap_or_else(|_| match lang {
                    "es" => "Título de Página".to_string(),
                    "fr" => "Titre de Page".to_string(),
                    "de" => "Seitentitel".to_string(),
                    "it" => "Titolo Pagina".to_string(),
                    "pt" => "Título da Página".to_string(),
                    _ => "Page Title".to_string(),
                });

                let description = std::env::var(&desc_key).unwrap_or_else(|_| match lang {
                    "es" => "Descripción de la página generada automáticamente.".to_string(),
                    "fr" => "Description de page générée automatiquement.".to_string(),
                    "de" => "Automatisch generierte Seitenbeschreibung.".to_string(),
                    "it" => "Descrizione pagina generata automaticamente.".to_string(),
                    "pt" => "Descrição da página gerada automaticamente.".to_string(),
                    _ => "Auto-generated page description.".to_string(),
                });

                (title, description)
            }
            _ => (
                "Page Title".to_string(),
                "Auto-generated page description.".to_string(),
            ),
        }
    }

    fn generate_basic_ftl(&self, prefix: &str, lang: &str) -> String {
        // Language-agnostic approach: use generic templates with placeholders
        let (title, description) = self.get_localized_templates(lang, "basic");

        format!(
            "# Auto-generated FTL file for {} ({})
# Generated at: {} by manager
# TODO: Customize these translations

manager-{}-title = {}
manager-{}-description = {}
",
            prefix,
            lang,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            prefix,
            title,
            prefix,
            description,
        )
    }

    fn generate_hero_ftl(&self, prefix: &str, lang: &str) -> String {
        // Use generic approach - users will customize these translations
        let default_suffix = match lang {
            "es" => " (ES)",
            "fr" => " (FR)",
            "de" => " (DE)",
            "it" => " (IT)",
            "pt" => " (PT)",
            _ => "",
        };

        format!(
            "# Auto-generated FTL file for {} ({})
# Generated at: {} by manager
# TODO: Customize these translations for your language

manager-{}-hero-title = Hero Title{}
manager-{}-hero-subtitle = Descriptive subtitle for the hero page{}
manager-{}-cta-primary-text = Primary Action{}
manager-{}-cta-primary-url = #
manager-{}-cta-secondary-text = Secondary Action{}
manager-{}-cta-secondary-url = #
",
            prefix,
            lang,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            prefix,
            default_suffix,
            prefix,
        )
    }

    fn generate_form_ftl(&self, prefix: &str, lang: &str) -> String {
        // Use generic approach - users will customize these translations
        let default_suffix = match lang {
            "es" => " (ES)",
            "fr" => " (FR)",
            "de" => " (DE)",
            "it" => " (IT)",
            "pt" => " (PT)",
            _ => "",
        };

        format!(
            "# Auto-generated FTL file for {} ({})
# Generated at: {} by manager
# TODO: Customize these translations for your language

manager-{}-form-title = Contact Form{}
manager-{}-form-description = Fill out this form to contact us{}
manager-{}-field-name = Name{}
manager-{}-field-name-placeholder = Your full name
manager-{}-field-email = Email{}
manager-{}-field-email-placeholder = your.email@example.com
manager-{}-field-message = Message{}
manager-{}-field-message-placeholder = Write your message here...
manager-{}-submit-button = Submit Form{}
",
            prefix,
            lang,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            prefix,
            default_suffix,
            prefix,
            prefix,
            default_suffix,
            prefix,
            prefix,
            default_suffix,
        )
    }

    fn generate_content_list_ftl(&self, prefix: &str, lang: &str) -> String {
        // Use generic approach - users will customize these translations
        let default_suffix = match lang {
            "es" => " (ES)",
            "fr" => " (FR)",
            "de" => " (DE)",
            "it" => " (IT)",
            "pt" => " (PT)",
            _ => "",
        };

        format!(
            "# Auto-generated FTL file for {} ({})
# Generated at: {} by manager
# TODO: Customize these translations for your language

manager-{}-list-title = Content List{}
manager-{}-list-description = Explore our articles and resources{}
manager-{}-search-placeholder = Search content...
manager-{}-filter-all = All{}
manager-{}-filter-featured = Featured{}
manager-{}-sample-title-1 = Sample Title 1{}
manager-{}-sample-description-1 = Description of the first sample article{}
manager-{}-sample-title-2 = Sample Title 2{}
manager-{}-sample-description-2 = Description of the second sample article{}
manager-{}-sample-title-3 = Sample Title 3{}
manager-{}-sample-description-3 = Description of the third sample article{}
manager-{}-read-more = Read more{}
",
            prefix,
            lang,
            Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
            prefix,
            default_suffix,
        )
    }

    /// Update pages/src/lib.rs exports
    pub fn update_lib_exports(&self, config: &PageConfig) -> Result<()> {
        let lib_file = self.get_pages_src_dir().join("lib.rs");

        if !lib_file.exists() {
            anyhow::bail!("Pages lib.rs not found at: {}", lib_file.display());
        }

        let content = std::fs::read_to_string(&lib_file)
            .with_context(|| format!("Failed to read lib.rs: {}", lib_file.display()))?;

        // Add module declaration if not present
        let module_line = format!("pub mod {};", config.module_name);
        let export_line = format!("pub use {}::*;", config.module_name);

        if !content.contains(&module_line) {
            let mut lines = content.lines().collect::<Vec<_>>();

            // Find a good place to insert the module - after other module declarations
            let mut insert_index = 0;
            for (i, line) in lines.iter().enumerate() {
                if line.starts_with("pub mod ") {
                    insert_index = i + 1;
                } else if line.starts_with("pub use ") && insert_index > 0 {
                    break;
                }
            }

            lines.insert(insert_index, &module_line);

            // Find where to insert the export
            let mut export_insert_index = lines.len();
            for (i, line) in lines.iter().enumerate() {
                if line.starts_with("pub use ") && !line.contains("::*") {
                    export_insert_index = i;
                    break;
                }
            }

            lines.insert(export_insert_index, &export_line);

            let new_content = lines.join("\n");
            std::fs::write(&lib_file, new_content)
                .with_context(|| format!("Failed to update lib.rs: {}", lib_file.display()))?;
        }

        Ok(())
    }

    /// Generate a complete page with all files
    pub fn generate_complete_page(&self, config: &PageConfig) -> Result<GenerationResult> {
        config
            .validate()
            .context("Page configuration validation failed")?;

        let mut generated_files = vec![];
        let mut warnings = vec![];

        // Check for existing files
        if self.page_exists(&config.module_name) {
            if !config.replace_existing {
                anyhow::bail!(
                    "Page module '{}' already exists. Use replace_existing=true to overwrite.",
                    config.module_name
                );
            } else {
                warnings.push(format!(
                    "Overwriting existing page module: {}",
                    config.module_name
                ));
            }
        }

        if self.route_file_exists(&config.module_name) && !config.replace_existing {
            warnings.push(format!(
                "Route configuration already exists for: {}",
                config.module_name
            ));
        }

        // Generate route file
        let route_file = self
            .generate_route_file(config)
            .context("Failed to generate route configuration")?;
        generated_files.push(route_file);

        // Generate page files if auto_scaffold is enabled
        let page_files = self
            .generate_page_files(config)
            .context("Failed to generate page files")?;
        generated_files.extend(page_files);

        // Update lib.rs exports if scaffolding was enabled
        if config.auto_scaffold {
            self.update_lib_exports(config)
                .context("Failed to update lib.rs exports")?;
        }

        Ok(GenerationResult {
            generated_files,
            warnings,
            config: config.clone(),
        })
    }
}

/// Result of page generation
#[derive(Debug)]
pub struct GenerationResult {
    /// List of generated files
    pub generated_files: Vec<PathBuf>,
    /// Any warnings during generation
    pub warnings: Vec<String>,
    /// The configuration used
    pub config: PageConfig,
}

impl GenerationResult {
    /// Get a summary of what was generated
    pub fn summary(&self) -> String {
        let mut summary = format!("✅ Generated page '{}':\n", self.config.name);

        for file in &self.generated_files {
            summary.push_str(&format!("  📄 {}\n", file.display()));
        }

        if !self.warnings.is_empty() {
            summary.push_str("\n⚠️  Warnings:\n");
            for warning in &self.warnings {
                summary.push_str(&format!("  • {}\n", warning));
            }
        }

        summary.push_str(&format!("\n🏗️  Template: {}", self.config.template));
        summary.push_str(&format!(
            "\n🌐 Languages: {}",
            self.config.languages.join(", ")
        ));
        summary.push_str(&format!("\n🔗 Route: {}", self.config.route_path));

        summary
    }
}
