import os
import hmac
import hashlib
import json
from typing import Dict, Any
from flask import Flask, request, jsonify

app = Flask(__name__)

WACRM_WEBHOOK_SECRET = os.environ.get("WACRM_WEBHOOK_SECRET", "skeen_webhook_secret_2026")
HERMES_AGENT = None  # Se inicializa al arrancar el gateway


def verify_signature(payload: bytes, signature: str) -> bool:
    """Verifica la firma HMAC-SHA256 del webhook de WACRM."""
    if not signature:
        return False
    
    # Formato esperado: "t=<timestamp>,v1=<signature>"
    parts = {}
    for part in signature.split(','):
        if '=' in part:
            key, value = part.split('=', 1)
            parts[key.strip()] = value.strip()
    
    timestamp = parts.get('t', '')
    expected_sig = parts.get('v1', '')
    
    expected = hmac.new(
        WACRM_WEBHOOK_SECRET.encode(),
        f"{timestamp}.{payload.decode()}".encode(),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(expected_sig, expected)


@app.route('/webhook/wacrm', methods=['POST'])
def handle_wacrm_webhook():
    """Recibe webhooks de WACRM y los procesa via Hermes agent."""
    payload = request.get_data()
    signature = request.headers.get('X-WACRM-Signature', '')
    
    if not verify_signature(payload, signature):
        return jsonify({"error": "Invalid signature"}), 401
    
    event = request.json
    event_type = event.get('event')
    data = event.get('data', {})
    
    # Enrutar segun tipo de evento
    handlers = {
        'message.received': handle_message_received,
        'message.status_updated': handle_status_update,
        'conversation.created': handle_new_conversation,
    }
    
    handler = handlers.get(event_type)
    if handler:
        handler(data)
    
    return jsonify({"received": True}), 200


def handle_message_received(data: Dict[str, Any]):
    """Procesa mensaje entrante de WACRM."""
    from_number = data.get('from')
    text = data.get('text', '')
    conversation_id = data.get('conversation_id')
    contact_id = data.get('contact_id')
    
    # Enviar al agent runtime de Hermes
    # Esto se conecta con el gateway principal de Hermes
    if HERMES_AGENT:
        HERMES_AGENT.process_message(
            channel='whatsapp',
            sender=from_number,
            text=text,
            metadata={
                'conversation_id': conversation_id,
                'contact_id': contact_id,
                'source': 'wacrm'
            }
        )
    
    # Log para debugging
    print(f"[WACRM Webhook] Mensaje de {from_number}: {text[:50]}...")


def handle_status_update(data: Dict[str, Any]):
    """Procesa actualizacion de estado de mensaje."""
    message_id = data.get('message_id')
    status = data.get('status')  # sent, delivered, read, failed
    
    print(f"[WACRM Webhook] Estado mensaje {message_id}: {status}")


def handle_new_conversation(data: Dict[str, Any]):
    """Procesa nueva conversacion."""
    conversation_id = data.get('conversation_id')
    contact_id = data.get('contact_id')
    
    print(f"[WACRM Webhook] Nueva conversacion: {conversation_id}")


@app.route('/health', methods=['GET'])
def health_check():
    """Health check para monitoreo."""
    return jsonify({"status": "ok", "service": "wacrm-webhook-server"}), 200


def init_hermes_agent(agent):
    """Inicializa la referencia al agente de Hermes."""
    global HERMES_AGENT
    HERMES_AGENT = agent


if __name__ == '__main__':
    port = int(os.environ.get('HERMES_WEBHOOK_PORT', 8080))
    app.run(host='0.0.0.0', port=port, debug=False)
