import logging
import os
from pathlib import Path

import yaml
from yandextank.core.tankcore import JobsStorage

from load.projects.cloud.cloud_helper import metadata_compute as compute
from load.projects.cloud.tank_client.client import METADATA_AGENT_VERSION_ATTR, LoadTestingGRPCClient, TankApiClient
from load.projects.cloud.tank_client.service import TankClientService
from load.projects.cloud.tank_client.utils import LOGGING

MIN_SLEEP_TIME = 1
CONFIG_PATH = '/etc/tank_client/config.yaml'
METADATA_HOST_ATTR = 'server-host'
METADATA_PORT_ATTR = 'server-port'
METADATA_REQUEST_FREQUENCY = 'request-frequency'  # seconds
METADATA_LOGGING_HOST_ATTR = 'cloud-helper-logging-host'
METADATA_LOGGING_PORT_ATTR = 'cloud-helper-logging-port'
METADATA_OBJECT_STORAGE_URL_ATTR = 'cloud-helper-object-storage-url'
METADATA_LT_CREATED_ATTR = 'loadtesting-created'
JOBS_STORAGE_FILE_ENV = 'JOBS_STORAGE_FILE'

logging.config.dictConfig(LOGGING)
LOGGER = logging.getLogger('tank_client')


def main():
    config = yaml.safe_load(Path(CONFIG_PATH).read_text())

    LOGGER.info(f'Load config {config}')

    attrs = compute.get_instance_attributes() or {}
    load_testing_host = attrs.get(METADATA_HOST_ATTR, config.get("load_testing_host"))
    load_testing_port = attrs.get(METADATA_PORT_ATTR, config.get("load_testing_port"))
    insecure_connection = attrs.get('insecure-connection', False) == 'True'
    request_frequency = int(attrs.get(METADATA_REQUEST_FREQUENCY, 0))

    agent_version = attrs.get(METADATA_AGENT_VERSION_ATTR, '')

    object_storage_url = attrs.get(METADATA_OBJECT_STORAGE_URL_ATTR, config.get("object_storage_url"))
    instance_lt_created = attrs.get(METADATA_LT_CREATED_ATTR, False)

    loadtesting_client = LoadTestingGRPCClient(load_testing_host, load_testing_port, agent_version,
                                               config.get("agent_id_file"),
                                               object_storage_url, config.get("iam_token_service_url"),
                                               instance_lt_created,
                                               config.get("external_agent_config_path"),
                                               insecure_connection=insecure_connection)

    tank_api_client = TankApiClient(config['tankapi_host'], config['tankapi_port'])
    jobs_storage = JobsStorage(os.getenv(JOBS_STORAGE_FILE_ENV, config['storage_file']))

    sleep_time = max(request_frequency, MIN_SLEEP_TIME)
    logging_host = attrs.get(METADATA_LOGGING_HOST_ATTR, config.get("logging_host"))
    logging_port = attrs.get(METADATA_LOGGING_PORT_ATTR, config.get("logging_port"))

    tank_client = TankClientService(loadtesting_client, tank_api_client, jobs_storage, config['client_workdir'],
                                    sleep_time, logging_host, logging_port)

    tank_client.serve()
