
async function searchResults(keyword) {
    const results = [];
    try {
        const response = await fetchv2("https://aniweek.com/bbs/search.php?srows=240&gr_id=&sfl=wr_subject&stx=" + encodeURIComponent(keyword));
        const html = await response.text();
        const regex = /<div class="list-row">[\s\S]*?<a href="([^"]+)"[\s\S]*?<img src="([^"]+)" alt="([^"]+)"/g;

        let match;
        while ((match = regex.exec(html)) !== null) {
            results.push({
                title: match[3].trim(),
                image: match[2].trim().replace("..","https://aniweek.com"),
                href: "https://aniweek.com" + match[1].trim()
            });
        }

        return JSON.stringify(results);
    } catch (err) {
        return JSON.stringify([{
            title: "Error",
            image: "Error",
            href: "Error"
        }]);
    }
}

async function extractDetails(url) {
    try {
        const response = await fetchv2(url);
        const html = await response.text();
        const regex = /<div class="view-stocon"><div class="c" id="animeContents">([\s\S]*?)<\/div><\/div>/;
        
        let description = "N/A";
        const match = regex.exec(html);
        if (match) {
            description = match[1].replace(/<br>/g, "\n").replace(/&nbsp;/g, " ").replace(/<[^>]*>/g, "").replace(/\n\n+/g, "\n").trim();
        }

        return JSON.stringify([{
            description: description,
            aliases: "N/A",
            airdate: "N/A"
        }]);
    } catch (err) {
        return JSON.stringify([{
            description: "Error",
            aliases: "Error",
            airdate: "Error"
        }]);
    }
}

async function extractEpisodes(url) {
    const results = [];
    try {
        const response = await fetchv2(url);
        const html = await response.text();
        const regex = /<li class="list-item">[\s\S]*?<div class="wr-num">(\d+)<\/div>[\s\S]*?<a href="([^"]+)"[\s\S]*?<\/li>/g;

        let match;
        while ((match = regex.exec(html)) !== null) {
            results.push({
                href: "https://aniweek.com" + match[2].trim(),
                number: parseInt(match[1], 10)
            });
        }

        return JSON.stringify(results.reverse());
    } catch (err) {
        return JSON.stringify([{
            href: "Error",
            number: "Error"
        }]);
    }
}

async function extractStreamUrl(url) {
    try {
        const response = await fetchv2(url);
        const html = await response.text();
        const regex = /<input type="hidden" name="vurl" value="https:\/\/michealcdn\.com\/video\/([^"]+)"/;
        
        const match = regex.exec(html);
        if (match) {
            try {
                const videoId = match[1];
                console.log("Video ID: " + videoId);
                const postData = "hash=" + videoId + "&r=https%3A%2F%2Fmm.viaproducciones.net%2F"
                const headers = {
                    "X-Requested-With": "XMLHttpRequest",
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                };
                const response = await fetchv2("https://michealcdn.com/player/index.php?data=" + videoId + "&do=getVideo", headers, "POST", postData);
                const data = await response.json();
                console.log("Fetched video data: " + JSON.stringify(data));
                
                const streamUrl = data.securedLink;
                return JSON.stringify({
                    "streams": [
                        {
                            "title": "Stream 1",
                            "streamUrl": streamUrl,
                            "headers": {
                                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                                "Accept": "*/*",
                                "Accept-Language": "en-US,en;q=0.9",
                                "Accept-Encoding": "gzip, deflate, br",
                                "Referer": "https://michealcdn.com/",
                                "Origin": "https://michealcdn.com",
                                "Sec-Fetch-Dest": "video",
                                "Sec-Fetch-Mode": "cors",
                                "Sec-Fetch-Site": "same-origin",
                                "Range": "bytes=0-"
                            }
                        }
                    ],
                    "subtitle": ""
                });
            } catch (err) {
                console.log("Error fetching video URL:"+ err);
            }
            return JSON.stringify({"streams": [{"title": "Error", "streamUrl": "https://error.org/", "headers": {}}], "subtitle": ""});
        }

        return JSON.stringify({"streams": [{"title": "Error", "streamUrl": "https://error.org/", "headers": {}}], "subtitle": ""});
    } catch (err) {
        return JSON.stringify({"streams": [{"title": "Error", "streamUrl": "https://error.org/", "headers": {}}], "subtitle": ""});
    }
}
