"""One-shot script to create the MariaDB database and all tables."""
import asyncio
import pymysql
from app.core.config import settings


def create_database():
    """Create database if it doesn't exist (sync, before async engine starts)."""
    conn = pymysql.connect(
        host=settings.DB_HOST,
        port=settings.DB_PORT,
        user=settings.DB_USER,
        password=settings.DB_PASSWORD,
        charset="utf8mb4",
    )
    cur = conn.cursor()
    cur.execute(
        f"CREATE DATABASE IF NOT EXISTS `{settings.DB_NAME}` "
        "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
    )
    cur.execute(f"SHOW DATABASES LIKE '{settings.DB_NAME}'")
    print(f"✅ Database '{settings.DB_NAME}' ready: {cur.fetchall()}")
    conn.close()


async def create_tables():
    """Create all SQLAlchemy-defined tables."""
    from app.core.database import engine, Base
    from app.models import user, game, academic, school, progress, payment  # noqa

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    print("✅ All tables created successfully")
    await engine.dispose()


if __name__ == "__main__":
    print(f"Using database: {settings.async_database_url}")
    if not settings.USE_SQLITE:
        create_database()
    asyncio.run(create_tables())
    print("🎉 Done!")
