#!/usr/bin/env python3
"""
Migration script to update production service to send raw alerts
"""

import re

# Read the file
with open('app/services/production_alert_service.py', 'r') as f:
    content = f.read()

# Pattern 1: Replace order_overload template usage (line 130-147)
pattern1 = r'''                template_data = self\.format_spanish_message\(
                    'order_overload',
                    percentage=int\(percentage - 100\)
                \)

                await self\.publish_item\(tenant_id, \{
                    'type': 'severe_capacity_overload',
                    'severity': 'urgent',
                    'title': template_data\['title'\],
                    'message': template_data\['message'\],
                    'actions': template_data\['actions'\],'''

replacement1 = '''                await self.publish_item(tenant_id, {
                    'type': 'severe_capacity_overload',
                    'severity': 'urgent',
                    'title': 'Raw Alert - Will be enriched',
                    'message': 'Raw Alert - Will be enriched',
                    'actions': [],'''

content = content.replace(pattern1, replacement1)

# Pattern 2: Replace production_delay template usage (line 231-242)
pattern2 = r'''            template_data = self\.format_spanish_message\(
                'production_delay',
                batch_name=f"\{delay\['product_name'\]\} #\{delay\['batch_number'\]\}",
                delay_minutes=int\(delay_minutes\)
            \)

            await self\.publish_item\(delay\['tenant_id'\], \{
                'type': 'production_delay',
                'severity': severity,
                'title': template_data\['title'\],
                'message': template_data\['message'\],
                'actions': template_data\['actions'\],'''

replacement2 = '''            await self.publish_item(delay['tenant_id'], {
                'type': 'production_delay',
                'severity': severity,
                'title': 'Raw Alert - Will be enriched',
                'message': 'Raw Alert - Will be enriched',
                'actions': [],'''

content = content.replace(pattern2, replacement2)

# Add batch_name to metadata for production_delay
content = content.replace(
    '''                'metadata': {
                    'batch_id': str(delay['id']),
                    'product_name': delay['product_name'],
                    'batch_number': delay['batch_number'],
                    'delay_minutes': delay_minutes,''',
    '''                'metadata': {
                    'batch_id': str(delay['id']),
                    'batch_name': f"{delay['product_name']} #{delay['batch_number']}",
                    'product_name': delay['product_name'],
                    'batch_number': delay['batch_number'],
                    'delay_minutes': delay_minutes,'''
)

# Pattern 3: Replace equipment_failure template usage (line 370-380)
pattern3 = r'''                template_data = self\.format_spanish_message\(
                    'equipment_failure',
                    equipment_name=equipment\['name'\]
                \)

                await self\.publish_item\(equipment\['tenant_id'\], \{
                    'type': 'equipment_failure',
                    'severity': 'urgent',
                    'title': template_data\['title'\],
                    'message': template_data\['message'\],
                    'actions': template_data\['actions'\],'''

replacement3 = '''                await self.publish_item(equipment['tenant_id'], {
                    'type': 'equipment_failure',
                    'severity': 'urgent',
                    'title': 'Raw Alert - Will be enriched',
                    'message': 'Raw Alert - Will be enriched',
                    'actions': [],'''

content = content.replace(pattern3, replacement3)

# Pattern 4: Replace maintenance_required template usage (line 392-403)
pattern4 = r'''                template_data = self\.format_spanish_message\(
                    'maintenance_required',
                    equipment_name=equipment\['name'\],
                    days_until_maintenance=max\(0, int\(days_to_maintenance\)\) if days_to_maintenance is not None else 3
                \)

                await self\.publish_item\(equipment\['tenant_id'\], \{
                    'type': 'maintenance_required',
                    'severity': severity,
                    'title': template_data\['title'\],
                    'message': template_data\['message'\],
                    'actions': template_data\['actions'\],'''

replacement4 = '''                await self.publish_item(equipment['tenant_id'], {
                    'type': 'maintenance_required',
                    'severity': severity,
                    'title': 'Raw Alert - Will be enriched',
                    'message': 'Raw Alert - Will be enriched',
                    'actions': [],'''

content = content.replace(pattern4, replacement4)

# Pattern 5: Replace low_equipment_efficiency template usage (line 415-426)
pattern5 = r'''                template_data = self\.format_spanish_message\(
                    'low_equipment_efficiency',
                    equipment_name=equipment\['name'\],
                    efficiency_percent=round\(efficiency, 1\)
                \)

                await self\.publish_item\(equipment\['tenant_id'\], \{
                    'type': 'low_equipment_efficiency',
                    'severity': severity,
                    'title': template_data\['title'\],
                    'message': template_data\['message'\],
                    'actions': template_data\['actions'\],'''

replacement5 = '''                await self.publish_item(equipment['tenant_id'], {
                    'type': 'low_equipment_efficiency',
                    'severity': severity,
                    'title': 'Raw Alert - Will be enriched',
                    'message': 'Raw Alert - Will be enriched',
                    'actions': [],'''

content = content.replace(pattern5, replacement5)

# Pattern 6: Replace production_efficiency template usage (line 479-490)
pattern6 = r'''                template_data = self\.format_spanish_message\(
                    'production_efficiency',
                    suggested_time=f"\{rec\['start_hour'\]:02d\}:00",
                    savings_percent=efficiency_loss
                \)

                await self\.publish_item\(tenant_id, \{
                    'type': 'production_efficiency',
                    'severity': 'medium',
                    'title': template_data\['title'\],
                    'message': template_data\['message'\],
                    'actions': template_data\['actions'\],'''

replacement6 = '''                await self.publish_item(tenant_id, {
                    'type': 'production_efficiency',
                    'severity': 'medium',
                    'title': 'Raw Alert - Will be enriched',
                    'message': 'Raw Alert - Will be enriched',
                    'actions': [],'''

content = content.replace(pattern6, replacement6)

# Add suggested_time to metadata for production_efficiency
content = content.replace(
    '''                    'metadata': {
                        'product_name': rec['product_name'],
                        'avg_production_time': float(rec['avg_production_time']),''',
    '''                    'metadata': {
                        'suggested_time': f"{rec['start_hour']:02d}:00",
                        'product_name': rec['product_name'],
                        'avg_production_time': float(rec['avg_production_time']),'''
)

# Pattern 7: Replace energy_optimization template usage (line 588-600)
pattern7 = r'''                        template_data = self\.format_spanish_message\(
                            'energy_optimization',
                            start_time=f"\{min_off_peak\['hour_of_day'\]:02d\}:00",
                            end_time=f"\{min_off_peak\['hour_of_day'\]\+2:02d\}:00",
                            savings_euros=potential_savings \* 0\.15  # Rough estimate
                        \)

                        await self\.publish_item\(tenant_id, \{
                            'type': 'energy_optimization',
                            'severity': 'low',
                            'title': template_data\['title'\],
                            'message': template_data\['message'\],
                            'actions': template_data\['actions'\],'''

replacement7 = '''                        await self.publish_item(tenant_id, {
                            'type': 'energy_optimization',
                            'severity': 'low',
                            'title': 'Raw Alert - Will be enriched',
                            'message': 'Raw Alert - Will be enriched',
                            'actions': [],'''

content = content.replace(pattern7, replacement7)

# Add time and savings to metadata for energy_optimization
content = content.replace(
    '''                            'metadata': {
                                'equipment_name': equipment,
                                'peak_hour': peak_hour_record['hour_of_day'],''',
    '''                            'metadata': {
                                'start_time': f"{min_off_peak['hour_of_day']:02d}:00",
                                'end_time': f"{min_off_peak['hour_of_day']+2:02d}:00",
                                'savings_euros': round(potential_savings * 0.15, 2),
                                'equipment_name': equipment,
                                'peak_hour': peak_hour_record['hour_of_day'],'''
)

# Pattern 8: Replace production_delay in DB handler (line 632-643)
pattern8 = r'''            template_data = self\.format_spanish_message\(
                'production_delay',
                batch_name=f"\{data\['product_name'\]\} #\{data\.get\('batch_number', 'N/A'\)\}",
                delay_minutes=data\['delay_minutes'\]
            \)

            await self\.publish_item\(tenant_id, \{
                'type': 'production_delay',
                'severity': 'high',
                'title': template_data\['title'\],
                'message': template_data\['message'\],
                'actions': template_data\['actions'\],'''

replacement8 = '''            await self.publish_item(tenant_id, {
                'type': 'production_delay',
                'severity': 'high',
                'title': 'Raw Alert - Will be enriched',
                'message': 'Raw Alert - Will be enriched',
                'actions': [],'''

content = content.replace(pattern8, replacement8)

# Add batch_name to DB handler metadata
content = content.replace(
    '''                'metadata': {
                    'batch_id': data['batch_id'],
                    'delay_minutes': data['delay_minutes'],''',
    '''                'metadata': {
                    'batch_id': data['batch_id'],
                    'batch_name': f"{data['product_name']} #{data.get('batch_number', 'N/A')}",
                    'delay_minutes': data['delay_minutes'],'''
)

# Write the updated file
with open('app/services/production_alert_service.py', 'w') as f:
    f.write(content)

print("Migration complete!")
print("Updated all template usages to send raw data for enrichment")
