"""Which version of a Form is which. A Form's versions share one form_id:
the *current* version (is_current) is what the Form Designer edits — an
unpublished draft once a new version has been started — while the *live*
version is what people fill in: the latest published one. Starting a new
draft never takes a form offline."""

import uuid

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.workflow import Form


async def live_form(db: AsyncSession, tenant_id: uuid.UUID, form_id: uuid.UUID) -> Form | None:
    """The latest published version, or the current one if none was ever published."""
    live = (
        await db.execute(
            select(Form)
            .where(Form.tenant_id == tenant_id, Form.form_id == form_id, Form.status == "published")
            .order_by(Form.version.desc())
            .limit(1)
        )
    ).scalar_one_or_none()
    if live is not None:
        return live
    return (
        await db.execute(select(Form).where(Form.tenant_id == tenant_id, Form.form_id == form_id, Form.is_current.is_(True)))
    ).scalar_one_or_none()
