use std::path::PathBuf;
use strum::IntoEnumIterator;
#[cfg(feature = "server")]
use utoipa::ToSchema;

use crate::compression_engine::{CompressionType, get_compression_engine};
use crate::meta_plugin::MetaPluginType;

use crate::filter_plugin::FilterOption;

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[cfg_attr(feature = "server", derive(ToSchema))]
pub struct FilterPluginInfo {
    pub name: String,
    pub options: Vec<FilterOption>,
    pub description: String,
}

#[derive(serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "server", derive(ToSchema))]
pub struct StatusInfo {
    pub paths: PathInfo,
    pub compression: Vec<CompressionInfo>,
    pub meta_plugins: std::collections::HashMap<String, MetaPluginInfo>,
    pub enabled_meta_plugins: Vec<String>,
    pub filter_plugins: Vec<FilterPluginInfo>,
    pub configured_meta_plugins: Option<Vec<crate::config::MetaPluginConfig>>,
}

impl Default for StatusInfo {
    fn default() -> Self {
        Self {
            paths: PathInfo {
                data: String::new(),
                database: String::new(),
            },
            compression: Vec::new(),
            meta_plugins: std::collections::HashMap::new(),
            enabled_meta_plugins: Vec::new(),
            filter_plugins: Vec::new(),
            configured_meta_plugins: None,
        }
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "server", derive(ToSchema))]
pub struct PathInfo {
    pub data: String,
    pub database: String,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[cfg_attr(feature = "server", derive(ToSchema))]
pub struct CompressionInfo {
    #[serde(rename = "type")]
    pub compression_type: String,
    pub found: bool,
    pub default: bool,
    pub binary: String,
    pub compress: String,
    pub decompress: String,
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[cfg_attr(feature = "server", derive(ToSchema))]
pub struct MetaPluginInfo {
    pub meta_name: String,
    pub outputs: std::collections::HashMap<String, serde_yaml::Value>,
    pub options: std::collections::HashMap<String, serde_yaml::Value>,
}

pub fn generate_status_info(
    data_path: PathBuf,
    db_path: PathBuf,
    enabled_meta_plugins: &[MetaPluginType],
    enabled_compression_type: Option<CompressionType>,
) -> anyhow::Result<StatusInfo> {
    log::debug!("STATUS: Starting status info generation");
    let path_info = PathInfo {
        data: data_path
            .into_os_string()
            .into_string()
            .map_err(|_| anyhow::anyhow!("Unable to convert data path to string"))?,
        database: db_path
            .into_os_string()
            .into_string()
            .map_err(|_| anyhow::anyhow!("Unable to convert DB path to string"))?,
    };

    let _default_type = crate::compression_engine::default_compression_type();
    let mut compression_info = Vec::new();

    // Sort compression types by their string representation
    let mut sorted_compression_types: Vec<CompressionType> = CompressionType::iter().collect();
    sorted_compression_types.sort_by_key(|ct| ct.to_string());

    for compression_type in sorted_compression_types {
        let (binary, compress, decompress, supported) =
            match get_compression_engine(compression_type.clone()) {
                Ok(engine) => {
                    let supp = engine.is_supported();
                    if supp && engine.is_internal() {
                        (
                            "<INTERNAL>".to_string(),
                            "".to_string(),
                            "".to_string(),
                            supp,
                        )
                    } else if supp {
                        let (b, c, d) = engine.get_status_info();
                        (b, c, d, supp)
                    } else {
                        (
                            "<UNSUPPORTED>".to_string(),
                            "".to_string(),
                            "".to_string(),
                            supp,
                        )
                    }
                }
                Err(_) => (
                    "<UNSUPPORTED>".to_string(),
                    "".to_string(),
                    "".to_string(),
                    false,
                ),
            };

        let is_enabled = enabled_compression_type
            .as_ref()
            .is_some_and(|ct| *ct == compression_type);

        compression_info.push(CompressionInfo {
            compression_type: compression_type.to_string(),
            found: supported,
            default: is_enabled,
            binary,
            compress,
            decompress,
        });
    }

    let mut meta_plugins_map = std::collections::HashMap::new();
    let mut enabled_meta_plugins_vec = Vec::new();

    // Sort meta plugin types by their string representation to avoid creating plugins just for sorting
    let mut sorted_meta_plugins: Vec<MetaPluginType> = MetaPluginType::iter().collect();
    sorted_meta_plugins.sort_by_key(|meta_plugin_type| meta_plugin_type.to_string());

    for meta_plugin_type in sorted_meta_plugins {
        log::debug!("STATUS: Processing meta plugin type: {meta_plugin_type:?}");
        let meta_plugin =
            match crate::meta_plugin::get_meta_plugin(meta_plugin_type.clone(), None, None) {
                Ok(p) => p,
                Err(e) => {
                    log::warn!(
                        "STATUS: Skipping unregistered meta plugin {meta_plugin_type:?}: {e}"
                    );
                    continue;
                }
            };

        // Get meta name first to avoid borrowing issues
        log::debug!("STATUS: Getting meta name...");
        let meta_name = meta_plugin.meta_type().to_string();
        log::debug!("STATUS: Got meta name: {meta_name}");

        // Check if this plugin is enabled
        let is_enabled = enabled_meta_plugins.contains(&meta_plugin_type);
        if is_enabled {
            enabled_meta_plugins_vec.push(meta_name.clone());
        }

        // Create a display of outputs for status - use configured outputs if available, otherwise defaults
        let outputs_display = if meta_plugin.outputs().is_empty() {
            // No configured outputs, use defaults
            let mut default_outputs = std::collections::HashMap::new();
            for output_name in meta_plugin.default_outputs() {
                default_outputs.insert(output_name.clone(), serde_yaml::Value::String(output_name));
            }
            default_outputs
        } else {
            // Use configured outputs
            meta_plugin.outputs().clone()
        };

        // Get options
        let options = meta_plugin.options().clone();

        meta_plugins_map.insert(
            meta_name.clone(),
            MetaPluginInfo {
                meta_name,
                outputs: outputs_display,
                options,
            },
        );
    }

    // Populate filter plugin info from the global registry
    let filter_plugins_map = crate::services::filter_service::get_available_filter_plugins()?;
    let filter_plugins_info: Vec<FilterPluginInfo> = filter_plugins_map
        .into_iter()
        .map(|(name, creator)| {
            let plugin = creator();
            FilterPluginInfo {
                name: name.clone(),
                options: plugin.options(),
                description: format!("{name} filter plugin"),
            }
        })
        .collect();

    Ok(StatusInfo {
        paths: path_info,
        compression: compression_info,
        meta_plugins: meta_plugins_map,
        enabled_meta_plugins: enabled_meta_plugins_vec,
        filter_plugins: filter_plugins_info,
        configured_meta_plugins: None,
    })
}
