from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

from savcfg.read import VarsReader
from savcfg.edit import VarsEditor


class KeyVaultVars(VarsReader, VarsEditor):
    """Implementation of keys readers using Azure KeyVault"""

    def __init__(
        self,
        kv_name: str,
        credential: DefaultAzureCredential,
        word_separator: str = "_",
        uppercase: bool = False,
    ):
        url = f"https://{kv_name}.vault.azure.net/"
        self._secrets = SecretClient(url, credential)
        self._vars = []
        self._sep = word_separator
        self._upper = uppercase

    def _normalize(self, key: str) -> str:
        if self._upper:
            key = key.upper()
        return key.replace("--", ".").replace("-", self._sep)

    def _denormalize(self, key: str) -> str:
        if self._upper:
            key = key.lower()
        return key.replace(".", "--").replace(self._sep, "-")

    def list_vars(self) -> list[str]:
        if not self._vars:
            self._vars = sorted(
                [
                    self._normalize(key.name)
                    for key in self._secrets.list_properties_of_secrets()
                    if key is not None and key.name is not None
                ],
                key=lambda x: x,
            )

        return self._vars

    def read(self, key: str) -> str:
        if not self._vars:
            self.list_vars()

        if key not in self._vars:
            return ""

        value = self._secrets.get_secret(self._denormalize(key)).value
        if not value:
            return ""

        return value

    def write(self, key: str, value: str):
        self._secrets.set_secret(self._denormalize(key), value)
