"""
Extra, independent code, merely arbitrarily stuffed here

This is not part of mini-buildd.

"""

import urllib.request

import bs4


class DebianPackageTracker():
    """
    Get (some) source package information from the Debian Package Tracker

    As long as there is no proper API, we do this the
    hacky way parsing the HTML via bs4 - so this will most
    definitely break at some point. Use at own discretion.
    """

    def __init__(self, src_package, tracker_url="https://tracker.debian.org"):
        self.info = {}

        pkg_url = f"{tracker_url}/pkg/{src_package}"
        with urllib.request.urlopen(pkg_url) as response:
            soup = bs4.BeautifulSoup(response.read(), features="html.parser")
            version_tags = soup.findAll("span", {"class": "versions-repository"})
            for d in version_tags:
                codename = d['title'].split("(")[1].split(" ")[0].translate({ord(")"): None})
                version = d.find_next_sibling("a").get_text("", strip=True)
                version_url = version.replace("~", "").replace("+", "")
                self.info[codename] = {
                    "version": version,
                    "changelog_url": f"{tracker_url}/media/packages/{src_package[:4] if src_package.startswith('lib') else src_package[0]}/{src_package}/changelog-{version_url}"
                }

    def get_info(self, codename):
        return self.info[codename]

    def get_version(self, codename):
        return self.info[codename]["version"]
