#!/usr/bin/env python3
"""
Test script to verify that the webhook proxy fix works correctly.
"""

import sys
import os

# Add the gateway directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_webhook_proxy_target_paths():
    """Test that webhook routes proxy to the correct target paths."""
    
    # Read the webhooks file
    with open('app/routes/webhooks.py', 'r') as f:
        content = f.read()
    
    # Check if webhook routes proxy to the correct target paths
    stripe_proxy = 'return await _proxy_to_tenant_service(request, "/webhooks/stripe")'
    generic_proxy = 'return await _proxy_to_tenant_service(request, "/webhooks/generic")'
    
    if stripe_proxy in content and generic_proxy in content:
        print("✅ Webhook routes correctly proxy to tenant service at /webhooks/*")
        return True
    else:
        print("❌ Webhook routes NOT correctly proxying to tenant service")
        print(f"  Looking for: {stripe_proxy}")
        print(f"  Looking for: {generic_proxy}")
        return False

def test_webhook_route_comments():
    """Test that the comments reflect the correct routing."""
    
    # Read the webhooks file
    with open('app/routes/webhooks.py', 'r') as f:
        content = f.read()
    
    # Check if comments reflect the correct routing
    correct_comment = "Gateway receives /api/v1/webhooks/* routes and proxies to tenant service at /webhooks/*"
    
    if correct_comment in content:
        print("✅ Webhook routing comments are correct")
        return True
    else:
        print("❌ Webhook routing comments are NOT correct")
        return False

def main():
    """Run all tests."""
    print("Testing webhook proxy fix...")
    print()
    
    tests = [
        test_webhook_proxy_target_paths,
        test_webhook_route_comments,
    ]
    
    results = []
    for test in tests:
        try:
            result = test()
            results.append(result)
        except Exception as e:
            print(f"❌ Error running {test.__name__}: {e}")
            results.append(False)
        print()
    
    if all(results):
        print("🎉 All tests passed! Webhook proxy should work correctly.")
        print()
        print("Summary of changes:")
        print("- Gateway now proxies /api/v1/webhooks/stripe to /webhooks/stripe")
        print("- Gateway now proxies /api/v1/webhooks/generic to /webhooks/generic")
        print("- This matches the tenant service's expected routes")
        return True
    else:
        print("❌ Some tests failed. Webhook proxy may not work correctly.")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)