from typing import Tuple
from github import Github, GitReleaseAsset
from distyctl import constants, types
from distyctl.exceptions import BrokenFrameworkVersion


class GithubClient:
    def __init__(self):
        self.github_agent = Github()
        self.organization = self.github_agent.get_organization(
            constants.GH_ORGANIZATION_NAME
        )
        self.framework_repo = self.organization.get_repo(constants.FRAMEWORK_REPO)

    def get_latest_release_version(self) -> types.VersionLiteral:
        return self.list_releases()[0]

    def list_releases(self) -> Tuple[str, ...]:
        return tuple(map(lambda x: x.name, self.framework_repo.get_releases()))

    def get_framework_asset_by_version(
        self, version: types.VersionLiteral
    ) -> GitReleaseAsset.GitReleaseAsset:
        release = self.framework_repo.get_release(version)

        assets = release.get_assets()

        first_asset_page = assets.get_page(0)

        if len(first_asset_page) == 0:
            raise BrokenFrameworkVersion(
                version, reason="No assets are included in the release."
            )

        framework_asset = first_asset_page[0]

        return framework_asset
