from flask import current_app
from github import Github

from app.terraform.block.bridge_reachability import BlockBridgeReachabilityAutomation


class BlockBridgeGitHubAutomation(BlockBridgeReachabilityAutomation):
    """
    Automation task to import bridge reachability results from GitHub.
    """

    short_name = "block_bridge_github"
    description = "Import bridge reachability results from GitHub"
    frequency = 30

    def fetch(self) -> None:
        github = Github(current_app.config['GITHUB_API_KEY'])
        repo = github.get_repo(current_app.config['GITHUB_BRIDGE_REPO'])
        for vantage_point in current_app.config['GITHUB_BRIDGE_VANTAGE_POINTS']:
            contents = repo.get_contents(f"recentResult_{vantage_point}")
            if isinstance(contents, list):
                raise RuntimeError(
                    f"Expected a file at recentResult_{vantage_point}"
                    " but got a directory.")
            self._lines = contents.decoded_content.decode('utf-8').splitlines()
