"""Shared fixtures for the test suite.

Keep this file minimal and free of application imports at module import time:
a fixture that reaches into the process environment must be requested
explicitly so a test can see exactly which confinement it is exercising.
"""

from __future__ import annotations

import os

# Must set CYBERBRAIN_CHAIN_KEY BEFORE any module imports that load audit.chain
os.environ.setdefault("CYBERBRAIN_CHAIN_KEY", "test-chain-key-for-testing-only-32bytes")

from pathlib import Path

import pytest

from cyberbrain26.product.local_store import ensure_workspaces_root


@pytest.fixture(autouse=True)
def isolated_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    """Redirect every writable path into ``tmp_path`` for all tests.

    Prevents cross-test contamination of the shared host database and
    workspaces root.
    """
    monkeypatch.setenv("CYBERBRAIN_DATA_DIR", str(tmp_path))
    monkeypatch.setenv("CYBERBRAIN_DB_PATH", str(tmp_path / "cyberbrain.sqlite3"))
    monkeypatch.setenv("CYBERBRAIN_WORKSPACES_ROOT", str(tmp_path / "workspaces"))
    monkeypatch.delenv("CYBERBRAIN_RETENTION_DAYS", raising=False)
    # Ensure chain key is set for all tests
    monkeypatch.setenv("CYBERBRAIN_CHAIN_KEY", "test-chain-key-for-testing-only-32bytes")


@pytest.fixture
def sandbox_workspaces_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """Return an isolated, per-test sanctioned workspaces root.

    The sandbox provider confines every writable workspace to
    ``<data dir>/workspaces``, so a test that wants a working workspace must
    build it under that root. The data directory is redirected into ``tmp_path``
    and the related variables are cleared so a developer's real
    ``~/.local/share/CyberBrain26`` is never written to and a stray host
    configuration cannot decide the outcome of a test.
    """
    data_dir = tmp_path / "data"
    monkeypatch.setenv("CYBERBRAIN_DATA_DIR", str(data_dir))
    for name in ("CYBERBRAIN_WORKSPACES_ROOT", "CYBERBRAIN_DB_PATH", "CYBERBRAIN_RETENTION_DAYS"):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setenv("CYBERBRAIN_DB_PATH", str(data_dir / "cyberbrain.sqlite3"))
    monkeypatch.setenv("CYBERBRAIN_WORKSPACES_ROOT", str(data_dir / "workspaces"))
    assert "CYBERBRAIN_DATA_DIR" in os.environ
    root = ensure_workspaces_root()
    root.mkdir(parents=True, exist_ok=True)
    return root
