//! Internationalization support for documentation templates

use std::collections::HashMap;
use std::env;
use std::path::Path;

use super::I18nContext;

/// Language configuration and metadata
#[derive(Debug, Clone)]
pub struct LanguageConfig {
    pub code: String,
    pub name: String,
    pub direction: String,
    pub date_format: String,
    pub available_templates: Vec<String>,
}

/// I18n manager for template system
pub struct I18nManager {
    /// Supported languages
    languages: HashMap<String, LanguageConfig>,
    /// Default language
    default_language: String,
    /// Template metadata
    _template_metadata: HashMap<String, TemplateMetadata>,
}

#[derive(Debug, Clone)]
pub struct TemplateMetadata {
    pub name: String,
    pub description: String,
    pub template_type: String,
    pub required_context: Vec<String>,
}

impl Default for I18nManager {
    fn default() -> Self {
        Self::new()
    }
}

impl I18nManager {
    /// Create new i18n manager with FTL integration
    pub fn new() -> Self {
        let mut languages = HashMap::new();

        // Load configuration from build-tools.toml or use defaults
        let _config = load_build_tools_config().unwrap_or_default();

        // English (default)
        languages.insert(
            "en".to_string(),
            LanguageConfig {
                code: "en".to_string(),
                name: "English".to_string(),
                direction: "ltr".to_string(),
                date_format: "%Y-%m-%d %H:%M:%S UTC".to_string(),
                available_templates: vec![
                    "summary".to_string(),
                    "reference".to_string(),
                    "automation".to_string(),
                    "top_level".to_string(),
                ],
            },
        );

        // Spanish
        languages.insert(
            "es".to_string(),
            LanguageConfig {
                code: "es".to_string(),
                name: "Español".to_string(),
                direction: "ltr".to_string(),
                date_format: "%d-%m-%Y %H:%M:%S UTC".to_string(),
                available_templates: vec![
                    "summary".to_string(),
                    "reference".to_string(),
                    "automation".to_string(),
                    "top_level".to_string(),
                ],
            },
        );

        let mut template_metadata = HashMap::new();
        template_metadata.insert(
            "summary".to_string(),
            TemplateMetadata {
                name: "summary".to_string(),
                description: "Summary page with metrics and navigation".to_string(),
                template_type: "page".to_string(),
                required_context: vec!["summary".to_string(), "metadata".to_string()],
            },
        );

        template_metadata.insert(
            "reference".to_string(),
            TemplateMetadata {
                name: "reference".to_string(),
                description: "Detailed reference documentation".to_string(),
                template_type: "page".to_string(),
                required_context: vec![
                    "routes".to_string(),
                    "components".to_string(),
                    "pages".to_string(),
                ],
            },
        );

        Self {
            languages,
            default_language: "en".to_string(),
            _template_metadata: template_metadata,
        }
    }

    /// Get language configuration
    pub fn get_language(&self, code: &str) -> Option<&LanguageConfig> {
        self.languages.get(code)
    }

    /// Get default language
    pub fn default_language(&self) -> &LanguageConfig {
        self.languages.get(&self.default_language).unwrap()
    }

    /// Get supported languages
    pub fn supported_languages(&self) -> Vec<&str> {
        self.languages.keys().map(|s| s.as_str()).collect()
    }

    /// Check if template is available for language
    pub fn has_template(&self, template: &str, language: &str) -> bool {
        self.languages
            .get(language)
            .map(|lang| lang.available_templates.contains(&template.to_string()))
            .unwrap_or(false)
    }

    /// Get template path for language with fallback
    pub fn resolve_template_path(&self, template: &str, language: &str) -> String {
        if self.has_template(template, language) {
            format!("{}/{}.tera", language, template)
        } else {
            // Fallback to default language
            format!("{}/{}.tera", self.default_language, template)
        }
    }

    /// Create i18n context for language
    pub fn create_context(&self, language: &str) -> I18nContext {
        let lang_config = self
            .get_language(language)
            .unwrap_or_else(|| self.default_language());

        I18nContext {
            language: lang_config.code.clone(),
            direction: lang_config.direction.clone(),
            date_format: lang_config.date_format.clone(),
            labels: self.get_labels(&lang_config.code),
        }
    }

    /// Get localized labels for language using FTL files
    fn get_labels(&self, language: &str) -> HashMap<String, String> {
        if let Ok(labels) = load_ftl_labels(language) {
            labels
        } else {
            // Fallback to hardcoded labels
            match language {
                "es" => spanish_labels(),
                _ => english_labels(),
            }
        }
    }
}

/// Configuration structure for build-tools system
#[derive(Debug, Clone)]
pub struct BuildToolsConfig {
    pub default_language: String,
    pub supported_languages: Vec<String>,
    pub ftl_base_path: String,
}

/// Load build-tools configuration from config/build-tools.toml
fn load_build_tools_config() -> Result<BuildToolsConfig, Box<dyn std::error::Error>> {
    let config_path = env::var("SITE_CONFIG_PATH").unwrap_or_else(|_| "config".to_string());

    let config_file = Path::new(&config_path).join("build-tools.toml");

    if config_file.exists() {
        let content = std::fs::read_to_string(&config_file)?;
        let toml_value: toml::Value = toml::from_str(&content)?;

        let default_language = toml_value
            .get("i18n")
            .and_then(|i18n| i18n.get("default_language"))
            .and_then(|v| v.as_str())
            .unwrap_or("en")
            .to_string();

        let supported_languages = toml_value
            .get("i18n")
            .and_then(|i18n| i18n.get("supported_languages"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_else(|| vec!["en".to_string(), "es".to_string()]);

        let ftl_base_path = toml_value
            .get("i18n")
            .and_then(|i18n| i18n.get("ftl_base_path"))
            .and_then(|v| v.as_str())
            .unwrap_or("build-tools")
            .to_string();

        Ok(BuildToolsConfig {
            default_language,
            supported_languages,
            ftl_base_path,
        })
    } else {
        Ok(BuildToolsConfig::default())
    }
}

impl Default for BuildToolsConfig {
    fn default() -> Self {
        Self {
            default_language: "en".to_string(),
            supported_languages: vec!["en".to_string(), "es".to_string()],
            ftl_base_path: "build-tools".to_string(),
        }
    }
}

/// Load labels from FTL files
fn load_ftl_labels(language: &str) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
    let i18n_path = env::var("SITE_I18N_PATH")
        .or_else(|_| env::var("SITE_FTL_PATH"))
        .unwrap_or_else(|_| "site/i18n".to_string());

    let config = load_build_tools_config().unwrap_or_default();
    let ftl_file_path = Path::new(&i18n_path)
        .join("i18n")
        .join(&config.ftl_base_path)
        .join(language)
        .join("templates.ftl");

    if ftl_file_path.exists() {
        let content = std::fs::read_to_string(&ftl_file_path)?;
        Ok(parse_ftl_content(&content))
    } else {
        Err(format!("FTL file not found: {}", ftl_file_path.display()).into())
    }
}

/// Simple FTL parser to extract key-value pairs
fn parse_ftl_content(content: &str) -> HashMap<String, String> {
    let mut labels = HashMap::new();

    for line in content.lines() {
        let line = line.trim();

        // Skip comments and empty lines
        if line.starts_with('#') || line.is_empty() {
            continue;
        }

        // Parse key = value lines
        if let Some((key, value)) = line.split_once(" = ") {
            let key = key.trim().to_string();
            let value = value.trim().trim_matches('"').to_string();
            labels.insert(key, value);
        }
    }

    labels
}

/// English labels for templates
pub fn english_labels() -> HashMap<String, String> {
    let mut labels = HashMap::new();

    // Page titles
    labels.insert(
        "title_server_summary".to_string(),
        "Server Routes Summary".to_string(),
    );
    labels.insert(
        "title_server_reference".to_string(),
        "Server API Routes Reference".to_string(),
    );
    labels.insert(
        "title_components_summary".to_string(),
        "Components Summary".to_string(),
    );
    labels.insert(
        "title_components_reference".to_string(),
        "Components Reference".to_string(),
    );
    labels.insert(
        "title_pages_summary".to_string(),
        "Pages Summary".to_string(),
    );
    labels.insert(
        "title_pages_reference".to_string(),
        "Pages Reference".to_string(),
    );
    labels.insert(
        "title_automation".to_string(),
        "Automation Guide".to_string(),
    );
    labels.insert(
        "title_top_level".to_string(),
        "Documentation Overview".to_string(),
    );

    // Common labels
    labels.insert("generated_at".to_string(), "Generated at".to_string());
    labels.insert("summary".to_string(), "Summary".to_string());
    labels.insert(
        "table_of_contents".to_string(),
        "Table of Contents".to_string(),
    );
    labels.insert("overview".to_string(), "Overview".to_string());
    labels.insert("details".to_string(), "Details".to_string());

    // Technical terms
    labels.insert("routes".to_string(), "Routes".to_string());
    labels.insert("components".to_string(), "Components".to_string());
    labels.insert("pages".to_string(), "Pages".to_string());
    labels.insert("source".to_string(), "source".to_string());
    labels.insert("line".to_string(), "line".to_string());
    labels.insert("context".to_string(), "context".to_string());
    labels.insert("methods".to_string(), "Methods".to_string());
    labels.insert("handler".to_string(), "Handler".to_string());
    labels.insert("module".to_string(), "Module".to_string());
    labels.insert("parameters".to_string(), "Parameters".to_string());
    labels.insert("response_type".to_string(), "Response Type".to_string());
    labels.insert("requires_auth".to_string(), "Requires Auth".to_string());
    labels.insert("middleware".to_string(), "Middleware".to_string());
    labels.insert("description".to_string(), "Description".to_string());
    labels.insert("enabled".to_string(), "Enabled".to_string());
    labels.insert("priority".to_string(), "Priority".to_string());
    labels.insert("language".to_string(), "Language".to_string());
    labels.insert("keywords".to_string(), "Keywords".to_string());

    // Statistics
    labels.insert("total_routes".to_string(), "Total Routes".to_string());
    labels.insert(
        "total_components".to_string(),
        "Total Components".to_string(),
    );
    labels.insert("total_pages".to_string(), "Total Pages".to_string());
    labels.insert("auth_required".to_string(), "Auth Required".to_string());
    labels.insert("static_routes".to_string(), "Static Routes".to_string());
    labels.insert("api_routes".to_string(), "API Routes".to_string());
    labels.insert("languages".to_string(), "Languages".to_string());

    // Navigation
    labels.insert("back_to_top".to_string(), "Back to Top".to_string());
    labels.insert("view_source".to_string(), "View Source".to_string());
    labels.insert("external_link".to_string(), "External Link".to_string());

    labels
}

/// Spanish labels for templates
pub fn spanish_labels() -> HashMap<String, String> {
    let mut labels = HashMap::new();

    // Page titles
    labels.insert(
        "title_server_summary".to_string(),
        "Resumen de Rutas del Servidor".to_string(),
    );
    labels.insert(
        "title_server_reference".to_string(),
        "Referencia de API del Servidor".to_string(),
    );
    labels.insert(
        "title_components_summary".to_string(),
        "Resumen de Componentes".to_string(),
    );
    labels.insert(
        "title_components_reference".to_string(),
        "Referencia de Componentes".to_string(),
    );
    labels.insert(
        "title_pages_summary".to_string(),
        "Resumen de Páginas".to_string(),
    );
    labels.insert(
        "title_pages_reference".to_string(),
        "Referencia de Páginas".to_string(),
    );
    labels.insert(
        "title_automation".to_string(),
        "Guía de Automatización".to_string(),
    );
    labels.insert(
        "title_top_level".to_string(),
        "Vista General de Documentación".to_string(),
    );

    // Common labels
    labels.insert("generated_at".to_string(), "Generado el".to_string());
    labels.insert("summary".to_string(), "Resumen".to_string());
    labels.insert(
        "table_of_contents".to_string(),
        "Índice de Contenidos".to_string(),
    );
    labels.insert("overview".to_string(), "Vista General".to_string());
    labels.insert("details".to_string(), "Detalles".to_string());

    // Technical terms
    labels.insert("routes".to_string(), "Rutas".to_string());
    labels.insert("components".to_string(), "Componentes".to_string());
    labels.insert("pages".to_string(), "Páginas".to_string());
    labels.insert("source".to_string(), "fuente".to_string());
    labels.insert("line".to_string(), "línea".to_string());
    labels.insert("context".to_string(), "contexto".to_string());
    labels.insert("methods".to_string(), "Métodos".to_string());
    labels.insert("handler".to_string(), "Manejador".to_string());
    labels.insert("module".to_string(), "Módulo".to_string());
    labels.insert("parameters".to_string(), "Parámetros".to_string());
    labels.insert("response_type".to_string(), "Tipo de Respuesta".to_string());
    labels.insert(
        "requires_auth".to_string(),
        "Requiere Autenticación".to_string(),
    );
    labels.insert("middleware".to_string(), "Middleware".to_string());
    labels.insert("description".to_string(), "Descripción".to_string());
    labels.insert("enabled".to_string(), "Habilitado".to_string());
    labels.insert("priority".to_string(), "Prioridad".to_string());
    labels.insert("language".to_string(), "Idioma".to_string());
    labels.insert("keywords".to_string(), "Palabras Clave".to_string());

    // Statistics
    labels.insert("total_routes".to_string(), "Total de Rutas".to_string());
    labels.insert(
        "total_components".to_string(),
        "Total de Componentes".to_string(),
    );
    labels.insert("total_pages".to_string(), "Total de Páginas".to_string());
    labels.insert(
        "auth_required".to_string(),
        "Autenticación Requerida".to_string(),
    );
    labels.insert("static_routes".to_string(), "Rutas Estáticas".to_string());
    labels.insert("api_routes".to_string(), "Rutas de API".to_string());
    labels.insert("languages".to_string(), "Idiomas".to_string());

    // Navigation
    labels.insert("back_to_top".to_string(), "Volver Arriba".to_string());
    labels.insert("view_source".to_string(), "Ver Código Fuente".to_string());
    labels.insert("external_link".to_string(), "Enlace Externo".to_string());

    labels
}
