from flask import Flask
from flask_mail import Mail, Message
from dotenv import load_dotenv
import os

load_dotenv()

app = Flask(__name__)

# Load config from .env
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'localhost')
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 25))
app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'False').lower() in ['true', '1', 't']
app.config['MAIL_USE_SSL'] = os.getenv('MAIL_USE_SSL', 'False').lower() in ['true', '1', 't']
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', '')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', '')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', 'noreply@collnetwork.net')

print("=" * 50)
print("EMAIL CONFIGURATION TEST")
print("=" * 50)
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_USE_SSL: {app.config['MAIL_USE_SSL']}")
print(f"MAIL_USERNAME: {app.config['MAIL_USERNAME'] or '(empty - using localhost)'}")
print(f"MAIL_PASSWORD: {'*' * len(app.config['MAIL_PASSWORD']) if app.config['MAIL_PASSWORD'] else '(empty - using localhost)'}")
print(f"MAIL_DEFAULT_SENDER: {app.config['MAIL_DEFAULT_SENDER']}")
print("=" * 50)

# FIX: Don't exit if password is empty when using localhost
if app.config['MAIL_SERVER'] != 'localhost' and not app.config['MAIL_PASSWORD']:
    print("❌ ERROR: Password required for remote SMTP servers!")
    exit(1)

mail = Mail(app)

with app.app_context():
    try:
        print("\n📧 Attempting to send test email...")
        msg = Message(
            subject='Test Email from Collnetwork',
            recipients=['info@collnetwork.net'],
            body='This is a test email. If you receive this, your configuration is working!'
        )
        mail.send(msg)
        print("✅ SUCCESS! Email sent successfully!")
    except Exception as e:
        print(f"❌ ERROR: {str(e)}")
        print(f"\nFull error details:")
        import traceback
        traceback.print_exc()