#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test email sending functionality
"""
import os
from dotenv import load_dotenv
from flask import Flask
from flask_mail import Mail, Message

load_dotenv()

app = Flask(__name__)
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER')
app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', 587))
app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS', 'true').lower() in ['true', 'on', '1']
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')

mail = Mail(app)

def test_email():
    print("=== Testing Email Configuration ===")
    print(f"Mail Server: {app.config['MAIL_SERVER']}")
    print(f"Mail Port: {app.config['MAIL_PORT']}")
    print(f"Mail Use TLS: {app.config['MAIL_USE_TLS']}")
    print(f"Mail Username: {app.config['MAIL_USERNAME']}")
    print(f"Mail Password: {'*' * len(app.config['MAIL_PASSWORD']) if app.config['MAIL_PASSWORD'] else 'Not set'}")
    print(f"Default Sender: {app.config['MAIL_DEFAULT_SENDER']}")
    print()

    try:
        with app.app_context():
            # Create test message
            msg = Message(
                subject='Test Email - Survey Manager',
                recipients=[app.config['MAIL_USERNAME']],  # Send to self
                sender=app.config['MAIL_DEFAULT_SENDER']
            )

            msg.html = """
            <html>
            <body style="font-family: Arial, sans-serif; padding: 20px;">
                <h2 style="color: #667eea;">✅ Email Test Successful!</h2>
                <p>This is a test email from Survey Manager.</p>
                <p>If you're reading this, your email configuration is working correctly!</p>
                <hr>
                <p style="color: #666; font-size: 12px;">
                    This is an automated test email.
                </p>
            </body>
            </html>
            """

            print("Sending test email...")
            mail.send(msg)
            print("✅ Test email sent successfully!")
            print(f"Check your inbox at: {app.config['MAIL_USERNAME']}")
            return True

    except Exception as e:
        print(f"❌ Error sending email: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    success = test_email()
    exit(0 if success else 1)
