#!/usr/bin/env python3
"""
Advanced Authentication Feature Tests for Adtlas Django Application

This script tests advanced authentication features:
1. Role-based access control
2. Session management  
3. Account security features
4. User management functions
"""

import requests
import json
import time
from datetime import datetime

class AdvancedAuthTester:
    def __init__(self, base_url="http://localhost:8002"):
        self.base_url = base_url
        self.session = requests.Session()
        
    def test_admin_access(self):
        """Test admin panel accessibility"""
        try:
            response = self.session.get(f"{self.base_url}/admin/")
            # Should redirect to login
            passed = response.status_code in [200, 302] and 'admin' in response.url
            print(f"Admin Panel Access: {'PASSED' if passed else 'FAILED'} - Status: {response.status_code}")
            return passed
        except Exception as e:
            print(f"Admin Panel Access: FAILED - {e}")
            return False
            
    def test_authenticated_endpoints(self):
        """Test endpoints that require authentication"""
        endpoints = [
            "/accounts/profile/",
            "/auth/logout",
        ]
        
        for endpoint in endpoints:
            try:
                response = self.session.get(f"{self.base_url}{endpoint}")
                # Should redirect to login for unauthenticated users
                passed = response.status_code in [302, 403] or 'login' in response.url
                print(f"Protected Endpoint {endpoint}: {'PASSED' if passed else 'FAILED'} - Status: {response.status_code}")
            except Exception as e:
                print(f"Protected Endpoint {endpoint}: FAILED - {e}")
                
    def test_health_endpoints(self):
        """Test application health endpoints"""
        try:
            response = self.session.get(f"{self.base_url}/health")
            passed = response.status_code in [200, 404]  # 404 is fine if not implemented
            print(f"Health Endpoint: {'PASSED' if passed else 'FAILED'} - Status: {response.status_code}")
        except Exception as e:
            print(f"Health Endpoint: ERROR - {e}")
            
    def test_static_files(self):
        """Test static file serving"""
        try:
            response = self.session.get(f"{self.base_url}/static/images/brands/favicon.ico")
            passed = response.status_code == 200
            print(f"Static Files: {'PASSED' if passed else 'FAILED'} - Status: {response.status_code}")
        except Exception as e:
            print(f"Static Files: ERROR - {e}")
            
    def test_security_headers(self):
        """Test security headers"""
        try:
            response = self.session.get(f"{self.base_url}/auth/login")
            headers = response.headers
            
            security_checks = {
                'X-Frame-Options': 'X-Frame-Options' in headers,
                'X-Content-Type-Options': 'X-Content-Type-Options' in headers,
                'Referrer-Policy': 'Referrer-Policy' in headers
            }
            
            passed = sum(security_checks.values()) >= 2  # At least 2 security headers
            print(f"Security Headers: {'PASSED' if passed else 'FAILED'} - Found: {sum(security_checks.values())}/3")
            
            for header, present in security_checks.items():
                print(f"  - {header}: {'✓' if present else '✗'}")
                
        except Exception as e:
            print(f"Security Headers: ERROR - {e}")
            
    def run_advanced_tests(self):
        """Run all advanced tests"""
        print("=" * 60)
        print("ADTLAS ADVANCED AUTHENTICATION TESTS")
        print("=" * 60)
        
        self.test_admin_access()
        self.test_authenticated_endpoints()
        self.test_health_endpoints() 
        self.test_static_files()
        self.test_security_headers()
        
        print("=" * 60)
        print("Advanced testing completed!")
        print("=" * 60)

if __name__ == "__main__":
    tester = AdvancedAuthTester()
    tester.run_advanced_tests()
