from sqlalchemy import select
from app.db.database import engine, Base, SessionLocal
from app.db.models import ApiSettings
# Must import all models to ensure they are registered in Base.metadata
from app.db import models

async def init_db():
    async with engine.begin() as conn:
        # Create all tables
        await conn.run_sync(Base.metadata.create_all)
    
    # Seed Data
    async with SessionLocal() as session:
        # Check if ApiSettings(id=1) exists
        stmt = select(ApiSettings).where(ApiSettings.id == 1)
        result = await session.execute(stmt)
        settings_entry = result.scalar_one_or_none()
        
        if not settings_entry:
            # Create default settings
            default_settings = ApiSettings(id=1)
            session.add(default_settings)
            await session.commit()
            print("Initialized default ApiSettings(id=1)")
