#!/usr/bin/env python3
"""
Script de prueba para el sistema de webhooks
"""

import requests
import json
import time

BASE_URL = "https://cierresmig.online"

def test_health():
    """Probar endpoint de salud"""
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=10)
        print(f"Health Check: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"Status: {data.get('status')}")
            print(f"Database: {data.get('database', 'unknown')}")
        else:
            print(f"Error: {response.text}")
        return response.status_code == 200
    except Exception as e:
        print(f"Error en health check: {e}")
        return False

def test_webhook():
    """Probar webhook con datos de prueba"""
    try:
        test_data = {
            "store_id": "123"
        }
        
        headers = {
            "Content-Type": "application/json",
            "X-Rappi-Event-Type": "PING"
        }
        
        response = requests.post(
            f"{BASE_URL}/webhook/rappi", 
            json=test_data,
            headers=headers,
            timeout=10
        )
        
        print(f"Webhook Test: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"Response: {data}")
        else:
            print(f"Error: {response.text}")
        
        return response.status_code == 200
    except Exception as e:
        print(f"Error en webhook test: {e}")
        return False

def test_api_endpoints():
    """Probar endpoints de API"""
    endpoints = [
        "/api/estadisticas",
        "/api/eventos",
        "/api/ordenes"
    ]
    
    for endpoint in endpoints:
        try:
            response = requests.get(f"{BASE_URL}{endpoint}", timeout=10)
            print(f"{endpoint}: {response.status_code}")
            if response.status_code != 200:
                print(f"  Error: {response.text}")
        except Exception as e:
            print(f"{endpoint}: Error - {e}")

def main():
    print("🧪 Probando sistema de webhooks...")
    print("=" * 50)
    
    # Test 1: Health check
    print("\n1. Health Check:")
    health_ok = test_health()
    
    # Test 2: Webhook
    print("\n2. Webhook Test:")
    webhook_ok = test_webhook()
    
    # Test 3: API endpoints
    print("\n3. API Endpoints:")
    test_api_endpoints()
    
    # Resumen
    print("\n" + "=" * 50)
    print("📊 Resumen:")
    print(f"Health Check: {'✅ OK' if health_ok else '❌ FAIL'}")
    print(f"Webhook: {'✅ OK' if webhook_ok else '❌ FAIL'}")
    
    if health_ok and webhook_ok:
        print("\n🎉 Sistema funcionando correctamente!")
        print(f"Dashboard: {BASE_URL}/")
        print(f"Webhook URL: {BASE_URL}/webhook/rappi")
    else:
        print("\n⚠️ Hay problemas que resolver")

if __name__ == "__main__":
    main()