from dataclasses import dataclass
from os import getenv
from pathlib import Path

from csirtmu.core.dataclass_config_loader import load_dataclass_config

BASE_DIR = Path(__file__).parent.parent.parent
ENV_PREFIX = "CSIRTMU_RT_EMAIL_PARSER"


@dataclass
class PerunSyncConfig:
    url: str
    token: str | None

    @property
    def auth_headers(self) -> dict[str, str]:
        if self.token is None or self.token.strip() == "":
            return {}
        return {"Authorization": f"Token {self.token}"}


@dataclass(unsafe_hash=True)
class Config:
    perun_sync: PerunSyncConfig
    address: str


class AppConfig:
    _config: Config | None = None

    @classmethod
    def get(cls, config_path: Path | None = None) -> Config:
        if cls._config is None:
            if config_path is None:  # pragma: no cover
                config_path = Path(
                    getenv(
                        ENV_PREFIX + "_CONFIG_PATH",
                        (BASE_DIR / "config/config.yaml").resolve(),
                    )
                )
            cls._config = load_dataclass_config(config_path, Config, ENV_PREFIX)
        return cls._config
