import tomllib
from typing import Any, Self


class Config:
    def __init__(self, data: dict) -> None:
        self.config = data

    @staticmethod
    def from_file(path: str):
        try:
            with open(path, "rb") as f:
                cfg = tomllib.load(f)
            return Config(cfg)
        except (FileNotFoundError, tomllib.TOMLDecodeError) as e:
            raise ValueError(
                f"Unable to load configuration file {path!r}; does it exist?"
            ) from e

    def lookup(self, key: str) -> Any:
        """Perform nested lookup, returning a KeyError on failure."""
        subconfig = self.config
        for subkey in key.split("."):
            try:
                subconfig = subconfig[subkey]
            except KeyError as e:
                raise KeyError(f"Configuration item {key!r} is missing.") from e
        return subconfig

    def subconfig(self, key: str) -> Self:
        cfg = self.lookup(key)
        if not isinstance(cfg, dict):
            raise KeyError(f"Configuration item {key!r} is not a subconfig.")
        return Config(cfg)
