from pathlib import Path

import pytest

from machine_backup.config import ConfigError, load_config


def test_missing_file_gives_defaults(tmp_path):
    cfg = load_config(tmp_path / "absent.toml")
    assert cfg.destination == Path("~/Backups/machine").expanduser()
    assert cfg.keep_snapshots == 7
    assert cfg.log_keep == 20
    assert cfg.age_recipient is None
    assert cfg.age_identity is None
    assert cfg.remote_target is None


def test_full_file_parsed(tmp_path):
    f = tmp_path / "config.toml"
    f.write_text(
        '[backup]\ndestination = "~/Autre"\nkeep = 3\n'
        '[age]\nrecipient = "age1abc"\nidentity = "~/id.txt"\n'
        '[remote]\ntarget = "user@host:/backups"\n'
        "[logs]\nkeep = 5\n"
    )
    cfg = load_config(f)
    assert cfg.destination == Path("~/Autre").expanduser()
    assert cfg.keep_snapshots == 3
    assert cfg.log_keep == 5
    assert cfg.age_recipient == "age1abc"
    assert cfg.age_identity == Path("~/id.txt").expanduser()
    assert cfg.remote_target == "user@host:/backups"


def test_empty_remote_target_is_none(tmp_path):
    f = tmp_path / "c.toml"
    f.write_text('[remote]\ntarget = ""\n')
    assert load_config(f).remote_target is None


def test_unknown_keys_are_ignored(tmp_path):
    f = tmp_path / "c.toml"
    f.write_text('[backup]\nkeep = 2\nfuturiste = true\n[inconnu]\nx = 1\n')
    assert load_config(f).keep_snapshots == 2


def test_invalid_toml_raises(tmp_path):
    f = tmp_path / "c.toml"
    f.write_text("[[[")
    with pytest.raises(ConfigError):
        load_config(f)
