#!/usr/bin/env python3
"""Initialize database schema: create all tables and stamp alembic version."""

import asyncio
import subprocess
import sys

from app.config import settings
from app.database import Base, engine
from app.models import *  # noqa: F401, F403


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


def stamp_alembic():
    result = subprocess.run(
        ["alembic", "stamp", "head"],
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        print(f"alembic stamp failed:\n{result.stderr}", file=sys.stderr)
        sys.exit(1)
    print("Alembic version stamped to head.")


async def main():
    print(f"Using DATABASE_URL: {settings.DATABASE_URL.split('@')[-1]}")
    await create_tables()
    stamp_alembic()
    await engine.dispose()
    print("Schema initialization complete.")


if __name__ == "__main__":
    asyncio.run(main())
