use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::{
    Provider, report_provider_error, requester_or_default,
};
use crate::status::*;
use crate::util::cache::VideoCache;
use crate::util::parse_abbreviated_number;
use crate::videos::{ServerOptions, VideoItem};
use async_trait::async_trait;
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use regex::Regex;
use scraper::{ElementRef, Html, Selector};
use wreq::Version;

pub const CHANNEL_METADATA: crate::providers::ProviderChannelMetadata =
    crate::providers::ProviderChannelMetadata {
        group_id: "mainstream-tube",
        tags: &["tube", "hd", "mixed", "search"],
    };

const BASE_URL: &str = "https://www.xnxx.com";
const CHANNEL_ID: &str = "xnxx";
const FIREFOX_UA: &str =
    "Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0";
const HTML_ACCEPT: &str =
    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8";

error_chain! {
    foreign_links {
        Io(std::io::Error);
    }
    errors {
        Parse(msg: String) {
            description("parse error")
            display("parse error: {}", msg)
        }
    }
}

#[derive(Debug, Clone)]
enum Target {
    // Most-viewed global feed — the best "default" xnxx has
    Hits,
    // Keyword search (also covers tag shortcuts since /search/{term} works for both)
    Search(String),
}

#[derive(Debug, Clone)]
pub struct XnxxProvider;

impl XnxxProvider {
    pub fn new() -> Self {
        Self
    }

    fn build_channel(&self, _cv: ClientVersion) -> Channel {
        Channel {
            id: CHANNEL_ID.to_string(),
            name: "XNXX".to_string(),
            description: "XNXX — 10M+ free HD porn videos with keyword search, tag routing, and a most-viewed global feed.".to_string(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=xnxx.com".to_string(),
            status: "active".to_string(),
            categories: vec![],
            options: vec![
                ChannelOption {
                    id: "sort".to_string(),
                    title: "Sort".to_string(),
                    description: "Browse XNXX ranking feeds.".to_string(),
                    systemImage: "list.number".to_string(),
                    colorName: "blue".to_string(),
                    options: vec![
                        FilterOption {
                            id: "popular".to_string(),
                            title: "Most Viewed".to_string(),
                        },
                        FilterOption {
                            id: "new".to_string(),
                            title: "Latest (Most Viewed)".to_string(),
                        },
                    ],
                    multiSelect: false,
                },
            ],
            nsfw: true,
            cacheDuration: Some(1800),
            ytdlpCommand: Some("yt-dlp --impersonate chrome-120".to_string())
        }
    }

    fn selector(value: &str) -> Result<Selector> {
        Selector::parse(value)
            .map_err(|e| Error::from(format!("selector `{value}` failed: {e}")))
    }

    fn decode_html(text: &str) -> String {
        decode(text.as_bytes())
            .to_string()
            .unwrap_or_else(|_| text.to_string())
    }

    fn text_of(el: &ElementRef<'_>) -> String {
        let raw: String = el.text().collect::<Vec<_>>().join(" ");
        Self::decode_html(&raw.split_whitespace().collect::<Vec<_>>().join(" "))
    }

    fn normalize_url(path: &str) -> String {
        let path = path.trim();
        if path.starts_with("http://") || path.starts_with("https://") {
            return path.to_string();
        }
        if path.starts_with("//") {
            return format!("https:{path}");
        }
        if path.starts_with('/') {
            return format!("{BASE_URL}{path}");
        }
        format!("{BASE_URL}/{path}")
    }

    /// Build a 0-indexed paged URL.
    /// page 1 → `{base}`, page N → `{base}/{N-1}`
    fn page_url(base: &str, page: u16) -> String {
        let base = base.trim_end_matches('/');
        if page <= 1 {
            base.to_string()
        } else {
            format!("{base}/{}", page - 1)
        }
    }

    fn target_url(target: &Target, page: u16) -> String {
        match target {
            Target::Hits => Self::page_url(&format!("{BASE_URL}/hits"), page),
            Target::Search(q) => {
                // Encode the query as slug: lowercase, spaces become hyphens
                // xnxx search uses URL-encoded spaces but also accepts hyphens
                let slug = q.trim()
                    .replace(' ', "-")
                    .to_ascii_lowercase();
                Self::page_url(&format!("{BASE_URL}/search/{slug}"), page)
            }
        }
    }

    fn html_headers(referer: &str) -> Vec<(String, String)> {
        vec![
            ("User-Agent".to_string(), FIREFOX_UA.to_string()),
            ("Accept".to_string(), HTML_ACCEPT.to_string()),
            ("Accept-Language".to_string(), "en-US,en;q=0.5".to_string()),
            ("Referer".to_string(), referer.to_string()),
        ]
    }

    async fn fetch_html(
        requester: &mut crate::util::requester::Requester,
        url: &str,
    ) -> Result<String> {
        requester
            .get_with_headers(url, Self::html_headers(url), Some(Version::HTTP_11))
            .await
            .map_err(|e| Error::from(format!("request failed for {url}: {e}")))
    }

    fn parse_duration_mins(text: &str) -> u32 {
        // Matches patterns like "16min", "23min", "1h20min", "1h"
        let re_hm = Regex::new(r"(\d+)h\s*(\d+)?min").ok();
        let re_h = Regex::new(r"(\d+)h(?:our)?s?").ok();
        let re_m = Regex::new(r"(\d+)\s*min").ok();
        let re_s = Regex::new(r"(\d+)\s*sec").ok();

        let text = text.trim();
        if let Some(re) = re_hm.as_ref() {
            if let Some(cap) = re.captures(text) {
                let h: u32 = cap.get(1).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
                let m: u32 = cap.get(2).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
                return h * 3600 + m * 60;
            }
        }
        if let Some(re) = re_h.as_ref() {
            if let Some(cap) = re.captures(text) {
                let h: u32 = cap.get(1).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
                return h * 3600;
            }
        }
        if let Some(re) = re_m.as_ref() {
            if let Some(cap) = re.captures(text) {
                let m: u32 = cap.get(1).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
                return m * 60;
            }
        }
        if let Some(re) = re_s.as_ref() {
            if let Some(cap) = re.captures(text) {
                let s: u32 = cap.get(1).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
                return s;
            }
        }
        0
    }

    fn parse_views(text: &str) -> Option<u32> {
        // text looks like "471.4M " or "15.5M " — extract the number+suffix before whitespace/icon
        let cleaned = text
            .split_whitespace()
            .next()
            .unwrap_or("")
            .trim_end_matches(',');
        parse_abbreviated_number(cleaned)
    }

    fn parse_rating_pct(text: &str) -> Option<f32> {
        let digits: String = text.chars().filter(|c| c.is_ascii_digit()).collect();
        digits.parse::<f32>().ok().map(|v| v / 100.0)
    }

    /// Parse video cards from both xnxx listing page formats.
    ///
    /// Format A (search pages): outer div has `data-eid` attribute directly.
    /// Format B (hits/browse pages): outer div has `data-video` JSON attribute.
    fn parse_listing(html: &str, limit: usize) -> Result<Vec<VideoItem>> {
        let document = Html::parse_document(html);
        let card_sel = Self::selector("div.thumb-block")?;
        let link_sel = Self::selector("a[href]")?;
        let img_sel = Self::selector("img[data-src]")?;
        let uploader_sel = Self::selector(".uploader a")?;
        let metadata_sel = Self::selector("div.metadata, p.metadata")?;
        let views_right_sel = Self::selector("span.right")?;
        let duration_left_sel = Self::selector("span.left")?;
        let superfluous_sel = Self::selector("span.superfluous")?;
        // Title: either `a.title[title]` (hits) or `p a[title]` (search)
        let title_sel = Self::selector("a.title[title], p a[title], a[title][href]")?;

        let mut items = Vec::new();

        'card: for card in document.select(&card_sel) {
            // Find a link that goes to a /video- page
            let video_link = card
                .select(&link_sel)
                .find(|el| {
                    el.value()
                        .attr("href")
                        .map(|h| h.contains("/video-"))
                        .unwrap_or(false)
                });
            let Some(video_link) = video_link else { continue };

            let href = video_link.value().attr("href").unwrap_or_default();
            let page_url = Self::normalize_url(href);
            if page_url.is_empty() {
                continue;
            }

            // Extract eid from the URL path: /video-{eid}/{slug}
            // Also works as the video id for deduplication
            let eid = href
                .trim_matches('/')
                .split('/')
                .find(|s| s.starts_with("video-"))
                .and_then(|s| s.strip_prefix("video-"))
                .unwrap_or_default()
                .to_string();
            if eid.is_empty() {
                continue;
            }

            // Numeric id: prefer data-id, then data-video JSON, then eid
            let numeric_id = card.value().attr("data-id")
                .map(str::to_string)
                .filter(|s| !s.is_empty())
                .or_else(|| {
                    // Try to extract from data-video JSON: {"id":12345,...}
                    card.value().attr("data-video")
                        .and_then(|dv| {
                            let re = Regex::new(r#""id"\s*:\s*(\d+)"#).ok()?;
                            re.captures(dv)?.get(1).map(|m| m.as_str().to_string())
                        })
                })
                .unwrap_or_else(|| eid.clone());

            // Thumbnail
            let thumb = card
                .select(&img_sel)
                .next()
                .and_then(|el| el.value().attr("data-src").map(str::to_string))
                .unwrap_or_default();
            if thumb.is_empty() {
                continue 'card;
            }

            // Title: find an <a title="..."> element pointing to the video
            let title = card
                .select(&title_sel)
                .find(|el| {
                    el.value()
                        .attr("href")
                        .map(|h| h.contains("/video-"))
                        .unwrap_or(false)
                })
                .and_then(|el| el.value().attr("title").map(Self::decode_html))
                .filter(|t| !t.trim().is_empty());
            let Some(title) = title else { continue };

            // Uploader
            let uploader_el = card.select(&uploader_sel).next();
            let uploader_name = uploader_el.as_ref().map(|el| Self::text_of(el))
                .filter(|s| !s.is_empty());
            let uploader_href = uploader_el
                .and_then(|el| el.value().attr("href").map(Self::normalize_url));

            // Metadata: views, rating, duration
            // Both formats share: views in span.right, rating in span.superfluous
            // Duration: in span.left (hits) or as text between span.right and end (search)
            let metadata_el = card.select(&metadata_sel).next();
            let (duration, views, rating) = if let Some(meta) = metadata_el {
                // Rating from .superfluous
                let rating = meta
                    .select(&superfluous_sel)
                    .map(|el| Self::text_of(&el))
                    .find(|t| t.contains('%'))
                    .and_then(|t| Self::parse_rating_pct(&t));

                // Views from span.right (text before the eye icon)
                let views = meta
                    .select(&views_right_sel)
                    .next()
                    .map(|el| Self::text_of(&el))
                    .and_then(|t| Self::parse_views(&t));

                // Duration: try span.left first (hits format), then raw metadata text (search format)
                let duration = meta
                    .select(&duration_left_sel)
                    .next()
                    .map(|el| Self::text_of(&el))
                    .map(|t| Self::parse_duration_mins(&t))
                    .filter(|&d| d > 0)
                    .unwrap_or_else(|| {
                        // Search format: duration text is a direct text node in p.metadata
                        let full_text = Self::text_of(&meta);
                        Self::parse_duration_mins(&full_text)
                    });

                (duration, views, rating)
            } else {
                (0, None, None)
            };

            let mut item = VideoItem::new(
                numeric_id,
                title.trim().to_string(),
                page_url,
                CHANNEL_ID.to_string(),
                thumb,
                duration,
            );
            if let Some(v) = views {
                item.views = Some(v);
            }
            if let Some(r) = rating {
                item.rating = Some(r);
            }
            if let Some(name) = uploader_name {
                item.uploader = Some(name);
            }
            if let Some(url) = uploader_href.filter(|u| !u.is_empty()) {
                let uploader_id = url
                    .trim_end_matches('/')
                    .rsplit('/')
                    .next()
                    .unwrap_or_default()
                    .to_string();
                if !uploader_id.is_empty() {
                    item.uploaderId = Some(format!("{CHANNEL_ID}:{uploader_id}"));
                }
                item.uploaderUrl = Some(url);
            }

            items.push(item);
            if items.len() >= limit {
                break;
            }
        }

        Ok(items)
    }

    fn resolve_query_target(query: &str) -> Target {
        let trimmed = query.trim().trim_start_matches('@');

        // Explicit prefix shortcuts: tag:X, cat:X
        if let Some((kind, value)) = trimmed.split_once(':') {
            let value = value.trim();
            if !value.is_empty() {
                match kind.trim().to_ascii_lowercase().as_str() {
                    "tag" | "cat" | "category" => return Target::Search(value.to_string()),
                    _ => {}
                }
            }
        }

        Target::Search(trimmed.to_string())
    }

    async fn fetch_target(
        &self,
        cache: VideoCache,
        target: Target,
        page: u16,
        per_page: usize,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let url = Self::target_url(&target, page);
        let cache_key = format!("{url}#per={per_page}");

        if let Some((ts, cached)) = cache.get(&cache_key) {
            if ts.elapsed().unwrap_or_default().as_secs() < 300 {
                return Ok(cached.clone());
            }
        }

        let mut requester =
            requester_or_default(&options, CHANNEL_ID, "xnxx.fetch_target.missing_requester");
        let html = match Self::fetch_html(&mut requester, &url).await {
            Ok(v) => v,
            Err(e) => {
                report_provider_error(
                    CHANNEL_ID,
                    "fetch_target.request",
                    &format!("url={url}; error={e}"),
                )
                .await;
                return Ok(vec![]);
            }
        };

        if html.trim().is_empty() {
            report_provider_error(CHANNEL_ID, "fetch_target.empty", &format!("url={url}")).await;
            return Ok(vec![]);
        }

        let items = Self::parse_listing(&html, per_page)?;
        if !items.is_empty() {
            cache.insert(cache_key, items.clone());
        }
        Ok(items)
    }
}

#[async_trait]
impl Provider for XnxxProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        _pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let page = page.parse::<u16>().unwrap_or(1).max(1);
        let per_page = per_page.parse::<usize>().unwrap_or(10).clamp(1, 60);

        let target = match query {
            Some(q) if !q.trim().is_empty() => Self::resolve_query_target(q.trim()),
            _ => Target::Hits,
        };

        // sort=new falls back to Hits since xnxx has no chronological listing
        let target = match (&target, sort.trim().to_ascii_lowercase().as_str()) {
            (Target::Hits, _) => Target::Hits,
            (Target::Search(_), _) => target,
        };

        match self.fetch_target(cache, target, page, per_page, options).await {
            Ok(items) => items,
            Err(e) => {
                crate::providers::report_provider_error(
                    CHANNEL_ID,
                    "get_videos",
                    &format!("sort={sort}; page={page}; error={e}"),
                )
                .await;
                vec![]
            }
        }
    }

    fn get_channel(&self, cv: ClientVersion) -> Option<Channel> {
        Some(self.build_channel(cv))
    }
}
