"""Oracle ADB connection pool — shared across all modules."""

from __future__ import annotations

import os
from contextlib import contextmanager
from typing import Generator, Optional

import oracledb

_pool: Optional[oracledb.ConnectionPool] = None


def _get_pool() -> oracledb.ConnectionPool:
    global _pool
    if _pool is None:
        kwargs: dict = dict(
            user=os.environ["ORACLE_USER"],
            password=os.environ["ORACLE_PASSWORD"],
            dsn=os.environ["ORACLE_DSN"],
            min=1,
            max=5,
            increment=1,
        )
        wallet = os.environ.get("ORACLE_WALLET")
        if wallet:
            kwargs["config_dir"] = wallet
        _pool = oracledb.create_pool(**kwargs)
    return _pool


@contextmanager
def conn() -> Generator[oracledb.Connection, None, None]:
    """Acquire a pooled connection with auto-commit/rollback."""
    pool = _get_pool()
    c = pool.acquire()
    try:
        yield c
        c.commit()
    except Exception:
        c.rollback()
        raise
    finally:
        pool.release(c)
