import os

import pytest
from sqlalchemy.ext.asyncio import (
    AsyncEngine,
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

from session_hub_core.config import DatabaseConfig
from session_hub_core.schema import create_schema


@pytest.fixture(scope="session")
def db_config(request: pytest.FixtureRequest) -> DatabaseConfig:
    """PostgreSQL test database: SESSION_HUB_TEST_DSN or a pgvector container."""
    dsn = os.environ.get("SESSION_HUB_TEST_DSN")
    if dsn:
        return DatabaseConfig(dsn=dsn)
    try:
        from testcontainers.community.postgres import PostgresContainer

        container = PostgresContainer("pgvector/pgvector:pg17")
        container.start()
        request.addfinalizer(container.stop)
        url = (
            container.get_connection_url()
            .replace("postgresql+psycopg2://", "postgresql+asyncpg://")
            .replace("postgresql://", "postgresql+asyncpg://")
        )
        return DatabaseConfig(dsn=url)
    except Exception as exc:
        pytest.skip(
            f"No test database available (docker down or SESSION_HUB_TEST_DSN unset): {exc}"
        )


@pytest.fixture(scope="session")
async def engine(db_config: DatabaseConfig) -> AsyncEngine:
    eng = create_async_engine(db_config.dsn, pool_pre_ping=True)
    await create_schema(db_config)
    yield eng
    await eng.dispose()


@pytest.fixture(scope="session")
def session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
    return async_sessionmaker(engine, expire_on_commit=False)
