"""Tests for abreka.config."""

import pytest

from abreka.config import discover_project, find_abreka_dir, load_config, save_config
from abreka.errors import ConfigNotFoundError
from abreka.models import Config, ProjectConfig


class TestDiscoverProject:
    def test_discovers_from_pyproject(self, tmp_project):
        name, lib = discover_project(tmp_project)
        assert name == "test-project"
        assert lib == "test_project"

    def test_missing_pyproject(self, tmp_path):
        with pytest.raises(ConfigNotFoundError):
            discover_project(tmp_path)

    def test_fallback_lib_name(self, tmp_path):
        (tmp_path / "pyproject.toml").write_text(
            '[project]\nname = "my-tool"\nversion = "0.1.0"\n'
        )
        name, lib = discover_project(tmp_path)
        assert name == "my-tool"
        assert lib == "my_tool"  # hyphen replaced


class TestFindAbrekaDir:
    def test_finds_in_current(self, abreka_project):
        result = find_abreka_dir(abreka_project)
        assert result == abreka_project / "abreka"

    def test_finds_from_subdirectory(self, abreka_project):
        subdir = abreka_project / "src" / "test_project"
        result = find_abreka_dir(subdir)
        assert result == abreka_project / "abreka"

    def test_not_found(self, tmp_path):
        with pytest.raises(ConfigNotFoundError):
            find_abreka_dir(tmp_path)


class TestConfigLoadSave:
    def test_round_trip(self, abreka_project):
        abreka_dir = abreka_project / "abreka"
        config = load_config(abreka_dir)
        assert config.project.name == "test-project"
        assert config.project.lib == "test_project"

        config.project.name = "modified"
        save_config(config, abreka_dir)
        reloaded = load_config(abreka_dir)
        assert reloaded.project.name == "modified"
