# services/external/app/services/messaging.py
"""
External Service Messaging - Event Publishing using shared messaging infrastructure
"""

from shared.messaging.rabbitmq import RabbitMQClient
from app.core.config import settings
import structlog

logger = structlog.get_logger()

# Single global instance
data_publisher = RabbitMQClient(settings.RABBITMQ_URL, "data-service")

async def setup_messaging():
    """Initialize messaging for data service"""
    try:
        success = await data_publisher.connect()
        if success:
            logger.info("Data service messaging initialized")
        else:
            logger.warning("Data service messaging failed to initialize")
        return success
    except Exception as e:
        logger.warning("Failed to setup messaging", error=str(e))
        return False

async def cleanup_messaging():
    """Cleanup messaging for data service"""
    try:
        await data_publisher.disconnect()
        logger.info("Data service messaging cleaned up")
    except Exception as e:
        logger.warning("Error during messaging cleanup", error=str(e))

async def publish_weather_updated(data: dict) -> bool:
    """Publish weather updated event"""
    try:
        return await data_publisher.publish_data_event("weather.updated", data)
    except Exception as e:
        logger.warning("Failed to publish weather updated event", error=str(e))
        return False

async def publish_traffic_updated(data: dict) -> bool:
    """Publish traffic updated event"""
    try:
        return await data_publisher.publish_data_event("traffic.updated", data)
    except Exception as e:
        logger.warning("Failed to publish traffic updated event", error=str(e))
        return False



# Health check for messaging
async def check_messaging_health() -> dict:
    """Check messaging system health"""
    try:
        if data_publisher.connected:
            return {"status": "healthy", "service": "rabbitmq", "connected": True}
        else:
            return {"status": "unhealthy", "service": "rabbitmq", "connected": False, "error": "Not connected"}
    except Exception as e:
        return {"status": "unhealthy", "service": "rabbitmq", "connected": False, "error": str(e)}