import os
import tomllib
import tomli_w
from enum import Enum
from pathlib import Path

from sunwaee.core.logger import get_logger

_log = get_logger("config")

_DEFAULT_CONFIG: dict = {
    "workspaces": {
        "default": "personal",
        "base_dir": "~/sunwaee/workspaces",
    }
}


class Caller(str, Enum):
    HUMAN = "human"
    API = "api"
    SUN = "sun"


def _config_dir() -> Path:
    return Path(os.environ.get("SUNWAEE_CONFIG_DIR", Path.home() / ".sunwaee"))


def _config_file() -> Path:
    return _config_dir() / "config.toml"


def get_caller() -> Caller:
    val = os.environ.get("SUNWAEE_CALLER", "human").lower()
    try:
        return Caller(val)
    except ValueError:
        return Caller.HUMAN


def is_machine_caller() -> bool:
    return get_caller() in (Caller.API, Caller.SUN)


def _load_config() -> dict:
    cfg_dir = _config_dir()
    cfg_file = _config_file()
    if not cfg_file.exists():
        _log.info("Config file not found, creating default at %s", cfg_file)
        cfg_dir.mkdir(parents=True, exist_ok=True)
        with open(cfg_file, "wb") as f:
            tomli_w.dump(_DEFAULT_CONFIG, f)
    _log.debug("Loading config from %s", cfg_file)
    with open(cfg_file, "rb") as f:
        return tomllib.load(f)


def _save_config(cfg: dict) -> None:
    cfg_dir = _config_dir()
    cfg_dir.mkdir(parents=True, exist_ok=True)
    _log.debug("Saving config to %s", _config_file())
    with open(_config_file(), "wb") as f:
        tomli_w.dump(cfg, f)


def get_workspaces_base_dir() -> Path:
    env = os.environ.get("SUNWAEE_WORKSPACES_DIR")
    if env:
        return Path(env).expanduser()
    cfg = _load_config()
    return Path(cfg.get("workspaces", {}).get("base_dir", "~/sunwaee/workspaces")).expanduser()


def get_default_workspace() -> str:
    env = os.environ.get("SUNWAEE_WORKSPACE")
    if env:
        return env
    cfg = _load_config()
    return cfg.get("workspaces", {}).get("default", "personal")


def set_default_workspace(name: str) -> None:
    _log.info("Setting default workspace to %r", name)
    cfg = _load_config()
    cfg.setdefault("workspaces", {})["default"] = name
    _save_config(cfg)


def get_module_dir(workspace: str, module: str) -> Path:
    """Return the directory for a given module within a workspace."""
    return get_workspaces_base_dir() / workspace / module
