"""
Live Site End-to-End Workflow Test for rateright.com.au
Tests the complete lifecycle through the production website
"""

import time
import requests
from datetime import datetime, timezone
import logging
import random
import string

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class RateRightLiveSiteTest:
    """Comprehensive live site testing for rateright.com.au"""
    
    def __init__(self):
        self.base_url = "https://rateright.com.au"
        self.test_results = {
            'passed': [],
            'failed': [],
            'warnings': []
        }
        # Generate unique test data to avoid conflicts
        self.test_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
        self.contractor_email = f"contractor_test_{self.test_id}@example.com"
        self.worker_email = f"worker_test_{self.test_id}@example.com"
        
    def log_result(self, status, message):
        """Log test results"""
        if status == 'PASS':
            self.test_results['passed'].append(message)
            logger.info(f"✅ PASS: {message}")
        elif status == 'FAIL':
            self.test_results['failed'].append(message)
            logger.error(f"❌ FAIL: {message}")
        elif status == 'WARN':
            self.test_results['warnings'].append(message)
            logger.warning(f"⚠️ WARN: {message}")
    
    def test_site_availability(self):
        """Test if the site is accessible"""
        logger.info("\n" + "="*60)
        logger.info("TESTING SITE AVAILABILITY")
        logger.info("="*60)
        
        try:
            # Test HTTPS
            response = requests.get(self.base_url, timeout=10, allow_redirects=True)
            if response.status_code == 200:
                self.log_result('PASS', f"Site is accessible at {self.base_url}")
                
                # Check for key indicators
                content = response.text.lower()
                if 'rateright' in content:
                    self.log_result('PASS', "RateRight branding found on homepage")
                else:
                    self.log_result('WARN', "RateRight branding not found in homepage content")
                
                # Check SSL certificate
                if response.url.startswith('https://'):
                    self.log_result('PASS', "SSL certificate is active")
                else:
                    self.log_result('WARN', "Site not using HTTPS")
                    
            else:
                self.log_result('FAIL', f"Site returned status code: {response.status_code}")
                
        except requests.exceptions.Timeout:
            self.log_result('FAIL', "Site timed out (>10 seconds)")
        except requests.exceptions.SSLError as e:
            self.log_result('FAIL', f"SSL certificate error: {e}")
        except Exception as e:
            self.log_result('FAIL', f"Failed to access site: {e}")
    
    def test_critical_endpoints(self):
        """Test critical application endpoints"""
        logger.info("\n" + "="*60)
        logger.info("TESTING CRITICAL ENDPOINTS")
        logger.info("="*60)
        
        endpoints = [
            ('/', 'Homepage'),
            ('/auth/register', 'Registration'),
            ('/auth/login', 'Login'),
            ('/jobs', 'Jobs listing'),
            ('/dashboard', 'Dashboard'),
            ('/api/health', 'API Health')
        ]
        
        session = requests.Session()
        
        for endpoint, name in endpoints:
            url = f"{self.base_url}{endpoint}"
            try:
                response = session.get(url, timeout=5, allow_redirects=True)
                
