from __future__ import annotations

import platform
from pathlib import Path
from typing import Any, Final

from dopt_basics import configs, io

from pycage.types import OsInfo


class LazyConfigLoader:
    def __init__(
        self,
        cfg_path: Path,
    ) -> None:
        if not cfg_path.exists():
            raise FileNotFoundError(f"Config path does not seem to exist: {cfg_path}")

        self.cfg_path = cfg_path
        self._cfg: dict[str, Any] | None = None

    def _load_config(self) -> None:
        self._cfg = configs.load_toml(self.cfg_path)

    def __getitem__(
        self,
        key: str,
    ) -> Any:
        if self._cfg is None:
            self._load_config()

        assert self._cfg is not None, "tried to access not loaded config"
        return self._cfg[key]


class PycageConfigLoader(LazyConfigLoader):
    def __init__(
        self,
        cfg_path: Path,
    ) -> None:
        super().__init__(cfg_path)
        self._os_info: OsInfo | None = None

    @property
    def os_info(self) -> OsInfo:
        if self._os_info is None:
            self._os_info = _parse_os_info(self)

        return self._os_info


def _parse_os_info(
    cfg: PycageConfigLoader,
) -> OsInfo:
    system = platform.system()

    os_file_info: OsInfo
    match system:
        case "Windows":
            os_file_info = OsInfo(**cfg["platforms"]["win"])
        case _:
            raise NotImplementedError(f"Platform {system} not implemented yet.")

    return os_file_info


cfg_path = io.search_file_iterative(
    Path(__file__), glob_pattern="config.toml", stop_folder_name="pycage"
)
assert cfg_path is not None, "static config path not found"
CFG: Final[PycageConfigLoader] = PycageConfigLoader(cfg_path)
