from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from app.config import settings

# Convert pymysql URL to aiomysql for async support
async_db_url = settings.DATABASE_URL.replace(
    "mysql+pymysql://", "mysql+aiomysql://"
)

engine = create_async_engine(
    async_db_url,
    echo=False,
    pool_pre_ping=True,
    pool_recycle=3600,
)

AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


class Base(DeclarativeBase):
    pass


async def get_db() -> AsyncSession:
    """Dependency: yields a database session and closes it after use."""
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


async def init_db():
    """Create all tables on startup (if not using Alembic migrations)."""
    async with engine.begin() as conn:
        from app.models import trade, strategy, performance_log, settings_model  # noqa: F401
        await conn.run_sync(Base.metadata.create_all)
