"""Config utilisateur : destination mémorisée et dernière sélection."""

from __future__ import annotations

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


@dataclass
class UserConfig:
    dest: str | None = None
    last_selection: list[str] = field(default_factory=list)


def config_path(home: Path) -> Path:
    return home / ".config" / "osx-backup" / "config.toml"


def load_user_config(home: Path) -> UserConfig:
    """Lit la config ; un fichier absent, illisible ou corrompu donne la config par défaut."""
    path = config_path(home)
    if not path.exists():
        return UserConfig()
    try:
        data = tomllib.loads(path.read_text(encoding="utf-8"))
    except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError):
        return UserConfig()
    dest = data.get("dest")
    selection = data.get("last_selection", [])
    return UserConfig(
        dest=str(dest) if dest else None,
        last_selection=[str(s) for s in selection] if isinstance(selection, list) else [],
    )


def save_user_config(home: Path, cfg: UserConfig) -> Path:
    path = config_path(home)
    path.parent.mkdir(parents=True, exist_ok=True)
    lines = ["# Généré par osx-backup"]
    if cfg.dest:
        lines.append(f"dest = {json.dumps(cfg.dest)}")
    lines.append(f"last_selection = {json.dumps(cfg.last_selection)}")
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return path
