"""Shared setup/teardown for TDD session DI Robot helpers.

Extracted from ``helper_tdd_session_create_di.py`` and
``helper_tdd_session_list_di.py`` to eliminate duplication (review finding F8).
"""

from __future__ import annotations

import os
import sys
import tempfile
from pathlib import Path

# Ensure local source tree is importable
_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
    sys.path.insert(0, _SRC)

from typer.testing import CliRunner  # noqa: E402

from cleveragents.application.container import reset_container  # noqa: E402
from cleveragents.cli.commands import session as session_mod  # noqa: E402
from cleveragents.config.settings import Settings  # noqa: E402

runner = CliRunner()


def setup_real_di() -> str:
    """Prepare the environment for real DI resolution.

    Returns the path to a temporary database file (caller must clean up).
    """
    session_mod._service = None
    # Reset any stale container from a prior test.
    reset_container()
    fd, db_path = tempfile.mkstemp(suffix=".db")
    os.close(fd)
    os.environ["CLEVERAGENTS_DATABASE_URL"] = f"sqlite:///{db_path}"
    return db_path


def teardown(db_path: str) -> None:
    """Clean up after a test."""
    session_mod._service = None
    os.environ.pop("CLEVERAGENTS_DATABASE_URL", None)
    reset_container()
    # Reset the Settings singleton so stale database URLs do not leak.
    Settings._instance = None
    Path(db_path).unlink(missing_ok=True)
