# guardianhub/persistence/manager.py
import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import QueuePool


class SovereignDBManager:
    _engines = {}

    @classmethod
    def get_engine(cls, db_name: str, is_admin: bool = False):
        user = os.getenv("MASTER_DB_ADMIN") if is_admin else os.getenv("MASTER_TENANT_ADMIN")
        pwd = os.getenv("MASTER_DB_ADMIN_PASSWORD") if is_admin else os.getenv("MASTER_TENANT_ADMIN_PASSWORD")
        host = os.getenv("POSTGRES_HOST", "localhost")

        cache_key = f"{db_name}_{'admin' if is_admin else 'user'}"

        if cache_key not in cls._engines:
            url = f"postgresql+asyncpg://{user}:{pwd}@{host}:5432/{db_name}"
            cls._engines[cache_key] = create_async_engine(
                url,
                # 🚀 TUNING FOR MICROSERVICES:
                # Lower pool size per service to prevent exhausting global connections
                pool_size=5,
                max_overflow=10,
                pool_timeout=30,
                pool_recycle=1800,
                pool_pre_ping=True,
                poolclass=QueuePool
            )
        return cls._engines[cache_key]

    @classmethod
    async def shutdown(cls):
        for engine in cls._engines.values():
            await engine.dispose()