"""Database engine for the API plugin.

NOTE: Runs inside the Airflow api-server process. Uses SQLAlchemy 1.4
from /home/airflow/.local. Do NOT import from src.*.
"""

import os

from sqlalchemy import create_engine

_engine = None


def _get_sync_db_url() -> str:
    """Get sync database URL from DATABASE_URL env var."""
    url = os.getenv("DATABASE_URL", "")
    if not url:
        raise RuntimeError("DATABASE_URL env var is required")
    return url.replace("+asyncpg", "+psycopg2")


def get_engine():
    """Lazy-initialized sync SQLAlchemy engine."""
    global _engine
    if _engine is None:
        _engine = create_engine(
            _get_sync_db_url(),
            pool_pre_ping=True,
            pool_size=3,
            max_overflow=2,
        )
    return _engine
