"""Pytest configuration and fixtures."""

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

import pytest


@pytest.fixture(autouse=True)
def force_frozen_backend():
    """Force frozen backend for all tests to prevent accidental LLM calls.

    This autouse fixture ensures tests never accidentally call real LLM APIs.
    Tests that need a real backend must explicitly override this.
    """
    with patch.dict(os.environ, {"SCRY_BACKEND": "frozen"}):
        yield


@pytest.fixture
def scry_run_home(tmp_path):
    """Create isolated scry-run home directory for testing.

    Sets SCRY_HOME to a temporary directory with proper structure.
    Automatically cleaned up after test.
    """
    home = tmp_path / ".scry-run"
    home.mkdir()
    (home / "apps").mkdir()

    with patch.dict(os.environ, {"SCRY_HOME": str(home)}):
        yield home


@pytest.fixture(scope="session")
def monkeypatch_session():
    """Session-scoped monkeypatch."""
    from _pytest.monkeypatch import MonkeyPatch
    mp = MonkeyPatch()
    yield mp
    mp.undo()


@pytest.fixture(autouse=True)
def reset_logger_singleton():
    """Reset logger singleton after each test to prevent cross-test pollution.
    
    Also cleans up any log files created in the working directory.
    """
    from scry_run.logging import ScryRunLogger
    
    # Reset before test
    ScryRunLogger._instance = None
    
    yield
    
    # Clean up after test - remove any log files in cwd
    cwd = Path.cwd()
    for log_file in cwd.glob("generation_*.log"):
        try:
            log_file.unlink()
        except (OSError, PermissionError):
            pass
    
    # Also clean up old-style generation.log if exists
    old_log = cwd / "generation.log"
    if old_log.exists():
        try:
            old_log.unlink()
        except (OSError, PermissionError):
            pass
    
    # Reset singleton again
    ScryRunLogger._instance = None
