from pathlib import Path

from awspipe.paths import database_path, ensure_app_home


def test_database_path_uses_awspipe_home(monkeypatch) -> None:
    monkeypatch.setenv("AWSPIPE_HOME", "C:/tmp/awspipe-home")

    assert str(database_path()).endswith("awspipe-home\\awspipe.duckdb") or str(database_path()).endswith("awspipe-home/awspipe.duckdb")


def test_ensure_app_home_falls_back_to_workspace(monkeypatch, tmp_path) -> None:
    blocked = tmp_path / "blocked"
    fallback = tmp_path / ".awspipe"
    original_mkdir = Path.mkdir

    def patched_mkdir(self, parents=False, exist_ok=False):
        if self == blocked:
            raise PermissionError("denied")
        return original_mkdir(self, parents=parents, exist_ok=exist_ok)

    monkeypatch.setattr("awspipe.paths.app_home", lambda: blocked)
    monkeypatch.chdir(tmp_path)
    monkeypatch.setattr(Path, "mkdir", patched_mkdir)

    path = ensure_app_home()

    assert path == fallback
    assert fallback.exists()
