import os
import tempfile
from pathlib import Path

# Use a temporary on-disk SQLite database for the test session so that
# both the sync and async engines used by the app point at the same isolated
# schema.  This avoids relying on (or mutating) the developer's data/translate.db.
_test_db_file = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
_test_db_file.close()
os.environ["SQLITE_PATH"] = _test_db_file.name

import pytest
import pytest_asyncio
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker

from database.connection import sync_engine
from database.models import Base

# In-memory SQLite: fully isolated, no disk state between test sessions
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"


@pytest.fixture(scope="session", autouse=True)
def initialize_test_database():
    Base.metadata.create_all(bind=sync_engine)
    yield
    # Clean up the temporary test database after the session.
    try:
        Path(_test_db_file.name).unlink(missing_ok=True)
    except Exception:
        pass


@pytest_asyncio.fixture
async def async_engine():
    from database.models import Base

    engine = create_async_engine(TEST_DATABASE_URL, echo=False)

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    yield engine

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)

    await engine.dispose()


@pytest_asyncio.fixture
async def async_session(async_engine) -> AsyncGenerator[AsyncSession, None]:
    async_session_factory = async_sessionmaker(
        bind=async_engine,
        class_=AsyncSession,
        expire_on_commit=False,
    )

    async with async_session_factory() as session:
        yield session
