#!/usr/bin/env python3
"""
Webhook listener for Smart City Digital Twin Alerts
Receives Docker events and sends Telegram alerts
"""

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import subprocess
import threading

TELEGRAM_USER = "@ericf972"  # Will be replaced with actual send_message in production

class WebhookHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        
        try:
            event = json.loads(post_data.decode('utf-8'))
            self.process_event(event)
            self.send_response(200)
            self.end_headers()
        except Exception as e:
            print(f"Error processing webhook: {e}")
            self.send_response(500)
            self.end_headers()
    
    def process_event(self, event):
        """Process incoming webhook event"""
        event_type = event.get('Type', '')
        event_action = event.get('Action', '')
        event_actor = event.get('Actor', {}).get('Attributes', {}).get('name', '')
        
        if event_type == 'container' and event_action in ['die', 'destroy', 'stop']:
            message = f"🚨 Smart City Alert!\n"
            message += f"Container: {event_actor}\n"
            message += f"Action: {event_action}\n"
            message += f"Time: {event.get('time', '')}\n"
            
            # Send Telegram alert (using subprocess to call Hermes send_message)
            subprocess.run([
                'hermes', 'send-message',
                '--target', TELEGRAM_USER,
                '--message', message
            ], timeout=10)
            print(f"Alert sent: {message}")
    
    def log_message(self, format, *args):
        """Suppress default logging"""
        pass

def run_webhook_server(port=8089):
    """Start webhook server"""
    server = HTTPServer(('0.0.0.0', port), WebhookHandler)
    print(f"Webhook server started on port {port}")
    server.serve_forever()

if __name__ == '__main__':
    run_webhook_server()
