//! TOML file handling and normalization utilities

use anyhow::{Context, Result};
use rustelo_core_lib::to_slug;
use std::fs;
use std::path::Path;

/// Normalize TOML file content if needed
pub fn normalize_toml_content(input_file: &str, original_content: &str) -> Result<bool> {
    // Check if this is a TOML file
    if !input_file.ends_with(".toml") {
        return Ok(false);
    }

    // Parse TOML content
    let mut toml_value: toml::Value =
        toml::from_str(original_content).context("Failed to parse TOML content")?;

    let mut changed = false;

    // Normalize categories_emojis section
    if let Some(categories_emojis) = toml_value.get_mut("categories_emojis") {
        if let Some(table) = categories_emojis.as_table_mut() {
            let mut new_table = toml::map::Map::new();

            for (key, value) in table.iter() {
                let normalized_key = to_slug(key);
                if normalized_key != *key {
                    println!(
                        "🔧 Normalized TOML category: '{}' -> '{}'",
                        key, normalized_key
                    );
                    changed = true;
                }
                new_table.insert(normalized_key, value.clone());
            }

            *table = new_table;
        }
    }

    // Normalize tags_emojis section
    if let Some(tags_emojis) = toml_value.get_mut("tags_emojis") {
        if let Some(table) = tags_emojis.as_table_mut() {
            let mut new_table = toml::map::Map::new();

            for (key, value) in table.iter() {
                let normalized_key = to_slug(key);
                if normalized_key != *key {
                    println!("🔧 Normalized TOML tag: '{}' -> '{}'", key, normalized_key);
                    changed = true;
                }
                new_table.insert(normalized_key, value.clone());
            }

            *table = new_table;
        }
    }

    // If changes were made, write the normalized content back
    if changed {
        let normalized_content =
            toml::to_string_pretty(&toml_value).context("Failed to serialize normalized TOML")?;

        fs::write(input_file, normalized_content)
            .context(format!("Failed to write normalized TOML to {}", input_file))?;

        println!("✅ Normalized TOML file: {}", input_file);
    }

    Ok(changed)
}

/// Generate meta.json file from TOML content for API access
pub fn generate_meta_json_from_toml(toml_path: &str, toml_value: &toml::Value) -> Result<()> {
    // Only process meta.toml files
    if !toml_path.contains("meta.toml") {
        return Ok(());
    }

    // Create MetaConfig structure
    let mut categories_emojis = std::collections::HashMap::new();
    let mut tags_emojis = std::collections::HashMap::new();

    // Extract categories_emojis
    if let Some(categories) = toml_value.get("categories_emojis") {
        if let Some(table) = categories.as_table() {
            for (key, value) in table {
                if let Some(emoji) = value.as_str() {
                    categories_emojis.insert(key.clone(), emoji.to_string());
                }
            }
        }
    }

    // Extract tags_emojis
    if let Some(tags) = toml_value.get("tags_emojis") {
        if let Some(table) = tags.as_table() {
            for (key, value) in table {
                if let Some(emoji) = value.as_str() {
                    tags_emojis.insert(key.clone(), emoji.to_string());
                }
            }
        }
    }

    // Create MetaConfig
    let meta_config = rustelo_core_lib::categories::MetaConfig {
        categories_emojis,
        tags_emojis,
    };

    // Determine output path - convert content/*/meta.toml to target/site/*/meta.json
    let json_path = if toml_path.starts_with("content/") {
        toml_path
            .replace("content/", "target/site/")
            .replace("meta.toml", "meta.json")
    } else {
        toml_path.replace("meta.toml", "meta.json")
    };

    // Create output directory if it doesn't exist
    if let Some(parent) = Path::new(&json_path).parent() {
        fs::create_dir_all(parent)
            .context(format!("Failed to create directory: {}", parent.display()))?;
    }

    // Write meta.json
    let json_content =
        serde_json::to_string_pretty(&meta_config).context("Failed to serialize MetaConfig")?;

    fs::write(&json_path, json_content)
        .context(format!("Failed to write meta.json to {}", json_path))?;

    println!("✅ Generated meta.json: {}", json_path);
    Ok(())
}
