//! Metadata generation and emoji utilities for content

use std::fs;

#[cfg(feature = "content-static")]
use rustelo_server::content::file_loader::FrontMatter;

/// Get localized label using the shared fluent/i18n system
fn get_localized_label(key: &str, language: &str) -> String {
    // Use the shared unified i18n system following project best practices
    let i18n = rustelo_core_lib::i18n::unified::UnifiedI18n::new(language, "");
    i18n.t(key)
}

/// Get category emoji from TOML configuration
pub fn get_category_emoji_from_toml(content_type: &str, language: &str, category: &str) -> String {
    get_emoji_from_meta_toml(content_type, language, category, "categories_emojis")
}

/// Get tag emoji from TOML configuration
pub fn get_tag_emoji_from_toml(content_type: &str, language: &str, tag: &str) -> String {
    get_emoji_from_meta_toml(content_type, language, tag, "tags_emojis")
}

/// Get emoji from meta TOML file for a specific key and section
fn get_emoji_from_meta_toml(
    content_type: &str,
    language: &str,
    key: &str,
    section: &str,
) -> String {
    let content_root =
        std::env::var("SITE_SERVER_ROOT_CONTENT").unwrap_or_else(|_| "site/content".to_string());
    let meta_path = format!("{}/{}/{}/meta.toml", content_root, content_type, language);

    if let Ok(content) = fs::read_to_string(&meta_path) {
        if let Ok(toml_value) = toml::from_str::<toml::Value>(&content) {
            if let Some(section_value) = toml_value.get(section) {
                if let Some(table) = section_value.as_table() {
                    // Try exact match first
                    if let Some(emoji_value) = table.get(key) {
                        if let Some(emoji) = emoji_value.as_str() {
                            return emoji.to_string();
                        }
                    }

                    // Try slug-normalized match
                    let normalized_key = rustelo_core_lib::to_slug(key);
                    if let Some(emoji_value) = table.get(&normalized_key) {
                        if let Some(emoji) = emoji_value.as_str() {
                            return emoji.to_string();
                        }
                    }
                }
            }
        }
    }

    // Default emojis as fallback
    match section {
        "categories_emojis" => "📂",
        "tags_emojis" => "🏷️",
        _ => "📄",
    }
    .to_string()
}

/// Generate enhanced metadata HTML for content
#[cfg(feature = "content-static")]
pub fn generate_enhanced_metadata_html(
    frontmatter: &FrontMatter,
    content_type: &str,
    language: &str,
) -> String {
    let mut metadata_parts = Vec::new();

    // Author information
    if let Some(author) = &frontmatter.author {
        let author_label = get_localized_label("author", language);
        metadata_parts.push(format!("<strong>{}:</strong> {}", author_label, author));
    }

    // Publication date
    if let Some(date) = &frontmatter.date {
        let date_label = match language {
            "es" => "Fecha",
            _ => "Date",
        };
        metadata_parts.push(format!("<strong>{}:</strong> {}", date_label, date));
    }

    // Reading time
    if let Some(read_time) = &frontmatter.read_time {
        let time_label = match language {
            "es" => "Tiempo de lectura",
            _ => "Reading time",
        };
        metadata_parts.push(format!("<strong>{}:</strong> {}", time_label, read_time));
    }

    // Category with emoji and link
    if let Some(category) = &frontmatter.category {
        let emoji = get_category_emoji_from_toml(content_type, language, category);
        let category_label = match language {
            "es" => "Categoría",
            _ => "Category",
        };

        let category_link = format!(
            "{}/categories/{}",
            super::routing::get_localized_content_path(content_type, language),
            rustelo_core_lib::to_slug(category)
        );

        let category_html = format!(
            r#"<a href="{}" class="inline-flex items-center px-3 py-1 text-sm font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20 ds-rounded-full no-underline transition-colors cursor-pointer">{} {}</a>"#,
            category_link, emoji, category
        );

        metadata_parts.push(format!(
            "<strong>{}:</strong> {}",
            category_label, category_html
        ));
    }

    // Tags with emojis and links
    if let Some(tags) = &frontmatter.tags {
        if !tags.is_empty() {
            let tags_label = match language {
                "es" => "Etiquetas",
                _ => "Tags",
            };

            let tags_html: Vec<String> = tags
                .iter()
                .map(|tag| {
                    let emoji = get_tag_emoji_from_toml(content_type, language, tag);
                    let tag_link = format!(
                        "{}/tags/{}",
                        super::routing::get_localized_content_path(content_type, language),
                        rustelo_core_lib::to_slug(tag)
                    );

                    format!(
                        r#"<a href="{}" class="inline-flex items-center px-3 py-1 text-sm font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20 ds-rounded-full no-underline transition-colors cursor-pointer">{} {}</a>"#,
                        tag_link, emoji, tag
                    )
                })
                .collect();

            metadata_parts.push(format!(
                "<strong>{}:</strong> <div class=\"flex flex-wrap gap-2 mt-2\">{}</div>",
                tags_label,
                tags_html.join(" ")
            ));
        }
    }

    // Dynamic fields based on content type
    if let Some(difficulty) = &frontmatter.difficulty {
        let difficulty_label = match language {
            "es" => "Dificultad",
            _ => "Difficulty",
        };
        metadata_parts.push(format!(
            "<strong>{}:</strong> {}",
            difficulty_label, difficulty
        ));
    }

    if let Some(prep_time) = &frontmatter.prep_time {
        let prep_label = match language {
            "es" => "Tiempo de preparación",
            _ => "Prep time",
        };
        metadata_parts.push(format!("<strong>{}:</strong> {}", prep_label, prep_time));
    }

    if let Some(duration) = &frontmatter.duration {
        let duration_label = match language {
            "es" => "Duración",
            _ => "Duration",
        };
        metadata_parts.push(format!("<strong>{}:</strong> {}", duration_label, duration));
    }

    if let Some(prerequisites) = &frontmatter.prerequisites {
        if !prerequisites.is_empty() {
            let prereq_label = match language {
                "es" => "Prerrequisitos",
                _ => "Prerequisites",
            };
            let prereq_list = prerequisites.join(", ");
            metadata_parts.push(format!(
                "<strong>{}:</strong> {}",
                prereq_label, prereq_list
            ));
        }
    }

    if metadata_parts.is_empty() {
        return String::new();
    }

    format!(
        r#"<div class="enhanced-content-meta ds-bg ds-border ds-rounded-lg p-6 mb-6 ds-shadow-sm">
            {}
        </div>"#,
        metadata_parts.join("<br>")
    )
}

/// Insert metadata after the title in content
pub fn insert_metadata_after_title(content: &str, metadata_html: &str) -> String {
    if metadata_html.is_empty() {
        return content.to_string();
    }

    let lines: Vec<&str> = content.lines().collect();
    let mut result = Vec::new();
    let mut title_found = false;

    for line in lines {
        result.push(line.to_string());

        // Look for the first h1 tag and insert metadata after it
        if !title_found && (line.trim().starts_with("# ") || line.trim().starts_with("<h1")) {
            title_found = true;
            result.push(String::new()); // Add blank line
            result.push(metadata_html.to_string());
            result.push(String::new()); // Add blank line
        }
    }

    result.join("\n")
}
