const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const router = express.Router();

const targetUrl = process.env.TARGET_URL;
const proxyUrl = process.env.PROXY_URL;

const EXTERNAL_SITEMAP_INDEX_URL = 'https://komikcast.pics/sitemap_index.xml'; 

const RSS_LIST_URL = `${targetUrl}/daftar-komik/`;
const MAX_RSS_ITEMS = 50; 
const AXIOS_TIMEOUT = 10000;

const fetchUrlsForRss = async () => {
    try {
        const response = await axios.get(RSS_LIST_URL, { timeout: AXIOS_TIMEOUT });
        const $ = cheerio.load(response.data);
        const urls = [];

        $('.list-update .utao-item a').slice(0, MAX_RSS_ITEMS).each((i, el) => {
            let path = $(el).attr('href');
            if (path && path.startsWith(targetUrl)) {
                const proxiedUrl = path.replace(targetUrl, proxyUrl);
                urls.push({
                    loc: proxiedUrl,
                    title: $(el).find('.judul-item').text().trim() || `Pembaruan Komik ${i + 1}`,
                    pubDate: new Date().toUTCString()
                });
            }
        });
        
        return urls;

    } catch (error) {
        console.error('Gagal mengambil URL dari situs target untuk RSS:', error.message);
        return [];
    }
};


// ------------------------------------------
// SITEMAP XML
// ------------------------------------------
router.get('/sitemap.xml', async (req, res) => {
    try {
        const response = await axios.get(EXTERNAL_SITEMAP_INDEX_URL, {
            responseType: 'text',
            timeout: AXIOS_TIMEOUT,
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
            }
        });

        let xmlContent = response.data;
        
        xmlContent = xmlContent.replace(/<\?xml-stylesheet.*?\?>/i, '');
		
        const targetDomainRegex = new RegExp(targetUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
        let proxiedXmlContent = xmlContent.replace(targetDomainRegex, proxyUrl);
        
        res.header('Content-Type', 'application/xml');
        res.send(proxiedXmlContent);

    } catch (error) {
        let errorMessage = `Gagal memproksi sitemap dari ${EXTERNAL_SITEMAP_INDEX_URL}. `;
        
        if (error.response) {
            errorMessage += `Status: ${error.response.status}. Pesan: ${error.response.statusText}.`;
        } else if (error.code === 'ETIMEDOUT') {
            errorMessage += `Timeout (${AXIOS_TIMEOUT}ms).`;
        } else {
            errorMessage += `Pesan: ${error.message}.`;
        }
        
        console.error(errorMessage);
        
        let fallbackXml = '<?xml version="1.0" encoding="UTF-8"?>\n';
        fallbackXml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
        fallbackXml += '<url>\n';
        fallbackXml += `  <loc>${proxyUrl}/</loc>\n`;
        fallbackXml += '</url>\n';
        fallbackXml += '</urlset>';
        
        res.header('Content-Type', 'application/xml');
        res.status(503).send(fallbackXml); 
    }
});


// ------------------------------------------
// SITEMAP TURUNAN (*-sitemap*.xml) - WILDWARD LOGIC
// ------------------------------------------
router.get('/*sitemap*.xml', async (req, res) => {
    const requestedPath = req.originalUrl;
    
    const targetSitemapUrl = targetUrl + requestedPath;
    
    try {
        const response = await axios.get(targetSitemapUrl, {
            responseType: 'text',
            timeout: AXIOS_TIMEOUT,
            headers: { 'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1)' }
        });

        let xmlContent = response.data;
        
        xmlContent = xmlContent.replace(/<\?xml-stylesheet.*?\?>/i, '');
        
        const targetDomainRegex = new RegExp(targetUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
        let proxiedXmlContent = xmlContent.replace(targetDomainRegex, proxyUrl);
        
        res.header('Content-Type', 'application/xml');
        res.status(200).send(proxiedXmlContent);

    } catch (error) {
        console.error(`Gagal memproksi sitemap turunan ${requestedPath}: ${error.message}`);
        
        res.header('Content-Type', 'application/xml');
        res.status(404).send('<error>Sitemap not found or blocked.</error>');
    }
});


// ------------------------------------------
// RSS FEED
// ------------------------------------------
router.get('/rss', async (req, res) => {
    const urls = await fetchUrlsForRss();

    let rss = '<?xml version="1.0" encoding="UTF-8"?>\n';
    rss += '<rss version="2.0">\n';
    rss += '<channel>\n';
    rss += `  <title>${process.env.PROXY_TITLE || 'Komik Proxy Service Updates'}</title>\n`;
    rss += `  <link>${proxyUrl}/</link>\n`;
    rss += `  <description>Pembaruan komik terbaru dari ${proxyUrl}.</description>\n`;
    rss += '  <language>id-id</language>\n';
    rss += `  <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>\n`;

    urls.forEach((item) => {
        rss += '<item>\n';
        rss += `  <title>${item.title}</title>\n`;
        rss += `  <link>${item.loc}</link>\n`;
        rss += `  <pubDate>${item.pubDate}</pubDate>\n`;
        rss += `  <guid>${item.loc}</guid>\n`;
        rss += '</item>\n';
    });

    rss += '</channel>\n';
    rss += '</rss>';

    res.header('Content-Type', 'application/rss+xml');
    res.send(rss);
});

module.exports = router;