#!/usr/bin/env python3
"""
Recommendation Alert Test
Sends a realistic optimization recommendation to test the AI recommendations system
"""

import aio_pika
import asyncio
import json
import uuid
from datetime import datetime

async def send_recommendation_alert():
    """Send a realistic optimization recommendation"""

    # Connect to RabbitMQ
    connection = await aio_pika.connect_robust('amqp://bakery:forecast123@rabbitmq:5672/')
    channel = await connection.channel()

    # Declare the alerts exchange
    exchange = await channel.declare_exchange(
        'alerts.exchange',
        aio_pika.ExchangeType.TOPIC,
        durable=True
    )

    # Use actual tenant ID
    tenant_id = 'c464fb3e-7af2-46e6-9e43-85318f34199a'

    print("💡 Sending optimization recommendation...")

    # Optimization Recommendation
    recommendation = {
        'id': str(uuid.uuid4()),
        'tenant_id': tenant_id,
        'item_type': 'recommendation',
        'type': 'demand_optimization',
        'severity': 'medium',
        'service': 'ai-forecast-service',
        'title': '💡 OPTIMIZACIÓN: Ajustar Producción de Croissants',
        'message': 'Nuestro análisis de IA detectó que la demanda de croissants aumenta un 35% los viernes. Se recomienda incrementar la producción para maximizar ventas y reducir desperdicio.',
        'actions': [
            'Revisar análisis de demanda detallado',
            'Ajustar plan de producción para viernes',
            'Evaluar capacidad de horno disponible',
            'Calcular ROI del incremento propuesto',
            'Implementar cambio gradualmente',
            'Monitorear resultados por 2 semanas'
        ],
        'metadata': {
            'product_name': 'Croissants',
            'current_friday_production': 120,
            'recommended_friday_production': 162,
            'increase_percentage': 35,
            'confidence_score': 0.87,
            'data_period_analyzed': '3 meses',
            'potential_revenue_increase': 280.50,
            'currency': 'EUR',
            'historical_sellout_rate': 0.95,
            'waste_reduction_potential': '15%',
            'implementation_effort': 'LOW',
            'roi_timeframe': '2 semanas',
            'seasonal_factors': [
                'Viernes laboral',
                'Proximidad fin de semana',
                'Horario de desayuno extendido'
            ],
            'risk_level': 'BAJO'
        },
        'timestamp': datetime.utcnow().isoformat()
    }

    await exchange.publish(
        aio_pika.Message(json.dumps(recommendation).encode()),
        routing_key='recommendation.medium.ai-forecast-service'
    )

    print(f"✅ Recommendation sent: {recommendation['title']}")
    print(f"   Recommendation ID: {recommendation['id']}")
    print(f"   Severity: {recommendation['severity'].upper()}")
    print(f"   Service: {recommendation['service']}")
    print(f"   Confidence: {recommendation['metadata']['confidence_score']*100:.0f}%")
    print(f"   Potential revenue increase: €{recommendation['metadata']['potential_revenue_increase']}")

    await connection.close()

    print("\n🎯 Recommendation test completed!")
    print("Check your frontend for:")
    print("  • Medium priority notification in header")
    print("  • Real-time recommendation in dashboard panel")
    print("  • Blue info badge (recommendation type)")
    print("  • Expandable card with AI analysis and business impact")

if __name__ == "__main__":
    asyncio.run(send_recommendation_alert())