import tvmauth
from typing import Dict, List

from library.python.vault_client.instances import Production as VaultClient

from saas.library.python.abc import AbcAPI
from saas.library.python.saas_ctype import SaasCtype
from saas.library.python.token_store import PersistentTokenStore
from saas.tools.devops.canary.reader.configs import AppConfig


class TvmClient:
    def __init__(self, config: AppConfig, saas_ctypes: List[SaasCtype]):
        self._ctype_to_tvm_id: Dict[str, int] = {
            saas_ctype.name: int(saas_ctype.environment.get('TVM_SERVICE_ID', saas_ctype.saas_debug_proxy_tvm_id))
            for saas_ctype in saas_ctypes
        }
        self._client: tvmauth.TvmClient = tvmauth.TvmClient(tvmauth.TvmApiClientSettings(
            self_tvm_id=config.saas_tvm_id,
            self_secret=self._load_tvm_secret(config.saas_tvm_id, config.saas_abc_group_id),
            dsts=list(self._ctype_to_tvm_id.values()),
        ))

    @staticmethod
    def _load_tvm_secret(tvm_id: int, abc_group: int) -> str:
        meta_info = AbcAPI().get_tvm_meta_info(tvm_id, abc_group)

        yav_secret_id = meta_info['secret_uuid']
        yav_token = PersistentTokenStore.get_token_from_store_env_or_file('yav')
        yav_client = VaultClient(authorization=f'OAuth {yav_token}', decode_files=True)

        version = yav_client.get_version(yav_secret_id)
        return version['value']['client_secret']

    def get_service_ticket(self, ctype: str) -> str:
        if not self._ctype_to_tvm_id.get(ctype):
            raise ValueError(f'Undefined ctype {ctype}, no tvm_id can be found')

        return self._client.get_service_ticket_for(tvm_id=self._ctype_to_tvm_id[ctype])
