import dataclasses
import pathlib
from dataclasses import dataclass, field
from pathlib import Path

import dacite
import toml
from r.utils import UserError


@dataclass
class Config:
    remote: str
    rsync_excludes: list[str] = field(default_factory=list)


@dataclass
class Context:
    config: Config
    root_directory: Path


def _find_config_file() -> Path | None:
    path = pathlib.Path().resolve()

    for i in [path, *path.parents]:
        config_file_path = i / 'r.toml'

        if config_file_path.is_file():
            return config_file_path

    return None


_dacite_config = dacite.Config(strict=True)


def load_config() -> Context:
    path = _find_config_file()

    if path is None:
        raise UserError(
            'No config file `r.toml\' found in the current directory or any of '
            'its parents.')

    config = dacite.from_dict(Config, toml.load(path), _dacite_config)

    return Context(config, path.parent)


def write_config(path: Path, config: Config):
    with path.open('w', encoding='utf-8') as file:
        toml.dump(dataclasses.asdict(config), file)
