use std::time::Duration;

use reqwest::Client;
use scraper::Html;

use crate::error::EngineError;
use crate::models::SearchResult;

const ENGINE: &str = "duckduckgo";
const DDG_URL: &str = "https://html.duckduckgo.com/html/";

// Conservative limit so a slow DDG response doesn't block the whole fan-out.
const TIMEOUT_MS: u64 = 8_000;

pub async fn search(
    client: &Client,
    query: &str,
    max_results: usize,
) -> Result<Vec<SearchResult>, EngineError> {
    let response = tokio::time::timeout(
        Duration::from_millis(TIMEOUT_MS),
        client.get(DDG_URL).query(&[("q", query)]).send(),
    )
    .await
    .map_err(|_| EngineError::Timeout { engine: ENGINE })?
    .map_err(|e| EngineError::Http {
        engine: ENGINE,
        source: e,
    })?;

    if !response.status().is_success() {
        return Err(EngineError::BadStatus {
            engine: ENGINE,
            status: response.status().as_u16(),
        });
    }

    let body = response.text().await.map_err(|e| EngineError::Http {
        engine: ENGINE,
        source: e,
    })?;

    parse(&body, max_results)
}

fn parse(html: &str, max_results: usize) -> Result<Vec<SearchResult>, EngineError> {
    let document = Html::parse_document(html);

    // Each organic result lives in a <div class="result"> — ads use different classes
    let result_sel = sel(ENGINE, "div.result")?;
    let title_sel = sel(ENGINE, "a.result__a")?;
    let snippet_sel = sel(ENGINE, "a.result__snippet")?;

    let mut results = Vec::new();

    for element in document.select(&result_sel) {
        if results.len() >= max_results {
            break;
        }

        let Some(title_el) = element.select(&title_sel).next() else {
            continue;
        };

        let title = title_el.text().collect::<String>().trim().to_string();
        if title.is_empty() {
            continue;
        }

        // DDG wraps destination URLs as redirects: /l/?uddg=<encoded-url>&...
        // We extract the real URL from the uddg query parameter.
        let href = title_el.value().attr("href").unwrap_or("");
        let url = extract_destination_url(href).unwrap_or_else(|| href.to_string());
        if url.is_empty() {
            continue;
        }

        let snippet = element
            .select(&snippet_sel)
            .next()
            .map(|el| el.text().collect::<String>().trim().to_string())
            .filter(|s| !s.is_empty());

        results.push(SearchResult {
            title,
            url,
            snippet,
            source_engine: ENGINE.to_string(),
        });
    }

    Ok(results)
}

// DDG redirect links look like: /l/?uddg=https%3A%2F%2Fexample.com&rut=...
// Parse as a full URL and pull out the uddg parameter value.
fn extract_destination_url(href: &str) -> Option<String> {
    let full = format!("https://html.duckduckgo.com{href}");
    let parsed = url::Url::parse(&full).ok()?;
    parsed
        .query_pairs()
        .find(|(k, _)| k == "uddg")
        .map(|(_, v)| v.into_owned())
}

fn sel(engine: &'static str, s: &str) -> Result<scraper::Selector, EngineError> {
    scraper::Selector::parse(s).map_err(|e| EngineError::ParseFailed {
        engine,
        reason: format!("invalid selector '{s}': {e:?}"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_destination_url() {
        let href = "/l/?uddg=https%3A%2F%2Fwww.rust-lang.org%2F&rut=abc123";
        assert_eq!(
            extract_destination_url(href),
            Some("https://www.rust-lang.org/".to_string())
        );
    }

    #[test]
    fn test_parse_extracts_results() {
        let html = r#"
            <div class="result">
                <a class="result__a" href="/l/?uddg=https%3A%2F%2Fexample.com">Example Site</a>
                <a class="result__snippet">An example website for testing.</a>
            </div>
            <div class="result">
                <a class="result__a" href="/l/?uddg=https%3A%2F%2Frust-lang.org">Rust</a>
                <a class="result__snippet">Systems programming language.</a>
            </div>
        "#;

        let results = parse(html, 10).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].title, "Example Site");
        assert_eq!(results[0].url, "https://example.com");
        assert_eq!(results[1].url, "https://rust-lang.org");
        assert!(results[0].snippet.is_some());
    }

    #[test]
    fn test_parse_respects_max_results() {
        let result_html = r#"<div class="result"><a class="result__a" href="/l/?uddg=https%3A%2F%2Fexample.com">T</a></div>"#;
        let html = result_html.repeat(5);
        let results = parse(&html, 2).unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_parse_skips_missing_snippet() {
        let html = r#"
            <div class="result">
                <a class="result__a" href="/l/?uddg=https%3A%2F%2Fexample.com">Title</a>
            </div>
        "#;
        let results = parse(html, 10).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].snippet.is_none());
    }

    #[tokio::test]
    #[ignore]
    async fn test_live_search() {
        let client = crate::engines::build_http_client().unwrap();
        let results = search(&client, "rust programming language", 10)
            .await
            .unwrap();

        println!("Got {} results:", results.len());
        for r in &results {
            println!("  [{}] {}", r.title, r.url);
            if let Some(s) = &r.snippet {
                println!("    snippet: {}", &s[..s.len().min(80)]);
            }
        }

        assert!(!results.is_empty(), "expected at least one result from DDG");
        for r in &results {
            assert!(!r.title.is_empty());
            assert!(r.url.starts_with("http"));
        }
    }
}
