"""
Demo Session Service - Main Application
Manages isolated demo sessions with ephemeral data
"""

import structlog

from app.core import settings, DatabaseManager
from app.api import demo_sessions, demo_accounts, demo_operations, internal
from shared.redis_utils import initialize_redis, close_redis
from shared.service_base import StandardFastAPIService

# Initialize logger
logger = structlog.get_logger()

# Initialize database manager
db_manager = DatabaseManager()


class DemoSessionService(StandardFastAPIService):
    """Demo Session Service with standardized monitoring setup"""

    async def on_startup(self, app):
        """Custom startup logic for Demo Session"""
        # Initialize database
        db_manager.initialize()
        logger.info("Database initialized")

        # Initialize Redis
        await initialize_redis(
            redis_url=settings.REDIS_URL,
            db=0,
            max_connections=50
        )
        logger.info("Redis initialized")

        await super().on_startup(app)

    async def on_shutdown(self, app):
        """Custom shutdown logic for Demo Session"""
        await super().on_shutdown(app)

        # Cleanup
        await db_manager.close()
        await close_redis()
        logger.info("Database and Redis connections closed")


# Create service instance
service = DemoSessionService(
    service_name="demo-session",
    app_name="Demo Session Service",
    description="Manages isolated demo sessions for prospect users",
    version=settings.VERSION,
    log_level=getattr(settings, 'LOG_LEVEL', 'INFO'),
    cors_origins=["*"],  # Configure appropriately for production
    api_prefix="/api/v1",
    enable_metrics=True,
    enable_health_checks=True,
    enable_tracing=True,
    enable_cors=True
)

# Create FastAPI app
app = service.create_app(debug=settings.DEBUG)

# Add service-specific routers
app.include_router(demo_sessions.router)
app.include_router(demo_accounts.router)
app.include_router(demo_operations.router)
app.include_router(internal.router)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )
