import smtplib
import socket
import os
from email.mime.text import MIMEText
from email.utils import formatdate

def load_env_vars():
    env_vars = {}
    if os.path.exists('.env'):
        with open('.env', 'r') as f:
            for line in f:
                if line.strip() and not line.startswith('#'):
                    try:
                        key, value = line.strip().split('=', 1)
                        if value.startswith('"') and value.endswith('"'):
                            value = value[1:-1]
                        env_vars[key] = value
                    except ValueError: continue
    return env_vars

def test_live_connection():
    env = load_env_vars()

    # Get from env, or fall back to known defaults for debugging
    host = env.get('SMTP_HOST', "mail.privateemail.com")
    port = int(env.get('SMTP_PORT', 587))
    user = env.get('SMTP_USER', "info@thinkedgeconsultancy.com")
    pw = env.get('SMTP_PASS', "Cyberboy26####")
    sender = env.get('SMTP_FROM', user)
    recipient = env.get('SMTP_TO', "adoxop1@gmail.com")

    print(f"--- Live Server SMTP Test ---")
    print(f"Target: {host}:{port}")
    print(f"User: {user}")
    print(f"Password starts with: {pw[:3]}***")

    # 1. Test DNS
    try:
        ip = socket.gethostbyname(host)
        print(f"✅ DNS Resolved: {host} -> {ip}")
    except Exception as e:
        print(f"❌ DNS Failed: {e}")
        return

    # 2. Test Connection
    try:
        print(f"Connecting to {host}:{port}...")
        server = smtplib.SMTP(host, port, timeout=15)
        print(f"✅ Connection successful!")

        print("Starting TLS (STARTTLS)...")
        server.starttls()
        print(f"✅ TLS established!")

        print(f"Logging in...")
        server.login(user, pw)
        print(f"✅ Login successful!")

        msg = MIMEText("This is a test from the live server script.")
        msg['Subject'] = "Live Server Test Email"
        msg['From'] = f"AeroMail Support <{sender}>"
        msg['To'] = recipient
        msg['Date'] = formatdate(localtime=True)

        print(f"Sending to {recipient}...")
        server.sendmail(sender, [recipient], msg.as_string())
        server.quit()
        print(f"✅ EMAIL SENT SUCCESSFULLY!")

    except Exception as e:
        print(f"❌ SMTP Error: {type(e).__name__}: {e}")
        if "(535," in str(e):
            print("\n🚨 TIP: '535 Incorrect authentication data' means the password or username is wrong.")
            print("1. Confirm if you need to enable SMTP in your PrivateEmail dashboard.")
            print("2. Verify your password doesn't have trailing spaces in the .env.")
            print("3. Log into webmail.privateemail.com manually to confirm the password.")

if __name__ == "__main__":
    test_live_connection()
