"""Tests for gri_utils.config module."""

import time
from pathlib import Path

import pytest

from gri_utils.config import config


@pytest.fixture(autouse=True)
def reset_config():
    """Reset config state before and after each test."""
    config._reset_for_testing()
    yield
    config._reset_for_testing()


@pytest.fixture
def config_file(tmp_path: Path) -> Path:
    """Create a temporary config file."""
    config_path = tmp_path / "config.toml"
    config_path.write_text("""
[gri-terrain]
max_memory_cache_mb = 1000.0
interpolation = "bicubic"

[gri-terrain.copernicus]
cache_dir = "~/.cache/gri/terrain/copernicus"

[gri-tropo]
n_sur_dir = "/data/tropo/n_sur"
""")
    return config_path


def test_get_returns_configured_values(config_file: Path) -> None:
    """Config loads and returns values from TOML file."""
    config.set_config_path(config_file)

    assert config.get("gri-terrain.max_memory_cache_mb") == 1000.0
    assert config.get("gri-terrain.interpolation") == "bicubic"
    assert config.get("gri-terrain.copernicus.cache_dir").endswith(
        ".cache/gri/terrain/copernicus",
    )


def test_get_returns_default_for_missing_key(tmp_path: Path) -> None:
    """Missing keys return default (None if not specified)."""
    empty_config = tmp_path / "empty.toml"
    empty_config.write_text("")
    config.set_config_path(empty_config)

    assert config.get("nonexistent.key") is None
    assert config.get("nonexistent.key", "fallback") == "fallback"


def test_get_path_returns_path_object(config_file: Path) -> None:
    """get_path returns Path objects with tilde expansion."""
    config.set_config_path(config_file)

    result = config.get_path("gri-tropo.n_sur_dir")
    assert isinstance(result, Path)
    assert result == Path("/data/tropo/n_sur")

    # Tilde expansion
    result = config.get_path("gri-terrain.copernicus.cache_dir")
    assert isinstance(result, Path)
    assert not str(result).startswith("~")


def test_set_creates_override(config_file: Path) -> None:
    """set() creates in-memory override that takes precedence."""
    config.set_config_path(config_file)

    assert config.get("gri-terrain.max_memory_cache_mb") == 1000.0
    config.set("gri-terrain.max_memory_cache_mb", 2000.0)
    assert config.get("gri-terrain.max_memory_cache_mb") == 2000.0


def test_reload_on_file_change(config_file: Path) -> None:
    """Config auto-reloads when file mtime changes."""
    config.set_config_path(config_file)
    assert config.get("gri-terrain.max_memory_cache_mb") == 1000.0

    time.sleep(0.1)  # Ensure mtime changes
    config_file.write_text("""
[gri-terrain]
max_memory_cache_mb = 500.0
""")

    assert config.get("gri-terrain.max_memory_cache_mb") == 500.0


def test_missing_config_file_uses_empty_config(tmp_path: Path) -> None:
    """Missing config file results in empty config, not error."""
    nonexistent = tmp_path / "nonexistent.toml"
    config.set_config_path(nonexistent)

    assert config.get("any.key", "default") == "default"
