use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand, SimplePluginCommand};
use nu_protocol::{Category, LabeledError, Signature, SyntaxShape, Type, Value};
use crate::FluentPlugin;

pub struct ExtractMessages;

impl SimplePluginCommand for ExtractMessages {
    type Plugin = FluentPlugin;

    fn name(&self) -> &str {
        "fluent-extract"
    }

    fn signature(&self) -> Signature {
        Signature::build(PluginCommand::name(self))
            .input_output_type(Type::Any, Type::List(Box::new(Type::String)))
            .required("file", SyntaxShape::Filepath, "FTL file to extract messages from")
            .category(Category::Strings)
    }

    fn description(&self) -> &str {
        "Extract message IDs from a Fluent Translation List (.ftl) file"
    }

    fn examples(&self) -> Vec<nu_protocol::Example<'_>> {
        vec![
            nu_protocol::Example {
                description: "Extract message IDs from an FTL file",
                example: "fluent-extract locales/en-US/main.ftl",
                result: None,
            },
        ]
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        input: &Value,
    ) -> Result<Value, LabeledError> {
        let _file_path: String = call.req(0)?;

        let parsed = SimplePluginCommand::run(&ParseFtl, _plugin, _engine, call, input)?;

        // Extract message IDs from the parsed result
        if let Value::Record { val, .. } = parsed {
            if let Some(Value::List { vals, .. }) = val.get("messages") {
                let message_ids: Vec<Value> = vals
                    .iter()
                    .filter_map(|msg| {
                        if let Value::Record { val, .. } = msg {
                            val.get("id").cloned()
                        } else {
                            None
                        }
                    })
                    .collect();

                return Ok(Value::list(message_ids, call.head));
            }
        }

        Err(LabeledError::new("Extract error").with_label("Failed to extract messages", call.head))
    }
}

use crate::commands::ParseFtl;