//! Alpine Linux packages search engine implementation (HTML)

use async_trait::async_trait;
use std::collections::HashMap;

use digse_core::{
    Engine, EngineCategory, EngineMetadata, Error, Result,
    SearchQuery, SearchResult, ResultType,
};

/// Alpine Linux binary packages search engine
pub struct AlpineLinuxEngine {
    metadata: EngineMetadata,
    client: reqwest::Client,
}

impl AlpineLinuxEngine {
    pub fn new() -> Self {
        let metadata = EngineMetadata {
            name: "alpinelinux".to_string(),
            category: EngineCategory::IT,
            enabled: true,
            requires_auth: false,
            timeout_seconds: 15,
            description: "Alpine Linux - search binary packages (pkgs.alpinelinux.org).".to_string(),
            website: Some("https://www.alpinelinux.org".to_string()),
        };

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()
            .expect("Failed to create Alpine Linux HTTP client");

        AlpineLinuxEngine { metadata, client }
    }

    async fn fetch_results(&self, query: &SearchQuery) -> Result<Vec<SearchResult>> {
        let base_url = "https://pkgs.alpinelinux.org";
        let page = ((query.offset / 10) + 1).to_string();
        let name = format!("*{}*", query.query);

        let resp = self.client
            .get(format!("{}/packages", base_url))
            .header("User-Agent", "digse/0.0.1")
            .query(&[
                ("name", name.as_str()),
                ("page", page.as_str()),
                ("arch", "x86_64"),
            ])
            .send()
            .await
            .map_err(|e| Error::HttpError(e.to_string()))?;

        if !resp.status().is_success() {
            return Ok(vec![]);
        }
        let html = resp.text().await.map_err(|e| Error::HttpError(e.to_string()))?;
        Ok(self.parse_html(&html, base_url))
    }

    fn parse_html(&self, html: &str, base_url: &str) -> Vec<SearchResult> {
        use scraper::{Html, Selector};
        let document = Html::parse_document(html);
        let mut results = Vec::new();

        let tr_sel = match Selector::parse("table tbody tr") {
            Ok(s) => s,
            Err(_) => return results,
        };
        let pkg_a_sel = Selector::parse("td.package a").unwrap();
        let ver_sel = Selector::parse("td.version").unwrap();
        let date_sel = Selector::parse("td.bdate").unwrap();
        let license_sel = Selector::parse("td.license").unwrap();
        let repo_sel = Selector::parse("td.repo").unwrap();

        for el in document.select(&tr_sel) {
            let a = match el.select(&pkg_a_sel).next() {
                Some(a) => a,
                None => continue,
            };
            let href = a.value().attr("href").unwrap_or("").to_string();
            let title = a.text().collect::<String>().trim().to_string();
            if title.is_empty() {
                continue;
            }
            let url = if href.starts_with("http") { href } else { format!("{}{}", base_url, href) };
            let version = text_of(&el, &ver_sel);
            let published = text_of(&el, &date_sel);
            let license = text_of(&el, &license_sel);
            let repo = text_of(&el, &repo_sel);
            let snippet = format!("version: {} | repo: {} | license: {}", version, repo, license);

            let r = SearchResult::new(title, url)
                .with_snippet(snippet)
                .with_engine(self.name())
                .with_result_type(ResultType::IT)
                .with_extra("version", serde_json::json!(version))
                .with_extra("published", serde_json::json!(published))
                .with_extra("license", serde_json::json!(license))
                .with_extra("repo", serde_json::json!(repo));
            results.push(r);
        }
        results
    }
}

fn text_of(el: &scraper::ElementRef, sel: &scraper::Selector) -> String {
    el.select(sel).next()
        .map(|e| e.text().collect::<String>().trim().to_string())
        .unwrap_or_default()
}

#[async_trait]
impl Engine for AlpineLinuxEngine {
    fn name(&self) -> &str { &self.metadata.name }
    fn category(&self) -> EngineCategory { self.metadata.category }
    fn is_enabled(&self) -> bool { self.metadata.enabled }
    fn metadata(&self) -> EngineMetadata { self.metadata.clone() }

    async fn search(&self, query: &SearchQuery) -> Result<Vec<SearchResult>> {
        let mut results = self.fetch_results(query).await?;
        for (i, r) in results.iter_mut().enumerate() {
            r.rank = query.offset + i + 1;
            r.score = 1.0 - (i as f64 * 0.05);
        }
        Ok(results)
    }

    fn supports_result_type(&self, t: &ResultType) -> bool {
        matches!(t, ResultType::IT | ResultType::All)
    }

    fn settings(&self) -> HashMap<String, String> {
        let mut s = HashMap::new();
        s.insert("base_url".to_string(), "https://pkgs.alpinelinux.org".to_string());
        s.insert("arch".to_string(), "x86_64".to_string());
        s
    }
}
