from __future__ import annotations

from pathlib import Path

import pytest

import runtime_paths


def test_defaults_to_the_dotdir_under_home(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.delenv(runtime_paths.RUNTIME_DIR_ENV, raising=False)
    monkeypatch.setenv("HOME", str(tmp_path))
    assert runtime_paths.runtime_dir() == tmp_path / ".local/state/overdeck/systray/runtime"


def test_default_resolves_private_overdeck_compat_symlink(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.delenv(runtime_paths.RUNTIME_DIR_ENV, raising=False)
    monkeypatch.setenv("HOME", str(tmp_path))
    target = tmp_path / ".overdeck"
    target.mkdir()
    compat = tmp_path / ".local/state/overdeck"
    compat.parent.mkdir(parents=True)
    compat.symlink_to(target, target_is_directory=True)

    assert runtime_paths.runtime_dir() == target / "systray/runtime"


def test_env_override_wins(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv(runtime_paths.RUNTIME_DIR_ENV, str(tmp_path / "elsewhere"))
    assert runtime_paths.runtime_dir() == tmp_path / "elsewhere"


def test_env_override_expands_user(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("HOME", str(tmp_path))
    monkeypatch.setenv(runtime_paths.RUNTIME_DIR_ENV, "~/state")
    assert runtime_paths.runtime_dir() == tmp_path / "state"


def test_empty_override_falls_back_to_the_default(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("HOME", str(tmp_path))
    monkeypatch.setenv(runtime_paths.RUNTIME_DIR_ENV, "")
    assert runtime_paths.runtime_dir() == tmp_path / ".local/state/overdeck/systray/runtime"


def test_compat_link_defaults_to_the_retired_name(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.delenv(runtime_paths.COMPAT_LINK_ENV, raising=False)
    monkeypatch.setenv("HOME", str(tmp_path))
    assert runtime_paths.compat_link() == tmp_path / ".systray-ai"


def test_compat_link_env_override_wins(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("HOME", str(tmp_path))
    monkeypatch.setenv(runtime_paths.COMPAT_LINK_ENV, "~/legacy")
    assert runtime_paths.compat_link() == tmp_path / "legacy"


def test_no_module_constructs_the_state_dir_outside_the_accessor() -> None:
    root = Path(runtime_paths.__file__).resolve().parent
    markers = (".local/state/overdeck/systray/runtime", ".systray-ai")
    offenders = [
        path.name
        for path in sorted(root.glob("*.py"))
        if path.name != "runtime_paths.py"
        and any(marker in path.read_text(encoding="utf-8") for marker in markers)
    ]
    assert offenders == []
