# ================================================================
# services/forecasting/app/core/database.py
# ================================================================
"""
Database configuration for forecasting service
"""

import structlog
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import NullPool
from sqlalchemy import text

from app.core.config import settings
from shared.database.base import Base

logger = structlog.get_logger()

# Create async engine
engine = create_async_engine(
    settings.DATABASE_URL,
    poolclass=NullPool,
    echo=settings.DEBUG,
    future=True
)

# Create session factory
AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autoflush=False,
    autocommit=False
)

class DatabaseManager:
    """Database management operations"""
    
    async def create_tables(self):
        """Create database tables"""
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        logger.info("Forecasting database tables created successfully")
    
    async def get_session(self) -> AsyncSession:
        """Get database session"""
        async with AsyncSessionLocal() as session:
            try:
                yield session
                await session.commit()
            except Exception as e:
                await session.rollback()
                logger.error(f"Database session error: {e}")
                raise
            finally:
                await session.close()

# Global database manager instance
database_manager = DatabaseManager()

async def get_db() -> AsyncSession:
    """Database dependency"""
    async for session in database_manager.get_session():
        yield session

async def get_db_health() -> bool:
    """Check database health"""
    try:
        async with AsyncSessionLocal() as session:
            await session.execute(text("SELECT 1"))
            return True
    except Exception as e:
        logger.error(f"Database health check failed: {e}")
        return False
