from biolib import utils
from biolib.biolib_api_client import BiolibApiClient
from biolib.biolib_api_client.biolib_job_api import BiolibJobApi
from biolib.biolib_binary_format import UnencryptedModuleOutput
from biolib.biolib_logging import logger
from biolib.compute_node.job_worker.executors.types import RemoteExecuteOptions

from biolib.compute_node.job_worker.job_storage import JobStorage
from biolib.jobs import Job


class RemoteExecutor:

    @staticmethod
    def execute_job(options: RemoteExecuteOptions, module_input_serialized: bytes) -> UnencryptedModuleOutput:
        job_id = options['job']['public_id']
        JobStorage.upload_module_input(
            job=options['job'],
            module_input_serialized=module_input_serialized
        )
        cloud_job = BiolibJobApi.create_cloud_job(job_id=job_id, result_name_prefix=options['result_name_prefix'])
        logger.debug(f"Cloud: Job created with id {cloud_job['public_id']}")

        if utils.IS_RUNNING_IN_NOTEBOOK:
            utils.STREAM_STDOUT = True

        app_version = options['job']['app_version']
        enable_print = bool(
            utils.STREAM_STDOUT and
            (app_version.get('main_output_file') or app_version.get('stdout_render_type') == 'text')
        )
        job = Job.create_from_uuid(
            uuid=options['job']['public_id'],
            auth_token=options['job']['auth_token']
        )
        job._stream_logs(enable_print)  # pylint: disable=protected-access

        BiolibApiClient.refresh_auth_token()
        return JobStorage.get_module_output(job=options['job'])
