import requests

from ...CommonFunctions import dearmor_pgp_key
from ..Playbooks.Playbook import PlaybookCredentialCollection, FileCleanupTask
from ...Logging.Logger import log, Severity
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION
from ..SetupStep import SetupStep

class ApplyRepositoryKey(SetupStep):
    def __init__(self, key_url: str, keyring_path: str):
        super().__init__()
        self.key_url = key_url
        self.keyring_path = keyring_path

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        machine = MACHINE_COLLECTION.backup
        log(f'Downloading key from {self.key_url}', Severity.INFO)
        response = requests.get(self.key_url)
        if response.status_code != 200:
            log(f"Unable to download key at {self.key_url}", Severity.ERROR)
            return False

        log(f"File downloaded", Severity.DEBUG)

        key = dearmor_pgp_key(response.content)

        machine.write_file(self. keyring_path, key)
        return True