import os
import tomllib
from pathlib import Path

from pymetropolis.metro_common import MetropyError

# MAIN_DIRECTORY = ConfigValue(
#     "main_directory",
#     "main_directory",
#     expected_type=Path(),
#     default="output/",
#     description="Directory where the files generated by pymetropolis will be stored.",
#     example='"paris/output/"',
#     note="If the directory does not exist, it will be created automatically.",
# )


class Config:
    main_directory: Path

    def __init__(self, d: dict):
        self.dict = d

    @classmethod
    def from_toml(cls, path: Path):
        """Initializes a Config from the path to a TOML file.

        Raises an exception if the given filename does not exist or is an invalid TOML file.
        """
        if not os.path.isfile(path):
            raise MetropyError("Cannot read config file: {}".format(os.path.abspath(path)))
        with open(path, "rb") as f:
            input_dict = tomllib.load(f)
        inst = cls(input_dict)
        inst.check_main_directory()
        return inst

    def check_main_directory(self):
        """Asserts that `main_directory` is properly defined and that the directory exists.

        If the directory does not exist, creates it.
        """
        main_dir = self.dict.get("main_directory")
        if main_dir is None:
            raise MetropyError("Missing `main_directory` in config")
        if not isinstance(main_dir, str):
            raise MetropyError(f"Config value `main_directory` should be a path, got `{main_dir}`")
        path = Path(main_dir)
        path.mkdir(exist_ok=True)
        self.main_directory = path
        # Also create the update_files/ directory if needed.
        update_files_path = path / "update_files"
        update_files_path.mkdir(exist_ok=True)
