"""E2E test fixtures -- no Docker, Postgres, or Redis required."""

from __future__ import annotations

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

import pytest
import yaml


@pytest.fixture
def workspace(tmp_path: Path) -> Path:
    """Create an isolated workspace with a .loom/ subdirectory and minimal config.

    Returns the workspace root directory.  The .loom/config.yaml contains
    just enough structure to satisfy ``load_config()``.
    """
    loom_dir = tmp_path / ".loom"
    loom_dir.mkdir()

    config = {
        "loom": {
            "project_name": "e2e-test",
            "project_id": "00000000-0000-0000-0000-000000000000",
        },
        "database": {
            "url": "postgresql://loom:loom@localhost:5432/loom",
        },
        "redis": {
            "url": "redis://localhost:6379",
        },
        "logging": {
            "level": "INFO",
        },
    }
    with open(loom_dir / "config.yaml", "w") as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)

    return tmp_path


@pytest.fixture
def mock_api():
    """Patch the Anthropic client at the transport level to return canned responses.

    Sets ANTHROPIC_API_KEY=test-key in the environment for the duration of
    the test.  Yields the mock object so tests can inspect calls or customise
    return values.
    """
    canned_response = MagicMock()
    canned_response.content = [
        MagicMock(text="Canned response from mock API")
    ]
    canned_response.stop_reason = "end_turn"
    canned_response.model = "mock-model"
    canned_response.usage = MagicMock(input_tokens=10, output_tokens=20)

    mock_client = MagicMock()
    mock_client.messages.create.return_value = canned_response

    # Patch at the anthropic module level so any import picks it up
    with (
        patch.dict(os.environ, {"ANTHROPIC_API_KEY": "test-key"}),
        patch("anthropic.Anthropic", return_value=mock_client) as patched,
    ):
        patched._mock_client = mock_client
        patched._canned_response = canned_response
        yield patched
