import sys
from pathlib import Path

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib

DEFAULT_CONFIG = {"api": {"api_url": "127.0.0.1:4510"}}


class Config:
    def __init__(self):
        self.config_dir = Path.home() / ".sai"
        self.config_file = self.config_dir / "rlmesh.toml"
        self.config = self._load_config()

    def _create_default_config(self):
        self.config_dir.mkdir(parents=True, exist_ok=True)

        with open(self.config_file, "w") as f:
            toml_str = "[api]\n"
            toml_str += f'api_url = "{DEFAULT_CONFIG["api"]["api_url"]}"\n'
            f.write(toml_str)

    def _load_config(self):
        if not self.config_file.exists():
            self._create_default_config()
            return DEFAULT_CONFIG

        with open(self.config_file, "rb") as f:
            user_config = tomllib.load(f)

        merged_config = DEFAULT_CONFIG.copy()
        if "api" in user_config:
            merged_config["api"].update(user_config["api"])

        return merged_config

    @property
    def api_url(self):
        return self.config["api"]["api_url"]


config = Config()
