# ABOUTME: Configuration loading from moongreet.toml.
# ABOUTME: Parses appearance and behavior settings for the greeter.

import tomllib
from dataclasses import dataclass
from pathlib import Path

DEFAULT_CONFIG_PATHS = [
    Path("/etc/moongreet/moongreet.toml"),
]


@dataclass
class Config:
    """Greeter configuration loaded from moongreet.toml."""

    background: Path | None = None


def load_config(config_path: Path | None = None) -> Config:
    """Load configuration from a TOML file.

    Relative paths in the config are resolved against the config file's directory.
    """
    if config_path is None:
        for path in DEFAULT_CONFIG_PATHS:
            if path.exists():
                config_path = path
                break
        if config_path is None:
            return Config()

    if not config_path.exists():
        return Config()

    with open(config_path, "rb") as f:
        data = tomllib.load(f)

    config = Config()
    appearance = data.get("appearance", {})

    bg = appearance.get("background")
    if bg:
        bg_path = Path(bg)
        if not bg_path.is_absolute():
            bg_path = config_path.parent / bg_path
        config.background = bg_path

    return config
