"""Module for writing yera config toml."""

from pathlib import Path
from typing import Literal

import tomli_w

from yera.config2.dataclasses import YeraConfig


def _dump_config_object_to_dict(obj: YeraConfig) -> dict:
    """Un-flatten a YeraConfig object ready for serialisation.

    Args:
        obj: YeraConfig object to un-flatten

    Returns:
        Dictionary with nested model structure suitable for TOML

    """
    yera_config_dict = obj.model_dump(exclude_unset=True, exclude_none=True)

    models_categories = {}

    for model_type, models in yera_config_dict["models"].items():
        nested = {}

        for model_config in models.values():
            *parts, name = model_config.pop("id").split(".")
            head = nested
            for part in parts:
                if part not in head:
                    head[part] = {}
                head = head[part]
            head[name] = model_config

        models_categories[model_type] = nested

    yera_config_dict["models"] = models_categories

    return yera_config_dict


def write_config(
    yera_config: YeraConfig,
    location: Literal["global", "local"],
    exists_ok: bool,
) -> None:
    """Write a YeraConfig object to a yera.toml file.

    Args:
        yera_config: The configuration object to serialize and write.
        location: Where to write the config file. 'global' writes to
            ~/.config/yera/yera.toml, 'local' writes to ./yera.toml
            in the current working directory.
        exists_ok: If False, raises FileExistsError when a yera.toml
            already exists at the target location. If True, overwrites
            existing files.

    Raises:
        ValueError: If location is not 'global' or 'local'.
        FileExistsError: If a yera.toml already exists at the target
            path and exists_ok is False.

    Example:
        >>> config = YeraConfig(...)
        >>> write_config(config, location="local", exists_ok=False)
        # Creates ./yera.toml in current directory

    """
    if location == "global":
        path = Path.home() / ".config" / "yera"
    elif location == "local":
        path = Path.cwd()
    else:
        raise ValueError(f"Invalid location: {location}")

    path = path / "yera.toml"

    if path.exists() and not exists_ok:
        raise FileExistsError(f"A yera.toml file already exists at {path}")

    path.parent.mkdir(parents=True, exist_ok=True)

    config_dict = _dump_config_object_to_dict(yera_config)
    toml_content = tomli_w.dumps(config_dict)
    path.write_text(toml_content, encoding="utf-8")
