from __future__ import annotations

import logging

from sqlalchemy.ext.asyncio import AsyncEngine
from sqlmodel import SQLModel
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession

from .engine import resolve_engine
from .models import Job
from .models import JobStatus

logger = logging.getLogger(__name__)


async def create_all(*, engine: AsyncEngine | None = None) -> None:
    """Create any missing tables on the selected engine."""
    # Import models so SQLModel metadata is fully registered before bootstrap.
    from transcription.db import models as _models  # noqa: F401

    active_engine = engine or resolve_engine()
    async with active_engine.begin() as connection:
        await connection.run_sync(SQLModel.metadata.create_all)
    logger.debug("Database schema bootstrap complete for database_url=%s", active_engine.url)


async def get_next_queued_job(*, session: AsyncSession) -> Job | None:
    """Get the next queued job, if any."""
    result = await session.exec(
        select(Job)
        .where(Job.status == JobStatus.QUEUED)
        .order_by(Job.date_created)  # pyright: ignore[reportArgumentType]
        .limit(1)
    )  # fmt: skip
    return result.first()
