use crate::meta_plugin::{BaseMetaPlugin, MetaPlugin, MetaPluginType};
use std::env;
use std::process;

#[derive(Debug, Clone, Default)]
pub struct ShellPidMetaPlugin {
    is_finalized: bool,
    base: BaseMetaPlugin,
}

impl ShellPidMetaPlugin {
    pub fn new(
        options: Option<std::collections::HashMap<String, serde_yaml::Value>>,
        outputs: Option<std::collections::HashMap<String, serde_yaml::Value>>,
    ) -> ShellPidMetaPlugin {
        let mut base = BaseMetaPlugin::new();

        // Set default outputs
        let default_outputs = &["shell_pid"];
        base.initialize_plugin(default_outputs, &options, &outputs);

        ShellPidMetaPlugin {
            is_finalized: false,
            base,
        }
    }
}

impl MetaPlugin for ShellPidMetaPlugin {
    fn is_finalized(&self) -> bool {
        self.is_finalized
    }

    fn set_finalized(&mut self, finalized: bool) {
        self.is_finalized = finalized;
    }

    fn set_save_meta(&mut self, save_meta: crate::meta_plugin::SaveMetaFn) {
        self.base.set_save_meta(save_meta);
    }

    fn save_meta(&self, name: &str, value: &str) {
        self.base.save_meta(name, value);
    }

    fn finalize(&mut self) -> crate::meta_plugin::MetaPluginResponse {
        // If already finalized, don't process again
        if self.is_finalized {
            return crate::meta_plugin::MetaPluginResponse {
                metadata: Vec::new(),
                is_finalized: true,
            };
        }

        // Mark as finalized
        self.is_finalized = true;

        crate::meta_plugin::MetaPluginResponse {
            metadata: Vec::new(),
            is_finalized: true,
        }
    }

    fn update(&mut self, _data: &[u8]) -> crate::meta_plugin::MetaPluginResponse {
        // If already finalized, don't process more data
        if self.is_finalized {
            return crate::meta_plugin::MetaPluginResponse {
                metadata: Vec::new(),
                is_finalized: true,
            };
        }

        crate::meta_plugin::MetaPluginResponse {
            metadata: Vec::new(),
            is_finalized: false,
        }
    }

    fn meta_type(&self) -> MetaPluginType {
        MetaPluginType::ShellPid
    }

    fn initialize(&mut self) -> crate::meta_plugin::MetaPluginResponse {
        // If already finalized, don't process again
        if self.is_finalized {
            return crate::meta_plugin::MetaPluginResponse {
                metadata: Vec::new(),
                is_finalized: true,
            };
        }

        let mut metadata = Vec::new();
        let pid = match env::var("PPID") {
            Ok(ppid) => ppid,
            Err(_) => process::id().to_string(),
        };

        // Use process_metadata_outputs to handle output mapping
        if let Some(meta_data) = crate::meta_plugin::process_metadata_outputs(
            "shell_pid",
            serde_yaml::Value::String(pid),
            self.base.outputs(),
        ) {
            metadata.push(meta_data);
        }

        // Mark as finalized since this plugin only needs to run once
        self.is_finalized = true;

        crate::meta_plugin::MetaPluginResponse {
            metadata,
            is_finalized: true,
        }
    }

    fn outputs(&self) -> &std::collections::HashMap<String, serde_yaml::Value> {
        self.base.outputs()
    }

    fn outputs_mut(
        &mut self,
    ) -> anyhow::Result<&mut std::collections::HashMap<String, serde_yaml::Value>> {
        Ok(self.base.outputs_mut())
    }

    fn options(&self) -> &std::collections::HashMap<String, serde_yaml::Value> {
        self.base.options()
    }

    fn options_mut(
        &mut self,
    ) -> anyhow::Result<&mut std::collections::HashMap<String, serde_yaml::Value>> {
        Ok(self.base.options_mut())
    }
}
use crate::meta_plugin::register_meta_plugin;

// Register the plugin at module initialization time
#[ctor::ctor]
fn register_shell_pid_plugin() {
    register_meta_plugin(MetaPluginType::ShellPid, |options, outputs| {
        Box::new(ShellPidMetaPlugin::new(options, outputs))
    })
    .expect("Failed to register ShellPidMetaPlugin");
}
