use base64::{engine::general_purpose, Engine as _};
use ntex::web;

use crate::util::requester::Requester;

/// Extracts digits from a string and sums them.
fn ssut51(arg: &str) -> u32 {
    arg.chars()
        .filter(|c| c.is_ascii_digit())
        .map(|c| c.to_digit(10).unwrap())
        .sum()
}

/// Encodes a token: "<sum1>-<host>-<sum2>" using Base64 URL-safe variant.
fn boo(sum1: u32, sum2: u32) -> String {
    let raw = format!("{}-{}-{}", sum1, "sxyprn.com", sum2);
    let encoded = general_purpose::STANDARD.encode(raw);

    // Replace + → -, / → _, = → .
    encoded
        .replace('+', "-")
        .replace('/', "_")
        .replace('=', ".")
}

#[derive(Debug, Clone)]
pub struct SxyprnProxy {
}

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

    pub async fn get_video_url(
        &self,
        url: String,
        requester: web::types::State<Requester>,
    ) -> String {
        let mut requester = requester.get_ref().clone();
        let url = "https://sxyprn.com/".to_string() + &url;
        let text = requester.get(&url, None).await.unwrap_or("".to_string());
        if text.is_empty() {
            return "".to_string();
        }
        let data_string = text.split("data-vnfo='").collect::<Vec<&str>>()[1]
            .split("\":\"").collect::<Vec<&str>>()[1]
                .split("\"}").collect::<Vec<&str>>()[0].replace("\\","");

        let mut tmp = data_string
            .split("/")
            .map(|s| s.to_string())
            .collect::<Vec<String>>();
        tmp[1] = format!("{}8/{}", tmp[1], boo(ssut51(tmp[6].as_str()), ssut51(tmp[7].as_str())));
        //preda
        tmp[5] = format!(
            "{}",
            tmp[5].parse::<u32>().unwrap() - ssut51(tmp[6].as_str()) - ssut51(tmp[7].as_str())
        );
        let sxyprn_video_url = format!("https://sxyprn.com{}",tmp.join("/"));
        
        let response = requester.get_raw(&sxyprn_video_url).await;
        match response {
            Ok(resp) => {
                return resp.headers().get("Location").unwrap().to_str().unwrap_or("").to_string();
            },
            Err(e) => {
                println!("Error fetching video URL: {}", e);
            }
        }
        return "".to_string();
    }
}