const filterList = [
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.amazon.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.apple.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.huawei.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.winoffice.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.samsung.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.tiktok.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.tiktok.extended.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.lgwebos.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.vivo.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.oppo-realme.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/native.xiaomi.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/fake.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/popupads.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/tif.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/tif-ips.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/pro.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/dyndns.txt",
    "https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@main/adblock/hoster.txt",
]

const cacheFetchWorker = new Worker("./cacheFetch.ts");

const cacheFetch = async (url: string): Promise<string> => {
    return new Promise((resolve, reject) => {
        cacheFetchWorker.onmessage = (event) => {
            resolve(event.data);
        }

        cacheFetchWorker.onerror = (event) => {
            reject(event.error);
        }

        cacheFetchWorker.postMessage(url);
    })
}




const updateList = async () => {
    let rules: string[] = [];

    for (const filter of filterList) {
        let list = await cacheFetch(filter);

        list = list.replace("[Adblock Plus]", '').trim();
        list = list.replace(/^!.*$/gm, '').trim();

        const listArray = list.split('\n')

        rules = rules.concat(listArray)
    }

    rules = Array.from(new Set(rules));

    Bun.write(Bun.file("./cache/combined.txt.gz"), Bun.gzipSync(makeComment(rules.length) + rules.join('\n')));

    console.log("Updated list @", new Date().toUTCString())
}

const updateListInterval = setInterval(updateList, 90e4) // Every 15 minutes

Bun.serve({
    async fetch(request, server) {
        if (new URL(request.url).pathname !== "/") {
            return new Response(null, { status: 404 });
        }

        return new Response(Bun.file("./cache/combined.txt.gz"), {
            headers: {
                "Content-Type": "text/plain",
                "Content-Encoding": "gzip"
            }
        })
    },
    idleTimeout: 1
})

const makeComment = (ruleCount: number) => {
    const now = new Date();

    const second = now.getSeconds();
    const minute = now.getMinutes();
    const hour = now.getHours();
    const day = now.getDate();
    const month = now.getMonth() + 1;
    const year = now.getFullYear();

    return `[Adblock Plus]
! Title: Combined List
! Description: DNS blocklists, one list, duplicates removed.
! Expires: 1 hour
! Last Modified: ${new Date().toUTCString().split(", ")[1]}
! Version: ${year}.${month}.${day}.${hour}.${minute}.${second}
! Syntax: AdBlock
! Number of Entries: ${ruleCount}\n`
}

await updateList();