from __future__ import annotations

from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from importlib import resources
from typing import Any, Dict

from analogai.foundation.common.utils.config_validator import validate_settings


_DEFAULT_SCHEMA_PATH = resources.files("analogai.foundation.config") / "schema.yaml"


@dataclass
class ConfigBase:
    settings: object
    schema_path: str | Path = _DEFAULT_SCHEMA_PATH
    _overrides: Dict[str, Any] = field(default_factory=dict, init=False, repr=False)

    def __post_init__(self) -> None:
        validate_settings(self.settings, self.schema_path)

    def get(self, key: str, default: Any = None) -> Any:
        if key in self._overrides:
            return self._overrides[key]
        return self.settings.get(key, default)

    @contextmanager
    def override(self, **kwargs: Any):
        old: Dict[str, Any] = {}
        for k, v in kwargs.items():
            old[k] = self._overrides.get(k, None)
            self._overrides[k] = v
        try:
            yield
        finally:
            for k in kwargs:
                if k in old and old[k] is not None:
                    self._overrides[k] = old[k]
                else:
                    self._overrides.pop(k, None)
