use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::{Provider, report_provider_error};
use crate::status::*;
use crate::util::cache::VideoCache;
use crate::util::parse_abbreviated_number;
use crate::util::time::parse_time_to_seconds;
use crate::videos::{ServerOptions, VideoItem};
use async_trait::async_trait;
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use serde_json::Value;
use std::vec;

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

error_chain! {
    foreign_links {
        Io(std::io::Error);
        HttpRequest(wreq::Error);
    }
}

#[derive(Debug, Clone)]
pub struct RedtubeProvider {
    url: String,
}
impl RedtubeProvider {
    pub fn new() -> Self {
        RedtubeProvider {
            url: "https://www.redtube.com".to_string(),
        }
    }

    fn build_channel(&self, _clientversion: ClientVersion) -> Channel {
        Channel {
            id: "redtube".to_string(),
            name: "Redtube".to_string(),
            description: "Redtube brings you NEW porn videos every day for free".to_string(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=www.redtube.com".to_string(),
            status: "active".to_string(),
            categories: vec![],
            options: vec![],
            nsfw: true,
            cacheDuration: Some(1800),
            ytdlpCommand: Some("yt-dlp --impersonate chrome-120".to_string())
        }
    }
    async fn get(
        &self,
        cache: VideoCache,
        page: u8,
        sort: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let _ = sort;
        let video_url = format!("{}/mostviewed?page={}", self.url, page);
        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    return Ok(items.clone());
                } else {
                    items.clone()
                }
            }
            None => {
                vec![]
            }
        };
        let mut requester =
            crate::providers::requester_or_default(&options, module_path!(), "missing_requester");
        let text = match requester.get(&video_url, None).await {
            Ok(text) => text,
            Err(e) => {
                report_provider_error(
                    "redtube",
                    "get.request",
                    &format!("url={video_url}; error={e}"),
                )
                .await;
                return Ok(old_items);
            }
        };
        let video_items: Vec<VideoItem> = self.get_video_items_from_html(text.clone());
        if !video_items.is_empty() {
            cache.remove(&video_url);
            cache.insert(video_url.clone(), video_items.clone());
        } else {
            return Ok(old_items);
        }
        Ok(video_items)
    }
    async fn query(
        &self,
        cache: VideoCache,
        page: u8,
        query: &str,
        sort: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let _ = sort; //TODO
        let search_string = query.to_lowercase().trim().replace(" ", "+");
        let video_url = format!("{}/?search={}&page={}", self.url, search_string, page);

        // Check our Video Cache. If the result is younger than 1 hour, we return it.
        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    return Ok(items.clone());
                } else {
                    let _ = cache.check().await;
                    return Ok(items.clone());
                }
            }
            None => {
                vec![]
            }
        };
        let mut requester =
            crate::providers::requester_or_default(&options, module_path!(), "missing_requester");
        let text = match requester.get(&video_url, None).await {
            Ok(text) => text,
            Err(e) => {
                report_provider_error(
                    "redtube",
                    "query.request",
                    &format!("url={video_url}; error={e}"),
                )
                .await;
                return Ok(old_items);
            }
        };
        let video_items: Vec<VideoItem> = self.get_video_items_from_html_query(text.clone());
        if !video_items.is_empty() {
            cache.remove(&video_url);
            cache.insert(video_url.clone(), video_items.clone());
        } else {
            return Ok(old_items);
        }
        Ok(video_items)
    }

    fn extract_between<'a>(&self, text: &'a str, start: &str, end: &str) -> Option<&'a str> {
        let start_idx = text.find(start)?;
        let from = start_idx + start.len();
        let rest = &text[from..];
        let end_idx = rest.find(end)?;
        Some(&rest[..end_idx])
    }

    fn parse_video_grid_items(&self, html: &str) -> Vec<VideoItem> {
        if !html.contains("videos_grid") {
            return vec![];
        }

        let listing = html
            .split("videos_grid")
            .nth(1)
            .unwrap_or_default()
            .split("</ul>")
            .next()
            .unwrap_or_default();

        let mut items: Vec<VideoItem> = Vec::new();
        for li in listing.split("<li id=\"").skip(1) {
            let id = self
                .extract_between(li, "data-video-id=\"", "\"")
                .unwrap_or_default()
                .trim()
                .to_string();
            if id.is_empty() {
                continue;
            }

            let title = li
                .split("video-title-wrapper")
                .nth(1)
                .and_then(|part| self.extract_between(part, "title=\"", "\""))
                .or_else(|| {
                    li.split("class=\"video-title-text")
                        .nth(1)
                        .and_then(|part| self.extract_between(part, "title=\"", "\""))
                })
                .or_else(|| self.extract_between(li, "<a title=\"", "\""))
                .unwrap_or_default()
                .trim()
                .to_string();
            let title = decode(title.as_bytes()).to_string().unwrap_or(title);

            let thumb = self
                .extract_between(li, "data-src=\"", "\"")
                .or_else(|| self.extract_between(li, "data-o_thumb=\"", "\""))
                .unwrap_or_default()
                .replace("&amp;", "&");

            let raw_duration = self
                .extract_between(li, "<span class=\"video-properties tm_video_duration\">", "</span>")
                .unwrap_or_default()
                .trim()
                .to_string();
            let duration = parse_time_to_seconds(&raw_duration).unwrap_or(0) as u32;

            let views_str = self
                .extract_between(li, "<span class='info-views'>", "</span>")
                .unwrap_or_default()
                .trim()
                .to_string();
            let views = parse_abbreviated_number(&views_str).unwrap_or(0) as u32;

            let preview = self
                .extract_between(li, "data-mediabook=\"", "\"")
                .unwrap_or_default()
                .replace("&amp;", "&");

            let video_url = format!("{}/{}", self.url, id);
            let video_item =
                VideoItem::new(id, title, video_url, "redtube".to_string(), thumb, duration)
                    .views(views)
                    .preview(preview);
            items.push(video_item);
        }

        items
    }

    fn get_video_items_from_html(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() {
            println!("HTML is empty");
            return vec![];
        }
        let card_items = self.parse_video_grid_items(&html);
        if !card_items.is_empty() {
            return card_items;
        }

        let mut items: Vec<VideoItem> = Vec::new();
        let video_listing_content = html
            .split("<script type=\"application/ld+json\">")
            .collect::<Vec<&str>>()
            .get(1)
            .copied()
            .unwrap_or_default()
            .split("</script>")
            .collect::<Vec<&str>>()
            .get(0)
            .copied()
            .unwrap_or_default();
        let mut videos: Value = match serde_json::from_str(video_listing_content) {
            Ok(videos) => videos,
            Err(e) => {
                crate::providers::report_provider_error_background(
                    "redtube",
                    "get_video_items_from_html.json_parse",
                    &e.to_string(),
                );
                return items;
            }
        };
        let Some(video_list) = videos.as_array_mut() else {
            crate::providers::report_provider_error_background(
                "redtube",
                "get_video_items_from_html.json_not_array",
                "expected array",
            );
            return items;
        };
        for vid in video_list {
            let video_url: String = vid["embedUrl"].as_str().unwrap_or("").to_string();
            let mut title: String = vid["name"].as_str().unwrap_or("").to_string();
            // html decode
            title = decode(title.as_bytes()).to_string().unwrap_or(title);
            let id = video_url
                .split("=")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .to_string();
            let raw_duration = vid["duration"].as_str().unwrap_or("0");
            let duration = raw_duration
                .replace("PT", "")
                .replace("S", "")
                .parse::<u32>()
                .unwrap_or(0);
            let views: u64 = vid["interactionCount"].as_u64().unwrap_or(0);
            let thumb = vid["thumbnailUrl"].as_str().unwrap_or("").to_string();

            let video_item = VideoItem::new(
                id,
                title,
                video_url.to_string(),
                "redtube".to_string(),
                thumb,
                duration,
            )
            .views(views as u32);
            items.push(video_item);
        }
        return items;
    }

    fn get_video_items_from_html_query(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() {
            println!("HTML is empty");
            return vec![];
        }
        self.parse_video_grid_items(&html)
    }
}

#[async_trait]
impl Provider for RedtubeProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let _ = options;
        let _ = per_page;
        let _ = pool;
        let mut sort = sort.to_lowercase();
        if sort.contains("date") {
            sort = "mr".to_string();
        }
        let videos: std::result::Result<Vec<VideoItem>, Error> = match query {
            Some(q) => {
                self.query(cache, page.parse::<u8>().unwrap_or(1), &q, &sort, options)
                    .await
            }
            None => {
                self.get(cache, page.parse::<u8>().unwrap_or(1), &sort, options)
                    .await
            }
        };
        match videos {
            Ok(v) => v,
            Err(e) => {
                println!("Error fetching videos: {}", e);
                vec![]
            }
        }
    }

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

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

    #[test]
    fn parse_video_grid_items_handles_browse_cards() {
        let provider = RedtubeProvider::new();
        let html = r#"
            <ul id="block_browse" class="videos_grid">
                <li id="browse_195840661" data-video-id="195840661">
                    <a data-testid="plw_video_thumbnail_link" href="/195840661" data-video-id="195840661">
                        <img data-src="https://cdn.example/thumb.jpg" data-mediabook="https://cdn.example/preview.mp4?x=1&amp;y=2">
                    </a>
                    <a class="video-title-text js-pop tm_video_title " title="Stepmoms &amp; More"></a>
                    <span class="video-properties tm_video_duration">2:17:57</span>
                    <span class='info-views'>981K</span>
                </li>
            </ul>
        "#;

        let items = provider.parse_video_grid_items(html);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].id, "195840661");
        assert_eq!(items[0].title, "Stepmoms & More");
        assert_eq!(items[0].url, "https://www.redtube.com/195840661");
        assert_eq!(items[0].thumb, "https://cdn.example/thumb.jpg");
        assert_eq!(
            items[0].preview.as_deref(),
            Some("https://cdn.example/preview.mp4?x=1&y=2")
        );
        assert_eq!(items[0].duration, 8277);
        assert_eq!(items[0].views, Some(981000));
    }

    #[test]
    fn parse_video_grid_items_handles_tags_cards() {
        let provider = RedtubeProvider::new();
        let html = r#"
            <div><ul class="videos_grid">
                <li id="tags_videos_42785231" data-video-id="42785231">
                    <a data-testid="plw_video_thumbnail_link" href="/42785231" data-video-id="42785231">
                        <img data-o_thumb="https://cdn.example/thumb2.jpg" data-mediabook="https://cdn.example/p2.mp4">
                    </a>
                    <a class="video-title-text js-pop tm_video_title " title="Title 2"></a>
                    <span class="video-properties tm_video_duration">13:06</span>
                    <span class='info-views'>51.2K</span>
                </li>
            </ul></div>
        "#;

        let items = provider.parse_video_grid_items(html);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].id, "42785231");
        assert_eq!(items[0].url, "https://www.redtube.com/42785231");
        assert_eq!(items[0].thumb, "https://cdn.example/thumb2.jpg");
        assert_eq!(items[0].duration, 786);
        assert_eq!(items[0].views, Some(51200));
    }
}
