"""Tests for home directory resolution."""

import os
from pathlib import Path
from unittest.mock import patch

import pytest

from scry_run.home import (
    get_home,
    get_config_path,
    get_apps_dir,
    get_app_dir,
    get_app_cache,
    get_app_logs,
    ensure_home_exists,
)


class TestGetHome:
    """Tests for get_home()."""

    def test_default_home(self):
        """Test default home is ~/.scry-run."""
        with patch.dict(os.environ, {}, clear=True):
            os.environ.pop("SCRY_HOME", None)
            home = get_home()
            assert home == Path.home() / ".scry-run"

    def test_env_override(self, tmp_path):
        """Test SCRY_HOME overrides default."""
        custom_home = tmp_path / "custom-home"
        with patch.dict(os.environ, {"SCRY_HOME": str(custom_home)}):
            home = get_home()
            assert home == custom_home


class TestPathHelpers:
    """Tests for path helper functions."""

    def test_get_config_path(self, tmp_path):
        """Test config path is home/config.toml."""
        with patch.dict(os.environ, {"SCRY_HOME": str(tmp_path)}):
            assert get_config_path() == tmp_path / "config.toml"

    def test_get_apps_dir(self, tmp_path):
        """Test apps dir is home/apps."""
        with patch.dict(os.environ, {"SCRY_HOME": str(tmp_path)}):
            assert get_apps_dir() == tmp_path / "apps"

    def test_get_app_dir(self, tmp_path):
        """Test app dir is home/apps/<name>."""
        with patch.dict(os.environ, {"SCRY_HOME": str(tmp_path)}):
            assert get_app_dir("todo-app") == tmp_path / "apps" / "todo-app"

    def test_get_app_cache(self, tmp_path):
        """Test app cache is home/apps/<name>/cache.json."""
        with patch.dict(os.environ, {"SCRY_HOME": str(tmp_path)}):
            assert get_app_cache("todo-app") == tmp_path / "apps" / "todo-app" / "cache.json"

    def test_get_app_logs(self, tmp_path):
        """Test app logs is home/apps/<name>/logs."""
        with patch.dict(os.environ, {"SCRY_HOME": str(tmp_path)}):
            assert get_app_logs("todo-app") == tmp_path / "apps" / "todo-app" / "logs"


class TestEnsureHomeExists:
    """Tests for ensure_home_exists()."""

    def test_creates_directories(self, tmp_path):
        """Test ensure_home_exists creates home and apps dirs."""
        home = tmp_path / ".scry-run"
        with patch.dict(os.environ, {"SCRY_HOME": str(home)}):
            ensure_home_exists()
            assert home.exists()
            assert (home / "apps").exists()

    def test_idempotent(self, tmp_path):
        """Test ensure_home_exists is idempotent."""
        home = tmp_path / ".scry-run"
        with patch.dict(os.environ, {"SCRY_HOME": str(home)}):
            ensure_home_exists()
            ensure_home_exists()  # Should not raise
            assert home.exists()
