#!/usr/bin/env python3
"""
Check what workflows are currently active in n8n
"""

import requests
import json

def check_n8n_workflows():
    """Check what workflows are currently active"""
    
    print("Checking n8n Workflows")
    print("=" * 30)
    
    # Check if n8n is running
    try:
        response = requests.get("http://localhost:5678", timeout=5)
        if response.status_code != 200:
            print("ERROR: n8n is not running")
            return
    except Exception as e:
        print(f"ERROR: Cannot connect to n8n: {e}")
        return
    
    print("SUCCESS: n8n is running")
    print()
    
    # Check all possible webhook endpoints
    webhooks = [
        "agent-task",
        "agent-task-v2", 
        "agent-task-corrected",
        "agent-task-fixed",
        "agent-task-working",
        "agent-task-final"
    ]
    
    print("Checking webhook endpoints...")
    print("-" * 40)
    
    active_webhooks = []
    
    for webhook in webhooks:
        url = f"http://localhost:5678/webhook/{webhook}"
        try:
            response = requests.post(url, json={"message": "test"}, timeout=5)
            if response.status_code == 200:
                print(f"ACTIVE: {webhook}")
                active_webhooks.append(webhook)
            elif response.status_code == 404:
                print(f"NOT FOUND: {webhook}")
            else:
                print(f"ERROR {response.status_code}: {webhook}")
        except Exception as e:
            print(f"ERROR: {webhook} - {e}")
    
    print()
    print(f"Found {len(active_webhooks)} active webhook(s): {active_webhooks}")
    
    # Test the agent-task-working webhook specifically
    if "agent-task-working" in active_webhooks:
        print()
        print("Testing agent-task-working webhook...")
        print("-" * 40)
        
        url = "http://localhost:5678/webhook/agent-task-working"
        payload = {"message": "Test message"}
        
        try:
            response = requests.post(url, json=payload, timeout=10)
            print(f"Status: {response.status_code}")
            
            if response.status_code == 200:
                data = response.json()
                print(f"Success: {data.get('success', False)}")
                print(f"Error: {data.get('error', 'None')}")
                
                if data.get('success'):
                    print("SUCCESS: The webhook is working correctly!")
                else:
                    print("ERROR: The webhook has validation issues")
                    print("This means you're still using the OLD workflow")
                    print()
                    print("SOLUTION:")
                    print("1. Go to n8n: http://localhost:5678")
                    print("2. Find ALL workflows with 'agent-task-working' webhook")
                    print("3. DELETE them all")
                    print("4. Import ONLY the new workflow: n8n_agent_system_flow_working_final.json")
                    print("5. Activate the new workflow")
        except Exception as e:
            print(f"Error testing webhook: {e}")

def main():
    """Main function"""
    check_n8n_workflows()

if __name__ == "__main__":
    main()
