from dataclasses import dataclass
import re
from typing import Protocol

from dynamix_sdk.utils import F_DECORATOR


@dataclass(kw_only=True)
class Config:
    url: str
    base_api_path: str = ''
    verify_ssl: bool
    http503_attempts: int = 10
    http503_attempts_interval: int = 5
    result_extra_allow: bool = False
    wrap_request_exceptions: bool = False
    f_decorators: list[F_DECORATOR] | None = None

    def get_api_url(self, api_path: str):
        substitutions = re.findall(r'\[\w+\]', api_path)
        _api_path = api_path[:]
        for s in substitutions:
            attr_name = f'{s.strip("[]")}'
            attr_value = getattr(self, attr_name)
            _api_path = _api_path.replace(s, attr_value)

        return f'{self.url}{self.base_api_path}{_api_path}'


class AuthenticatorProtocol(Protocol):
    def get_jwt(self) -> str:
        ...


@dataclass(kw_only=True)
class ConfigWithAuth(Config):
    auth: str | AuthenticatorProtocol

    @property
    def jwt(self):
        if isinstance(self.auth, str):
            return self.auth
        else:
            return self.auth.get_jwt()


@dataclass(kw_only=True)
class BaseConfigWithDomain(Config):
    domain: str
