"""Test configuration and shared fixtures for AI MusiMuse.

This module provides fixtures and helpers used across all test modules.
"""

from __future__ import annotations

from pathlib import Path

import pytest
from sqlalchemy.orm import Session

from config.settings import Settings
from database.database import get_session_factory, init_db


def init_test_db(tmp_path: Path) -> Session:
    """Initialize a test SQLite database and return a session.

    Args:
        tmp_path: Temporary directory for the database file.

    Returns:
        An open SQLAlchemy session.
    """
    db_url = f"sqlite:///{tmp_path / 'test.db'}"
    init_db(database_url=db_url)
    session_factory = get_session_factory()
    return session_factory()


@pytest.fixture(autouse=True)
def _reset_database_globals() -> None:
    """Reset database module globals before each test.

    Ensures that ``_engine`` and ``_SessionLocal`` do not leak
    between tests.
    """
    from database import database as db_module

    db_module._engine = None
    db_module._SessionLocal = None


@pytest.fixture
def temp_db_path(tmp_path: Path) -> Path:
    """Return a path for a temporary SQLite database file.

    Args:
        tmp_path: Pytest-provided temporary directory.

    Returns:
        Path to a temporary database file (not yet created).
    """
    return tmp_path / "test_musimuse.db"


@pytest.fixture
def temp_db_url(temp_db_path: Path) -> str:
    """Return a SQLite URL for a temporary database.

    Args:
        temp_db_path: Path fixture for the temporary database file.

    Returns:
        A SQLAlchemy SQLite URL string.
    """
    return f"sqlite:///{temp_db_path}"


@pytest.fixture
def settings(temp_db_url: str, tmp_path: Path) -> Settings:
    """Return a Settings instance configured for testing.

    Args:
        temp_db_url: Temporary database URL fixture.
        tmp_path: Pytest-provided temporary directory.

    Returns:
        A :class:`Settings` instance with test-friendly values.
    """
    return Settings(
        project_name="AI MusiMuse (Test)",
        database_url=temp_db_url,
        log_level="DEBUG",
        cache_directory=str(tmp_path / "cache"),
        data_directory=str(tmp_path / "data"),
        output_directory=str(tmp_path / "output"),
    )
