from qutebrowser.api import interceptor

c.url.searchengines = {
    "sci": "https://sci-hub.ru/{}",
    "DEFAULT": "https://search.martyoeh.me/?q={}",
    "al": "https://wiki.archlinux.org/index.php/{}",
    "alt": "https://alternativeto.net/software/{}/?license=opensource",
    "aur": "https://aur.archlinux.org/packages/?K={}",
    "d": "https://www.dict.cc/?s={}",
    "ddg": "https://duckduckgo.com/?q={}",
    "docker": "https://hub.docker.com/search?q={}",
    "dt": "https://www.deepl.com/translator#en/de/{}",
    "g": "https://www.google.com/search?q={}",
    "gh": "https://github.com/search?q={}",
    "gol": "https://golang.org/pkg/{}/",
    "gt": "https://translate.google.com/#auto/de/{}",
    "hn": "https://hn.algolia.com/?q={}",
    "kb": "https://soeg.kb.dk/discovery/search?query=any,contains,{}&lang=en",
    "l": "https://links.martyoeh.me/?searchterm={}&searchtags=",
    "lib": "http://libgen.fun/search.php?req={}",
    "man": "https://manned.org/browse/search?q={}",
    "maps": "https://www.qwant.com/maps/?q={}",
    "pcw": "https://www.pcgamingwiki.com/w/index.php?search={}",
    "r": "https://www.reddit.com/r/{}",
    "t": "https://www.thesaurus.com/browse/{}",
    "w": "https://en.wikipedia.org/w/index.php?search={}",
    "yt": "https://www.youtube.com/results?search_query={}",
}
c.url.default_page = "https://start.duckduckgo.com"
c.url.start_pages = ["https://start.duckduckgo.com"]

redirects = {
    "reddit.com": "teddit.net",
    "www.reddit.com": "teddit.net",
    "youtube.com": "yewtu.be",
    "www.youtube.com": "www.yewtu.be",
    "twitter.com": "nitter.net",
    "www.twitter.com": "nitter.net",
    "instagram.com": "bibliogram.art",
    "www.instagram.com": "bibliogram.art",
    "wikipedia.org": "wikiless.org",
    "en.wikipedia.org": "wikiless.org",
    "medium.com": "scribe.rip",
}


def rewrite(request: interceptor.Request):
    if (
        request.resource_type != interceptor.ResourceType.main_frame
        or request.request_url.scheme() in {"data", "blob"}
    ):
        return

    url = request.request_url

    redir = redirects.get(url.host())
    if redir is not None and url.setHost(redir) is not False:
        try:
            request.redirect(url)
        except:
            pass


interceptor.register(rewrite)
