use aurora_core::{AuroraResult, Command, CommandCategory, Engine, Pipeline};
use aurora_locale::Localizer;
use std::sync::Arc;

use crate::matcher;

pub struct SemEngine {
    localizer: Arc<Localizer>,
}

impl SemEngine {
    pub fn new(localizer: Arc<Localizer>) -> Self {
        Self { localizer }
    }
}

impl Engine for SemEngine {
    fn name(&self) -> &'static str {
        "sem"
    }

    fn can_handle(&self, cmd: &Command) -> bool {
        matches!(cmd.category, CommandCategory::Sem)
    }

    fn execute(&self, cmd: &Command, _input: &Pipeline) -> AuroraResult<Pipeline> {
        let query = cmd.args.first().map(|s| s.as_str()).unwrap_or("");
        let path = cmd.args.get(1).map(|s| s.as_str()).unwrap_or(".");
        let langs: Vec<&str> = cmd
            .flags
            .get("lang")
            .map(|s| s.split(',').map(|l| l.trim()).collect())
            .unwrap_or_else(|| {
                vec![
                    "rs", "py", "js", "ts", "c", "cpp", "go",
                ]
            });

        if query.is_empty() {
            return Err(aurora_core::AuroraError::InvalidInput(
                self.localizer
                    .t("Укажите поисковый запрос", "Specify a search query")
                    .to_string(),
            ));
        }

        matcher::semantic_search(query, path, &langs)
    }
}
