"""Helpers for accessing lifespan-owned application state resources."""

from __future__ import annotations

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlmodel.ext.asyncio.session import AsyncSession

from transcription.db.runtime import DatabaseRuntime
from transcription.db.session import get_session_factory
from transcription.worker import WorkerNotifier
from transcription.worker import resolve_worker_notifier


def resolve_database_runtime(state: object) -> DatabaseRuntime | None:
    """Return database runtime from app-like state objects when available."""
    runtime = getattr(state, "runtime", None)
    return runtime if isinstance(runtime, DatabaseRuntime) else None


def require_database_runtime(state: object) -> DatabaseRuntime:
    """Return database runtime or raise when app lifespan has not initialized it."""
    runtime = resolve_database_runtime(state)
    if runtime is None:
        raise RuntimeError("Database runtime is not initialized on application state")
    return runtime


def resolve_session_factory(state: object) -> async_sessionmaker[AsyncSession]:
    """Return DB session factory from state when available, otherwise shared runtime."""
    runtime = resolve_database_runtime(state)
    if runtime is not None:
        return runtime.session_factory
    return get_session_factory()


def get_worker_notifier(app: FastAPI) -> WorkerNotifier:
    """Return app worker notifier, or a no-op fallback when unavailable."""
    return resolve_worker_notifier(app.state)
