#!/usr/bin/env python3
"""
Test script for authentication functionality
Tests JWT token verification with both local and remote auth service
"""

import requests
import json
import sys
import os
import jwt
from datetime import datetime, timedelta

# Configuration
AI_MOCKUP_URL = "http://localhost:8021"
USER_AUTH_URL = "http://localhost:8011"
TEST_USER_EMAIL = "test@example.com"
TEST_USER_PASSWORD = "testpassword123"

def test_user_auth_service():
    """Test if user-auth service is running and accessible"""
    print("🔍 Testing user-auth service...")
    try:
        response = requests.get(f"{USER_AUTH_URL}/health", timeout=10)
        if response.status_code == 200:
            print(f"✅ User-auth service is running: {response.json()}")
            return True
        else:
            print(f"❌ User-auth service health check failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ User-auth service error: {e}")
        return False

def test_ai_mockup_service():
    """Test if ai-mockup service is running and accessible"""
    print("🔍 Testing ai-mockup service...")
    try:
        response = requests.get(f"{AI_MOCKUP_URL}/api/health", timeout=10)
        if response.status_code == 200:
            print(f"✅ AI-mockup service is running: {response.json()}")
            return True
        else:
            print(f"❌ AI-mockup service health check failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ AI-mockup service error: {e}")
        return False

def test_token_verification_endpoint():
    """Test the token verification endpoint in user-auth service"""
    print("🔍 Testing token verification endpoint...")
    
    # Create a test JWT token
    test_payload = {
        'userId': 'test-user-id',
        'email': TEST_USER_EMAIL,
        'username': 'testuser',
        'role': 'user',
        'exp': datetime.utcnow() + timedelta(hours=1),
        'iat': datetime.utcnow(),
        'iss': 'tech4biz-auth',
        'aud': 'tech4biz-users'
    }
    
    # Use the same secret as configured in the services
    test_secret = 'access-secret-key-2024-tech4biz'
    test_token = jwt.encode(test_payload, test_secret, algorithm='HS256')
    
    try:
        response = requests.get(
            f"{USER_AUTH_URL}/api/auth/verify",
            headers={'Authorization': f'Bearer {test_token}'},
            timeout=10
        )
        
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                print(f"✅ Token verification endpoint working: {result}")
                return True
            else:
                print(f"❌ Token verification failed: {result}")
                return False
        else:
            print(f"❌ Token verification endpoint failed: {response.status_code}")
            try:
                error_data = response.json()
                print(f"   Error: {error_data}")
            except:
                print(f"   Error text: {response.text}")
            return False
    except Exception as e:
        print(f"❌ Token verification test error: {e}")
        return False

def test_ai_mockup_with_auth():
    """Test ai-mockup service with authentication"""
    print("🔍 Testing ai-mockup service with authentication...")
    
    # Create a test JWT token
    test_payload = {
        'userId': 'test-user-id',
        'email': TEST_USER_EMAIL,
        'username': 'testuser',
        'role': 'user',
        'exp': datetime.utcnow() + timedelta(hours=1),
        'iat': datetime.utcnow(),
        'iss': 'tech4biz-auth',
        'aud': 'tech4biz-users'
    }
    
    test_secret = 'access-secret-key-2024-tech4biz'
    test_token = jwt.encode(test_payload, test_secret, algorithm='HS256')
    
    try:
        # Test a protected endpoint (assuming there's one)
        response = requests.get(
            f"{AI_MOCKUP_URL}/api/protected-endpoint",
            headers={'Authorization': f'Bearer {test_token}'},
            timeout=10
        )
        
        # This might return 404 if the endpoint doesn't exist, but should not return 401
        if response.status_code == 401:
            print(f"❌ Authentication still failing: {response.status_code}")
            try:
                error_data = response.json()
                print(f"   Error: {error_data}")
            except:
                print(f"   Error text: {response.text}")
            return False
        else:
            print(f"✅ Authentication working (status: {response.status_code})")
            return True
    except Exception as e:
        print(f"❌ AI-mockup auth test error: {e}")
        return False

def main():
    """Run all authentication tests"""
    print("🚀 Starting authentication tests...\n")
    
    tests = [
        test_user_auth_service,
        test_ai_mockup_service,
        test_token_verification_endpoint,
        test_ai_mockup_with_auth
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        try:
            if test():
                passed += 1
            print()
        except Exception as e:
            print(f"❌ Test {test.__name__} crashed: {e}\n")
    
    print(f"📊 Test Results: {passed}/{total} tests passed")
    
    if passed == total:
        print("🎉 All authentication tests passed!")
        return 0
    else:
        print("⚠️  Some authentication tests failed. Check the logs above.")
        return 1

if __name__ == "__main__":
    sys.exit(main())
