#!/usr/bin/env python
"""
Test script for Notification Simulator API.

This script demonstrates how to use the simulator to test email and SMS notifications.
Run this after starting the development server and enabling the simulator in .env.

Usage:
    python test_simulator.py
"""
import os
import sys
import django
import requests

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.base')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
django.setup()

from apps.notifications.services import NotificationService


def print_header(text):
    """Print a formatted header."""
    print(f"\n{'='*70}")
    print(f"{text:^70}")
    print(f"{'='*70}\n")


def print_success(text):
    """Print success message in green."""
    print(f"✅ {text}")


def print_error(text):
    """Print error message in red."""
    print(f"❌ {text}")


def test_email_simulator():
    """Test the email simulator."""
    print_header("Testing Email Simulator")
    
    try:
        # Test plain text email
        print("Sending plain text email...")
        log = NotificationService.send_email_via_api(
            message='This is a test email from the PX360 simulator.',
            email='test@example.com',
            subject='Test Email - Plain Text'
        )
        
        if log and log.status == 'sent':
            print_success("Plain text email sent successfully!")
            print(f"   Log ID: {log.id}")
            print(f"   Status: {log.status}")
        else:
            print_error("Failed to send plain text email")
            return False
        
        # Test HTML email
        print("\nSending HTML email...")
        log = NotificationService.send_email_via_api(
            message='Please view this email in HTML mode.',
            email='test@example.com',
            subject='Test Email - HTML',
            html_message='<h1>HTML Test</h1><p>This is <strong>formatted</strong> text.</p>'
        )
        
        if log and log.status == 'sent':
            print_success("HTML email sent successfully!")
            print(f"   Log ID: {log.id}")
            print(f"   Status: {log.status}")
        else:
            print_error("Failed to send HTML email")
            return False
        
        return True
        
    except Exception as e:
        print_error(f"Error testing email simulator: {str(e)}")
        return False


def test_sms_simulator():
    """Test the SMS simulator."""
    print_header("Testing SMS Simulator")
    
    try:
        # Test short SMS
        print("Sending short SMS...")
        log = NotificationService.send_sms_via_api(
            message='This is a test SMS from PX360 simulator.',
            phone='+966501234567'
        )
        
        if log and log.status == 'sent':
            print_success("Short SMS sent successfully!")
            print(f"   Log ID: {log.id}")
            print(f"   Status: {log.status}")
        else:
            print_error("Failed to send short SMS")
            return False
        
        # Test long SMS with word wrapping
        print("\nSending long SMS (with word wrapping)...")
        log = NotificationService.send_sms_via_api(
            message='This is a much longer SMS message to test the word wrapping functionality of the simulator. It should display properly formatted in the terminal output.',
            phone='+966501234567'
        )
        
        if log and log.status == 'sent':
            print_success("Long SMS sent successfully!")
            print(f"   Log ID: {log.id}")
            print(f"   Status: {log.status}")
        else:
            print_error("Failed to send long SMS")
            return False
        
        return True
        
    except Exception as e:
        print_error(f"Error testing SMS simulator: {str(e)}")
        return False


def test_health_check():
    """Test the health check endpoint."""
    print_header("Checking Simulator Health")
    
    try:
        response = requests.get('http://localhost:8000/api/simulator/health')
        
        if response.status_code == 200:
            data = response.json()
            print_success("Simulator is healthy!")
            print(f"   Status: {data['status']}")
            print(f"   Total Requests: {data['statistics']['total_requests']}")
            print(f"   Email Requests: {data['statistics']['email_requests']}")
            print(f"   SMS Requests: {data['statistics']['sms_requests']}")
            return True
        else:
            print_error(f"Health check failed with status {response.status_code}")
            return False
            
    except requests.exceptions.ConnectionError:
        print_error("Cannot connect to simulator. Is the server running?")
        return False
    except Exception as e:
        print_error(f"Error checking health: {str(e)}")
        return False


def test_error_handling():
    """Test error handling in simulator."""
    print_header("Testing Error Handling")
    
    # Test missing fields
    print("\nTesting missing fields in email...")
    response = requests.post(
        'http://localhost:8000/api/simulator/send-email',
        json={'to': 'test@example.com'}  # Missing subject and message
    )
    
    if response.status_code == 400:
        data = response.json()
        if not data['success'] and 'Missing required fields' in data['error']:
            print_success("Missing fields error handled correctly!")
            print(f"   Error: {data['error']}")
        else:
            print_error("Unexpected error response")
    else:
        print_error(f"Expected 400, got {response.status_code}")
    
    # Test invalid JSON
    print("\nTesting invalid JSON...")
    response = requests.post(
        'http://localhost:8000/api/simulator/send-sms',
        data='invalid json'
    )
    
    if response.status_code == 400:
        data = response.json()
        if not data['success'] and 'Invalid JSON format' in data['error']:
            print_success("Invalid JSON error handled correctly!")
            print(f"   Error: {data['error']}")
        else:
            print_error("Unexpected error response")
    else:
        print_error(f"Expected 400, got {response.status_code}")


def reset_simulator():
    """Reset the simulator counters."""
    print_header("Resetting Simulator")
    
    try:
        response = requests.get('http://localhost:8000/api/simulator/reset')
        
        if response.status_code == 200:
            print_success("Simulator reset successfully!")
            return True
        else:
            print_error(f"Reset failed with status {response.status_code}")
            return False
            
    except Exception as e:
        print_error(f"Error resetting simulator: {str(e)}")
        return False


def main():
    """Main test function."""
    print("\n" + "="*70)
    print("PX360 Notification Simulator Test Suite".center(70))
    print("="*70)
    
    # Check if simulator is accessible
    print("\nChecking if simulator is accessible...")
    health_ok = test_health_check()
    
    if not health_ok:
        print_error("\nSimulator is not accessible!")
        print("\nPlease ensure:")
        print("1. Development server is running: python manage.py runserver")
        print("2. Simulator is enabled in .env file")
        print("3. URLs point to localhost:8000/api/simulator/...")
        return
    
    # Run tests
    email_ok = test_email_simulator()
    sms_ok = test_sms_simulator()
    test_error_handling()
    
    # Show final statistics
    print_header("Final Statistics")
    response = requests.get('http://localhost:8000/api/simulator/health')
    data = response.json()
    stats = data['statistics']
    
    print(f"Total Requests: {stats['total_requests']}")
    print(f"Email Requests: {stats['email_requests']}")
    print(f"SMS Requests: {stats['sms_requests']}")
    
    # Summary
    print_header("Test Summary")
    if email_ok and sms_ok:
        print_success("All tests passed! 🎉")
    else:
        print_error("Some tests failed. Please check the output above.")
    
    print("\nCheck your terminal for formatted email and SMS outputs.")
    print("Check logs/px360.log for detailed logs.")
    print(f"\n{'='*70}\n")


if __name__ == '__main__':
    main()
