import logging
from pathlib import Path

from magnus import defaults
from magnus.integration import BaseIntegration

logger = logging.getLogger(defaults.NAME)


class LocalComputeS3RunLogStore(BaseIntegration):
    """
    Local compute and File system run log store
    """
    mode_type = 'local'
    service_type = 'run_log_store'  # One of secret, catalog, datastore
    service_provider = 's3'  # The actual implementation of the service

    def validate(self, **kwargs):
        if self.executor._is_parallel_execution():
            msg = (
                'Run log generated by s3 run log store are not thread safe. '
                'Inconsistent results are possible because of race conditions to write to the same file.\n'
                'Consider using partitioned run log store like database for consistent results.'

            )
            logger.warning(msg)


class LocalContainerComputeS3Store(BaseIntegration):
    """
    Integration between local container and S3 run log store
    """
    mode_type = 'local-container'
    service_type = 'run-log-store'  # One of secret, catalog, datastore
    service_provider = 's3'  # The actual implementation of the service

    def validate(self, **kwargs):
        if self.executor._is_parallel_execution():
            msg = (
                'Run log generated by s3 run log store are not thread safe. '
                'Inconsistent results are possible because of race conditions to write to the same file.\n'
                'Consider using partitioned run log store like database for consistent results.'

            )
            logger.warning(msg)

    def configure_for_traversal(self, **kwargs):
        write_to = self.service.get_aws_credentials_file()
        self.executor.volumes[str(Path(write_to).resolve())] = {
            'bind': '/root/.aws/credentials',
            'mode': 'ro'
        }
