#!/usr/bin/env python3
"""
Test suite for authentication functionality
"""

import os
import sys
from unittest.mock import patch, MagicMock

# Add parent directory to path to import modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from auth.auth_service import AuthService


class TestAuthentication:
    """Test class for authentication functionality"""
    
    def __init__(self):
        self.test_results = []
        
    def test_auth_service_initialization(self):
        """Test that AuthService initializes properly"""
        try:
            auth_service = AuthService()
            
            # Check if required attributes exist
            required_attrs = [
                'twitter_client', 'facebook_api_url', 'facebook_access_token',
                'twitter_authenticated', 'facebook_authenticated'
            ]
            
            missing_attrs = []
            for attr in required_attrs:
                if not hasattr(auth_service, attr):
                    missing_attrs.append(attr)
            
            if not missing_attrs:
                self.test_results.append(("Auth Service Initialization", True, "AuthService initialized with all required attributes"))
                return True
            else:
                self.test_results.append(("Auth Service Initialization", False, f"Missing attributes: {missing_attrs}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Auth Service Initialization", False, f"Exception: {e}"))
            return False
    
    def test_twitter_authentication_status(self):
        """Test Twitter authentication status checking"""
        try:
            auth_service = AuthService()
            
            # Test authentication status methods
            twitter_auth = auth_service.is_twitter_authenticated()
            facebook_auth = auth_service.is_facebook_authenticated()
            
            # These should return boolean values
            if isinstance(twitter_auth, bool) and isinstance(facebook_auth, bool):
                self.test_results.append(("Authentication Status", True, f"Twitter: {twitter_auth}, Facebook: {facebook_auth}"))
                return True
            else:
                self.test_results.append(("Authentication Status", False, f"Invalid return types - Twitter: {type(twitter_auth)}, Facebook: {type(facebook_auth)}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Authentication Status", False, f"Exception: {e}"))
            return False
    
    def test_twitter_client_retrieval(self):
        """Test Twitter client retrieval"""
        try:
            auth_service = AuthService()
            twitter_client = auth_service.get_twitter_client()
            
            # Client should be None if not authenticated, or a valid client object if authenticated
            if twitter_client is None or hasattr(twitter_client, 'create_tweet'):
                self.test_results.append(("Twitter Client Retrieval", True, "Twitter client retrieved successfully"))
                return True
            else:
                self.test_results.append(("Twitter Client Retrieval", False, f"Invalid client type: {type(twitter_client)}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Twitter Client Retrieval", False, f"Exception: {e}"))
            return False
    
    def test_facebook_api_retrieval(self):
        """Test Facebook API URL and token retrieval"""
        try:
            auth_service = AuthService()
            api_url = auth_service.get_facebook_api_url()
            access_token = auth_service.get_facebook_access_token()
            
            # API URL should be a string (even if empty)
            # Access token should be a string (even if empty)
            if isinstance(api_url, str) and isinstance(access_token, str):
                self.test_results.append(("Facebook API Retrieval", True, f"API URL: {api_url[:50]}..., Token: {'*' * len(access_token) if access_token else 'None'}"))
                return True
            else:
                self.test_results.append(("Facebook API Retrieval", False, f"Invalid types - URL: {type(api_url)}, Token: {type(access_token)}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Facebook API Retrieval", False, f"Exception: {e}"))
            return False
    
    def test_environment_variable_handling(self):
        """Test environment variable handling"""
        try:
            # Test with mock environment variables
            test_env = {
                'TWITTER_API_KEY': '8pwoQwNNE4gmMy4L5eC0PBwr7',
                'TWITTER_API_SECRET': 'eIZMNQd5GDNavLOx7bAeazJrKMM6COhUYHh0iKI4k3CgkfMEs9',
                'TWITTER_ACCESS_TOKEN': '3239141911-rXqY23b7OcFue6NDBQklHxJ3TSyAU78UKIsq1Hz',
                'TWITTER_ACCESS_TOKEN_SECRET': 'fiDyC0G95FVeBDksmdE8IOYrK6ByghZ0NTThdtamx1UBN',
                'FACEBOOK_ACCESS_TOKEN': 'EAAJboXyzW5EBPbEbUEzZA0SDYv0k93UlKJ9qinIZA7EsAp3eYV6PEHP6QUKfugDf4aGfrH7oZAhqxfZCo1txMuCPUnhJlds8H8VDHe8m7dZBn2KdcPgdJzF9WRfEKwnfUvSRgMCe46E9TmeOm8w6srmRTYXyylIZA7KdaUpQLRZCGxZBurhqh4bbOBQajKbgI4ZC3c6CpiqkGCmfm4TZA2MgZDZD',
                'FACEBOOK_PAGE_ID': '794458810416162'
            }
            
            with patch.dict(os.environ, test_env):
                auth_service = AuthService()
                
                # Should not raise exceptions even with test environment
                self.test_results.append(("Environment Variable Handling", True, "AuthService handles environment variables properly"))
                return True
                
        except Exception as e:
            self.test_results.append(("Environment Variable Handling", False, f"Exception: {e}"))
            return False
    
    def test_missing_credentials_handling(self):
        """Test handling of missing credentials"""
        try:
            # Test with empty environment
            with patch.dict(os.environ, {}, clear=True):
                auth_service = AuthService()
                
                # Should handle missing credentials gracefully
                twitter_auth = auth_service.is_twitter_authenticated()
                facebook_auth = auth_service.is_facebook_authenticated()
                
                # Should return False for both when credentials are missing
                if not twitter_auth and not facebook_auth:
                    self.test_results.append(("Missing Credentials Handling", True, "Properly handles missing credentials"))
                    return True
                else:
                    self.test_results.append(("Missing Credentials Handling", False, f"Unexpected auth status - Twitter: {twitter_auth}, Facebook: {facebook_auth}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("Missing Credentials Handling", False, f"Exception: {e}"))
            return False
    
    def run_all_tests(self):
        """Run all authentication tests"""
        print("\n" + "="*60)
        print("🔐 RUNNING AUTHENTICATION TESTS")
        print("="*60)
        
        # Run all tests
        tests = [
            self.test_auth_service_initialization,
            self.test_twitter_authentication_status,
            self.test_twitter_client_retrieval,
            self.test_facebook_api_retrieval,
            self.test_environment_variable_handling,
            self.test_missing_credentials_handling
        ]
        
        passed = 0
        total = len(tests)
        
        for test in tests:
            print(f"\n🔍 Running {test.__name__}...")
            if test():
                passed += 1
                print(f"✅ {test.__name__} PASSED")
            else:
                print(f"❌ {test.__name__} FAILED")
        
        # Print summary
        print("\n" + "="*60)
        print("📊 AUTHENTICATION TEST SUMMARY")
        print("="*60)
        print(f"Total Tests: {total}")
        print(f"Passed: {passed}")
        print(f"Failed: {total - passed}")
        print(f"Success Rate: {(passed/total)*100:.1f}%")
        
        # Print detailed results
        print("\n📋 Detailed Results:")
        for test_name, success, message in self.test_results:
            status = "✅ PASS" if success else "❌ FAIL"
            print(f"  {status} {test_name}: {message}")
        
        return passed == total


def run_authentication_tests():
    """Main function to run authentication tests"""
    tester = TestAuthentication()
    return tester.run_all_tests()


if __name__ == "__main__":
    success = run_authentication_tests()
    exit(0 if success else 1)