
import os
import sys
import logging
from datetime import datetime

# Ensure the backend directory is in the path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

try:
    from services.email_service import email_service
except ImportError:
    # If running from root, adjust path
    sys.path.append(os.path.join(os.getcwd(), 'backend'))
    from services.email_service import email_service

def load_env_file():
    """Simple .env loader to avoid extra dependencies for this test script"""
    env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
    if not os.path.exists(env_path):
        print(f"[WARN] No .env file found at {env_path}")
        return

    print(f"[INFO] Loading environment from {env_path}")
    with open(env_path, 'r') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            try:
                key, value = line.split('=', 1)
                os.environ[key] = value.strip("'").strip('"')
            except ValueError:
                pass

def test_smtp_connection():
    # Load .env first
    load_env_file()
    
    # Re-import service to pick up env vars
    # We need to re-instantiate or re-import because the original import 
    # might have happened before env vars were set if this was a module.
    # However, since we import inside the function or after setting env in main, 
    # we should check how it was imported at top level.
    # The top level import `from services.email_service import email_service` 
    # instantiated the class immediately. We need to re-instantiate it.
    
    from services.email_service import EmailService
    email_service = EmailService()

    print("="*60)
    print("ELMEG SMTP CONNECTION TEST")
    print("="*60)

    # 1. Print Configuration
    print("\n[1] Configuration Check:")
    print(f"   Provider: {email_service.provider}")
    print(f"   SMTP Host: {email_service.smtp_host}")
    print(f"   SMTP Port: {email_service.smtp_port}")
    print(f"   SMTP Username: {email_service.smtp_username}")
    print(f"   SMTP TLS: {email_service.smtp_use_tls}")
    print(f"   From Email: {email_service.email_from}")

    if email_service.provider != "smtp":
        print("\n[!] ERROR: Email service is NOT configured for SMTP.")
        print(f"    Current provider is: {email_service.provider}")
        print("    Please set SMTP_HOST, SMTP_PORT, SMTP_USERNAME, and SMTP_PASSWORD environment variables.")
        return

    # 2. Ask for recipient
    if len(sys.argv) > 1:
        recipient = sys.argv[1]
    else:
        recipient = input("\nEnter recipient email address for test (e.g. your@email.com): ").strip()
        if not recipient:
            print("No recipient provided. Aborting.")
            return

    # 3. Send Test Email
    print(f"\n[2] Attempting to send test email to: {recipient}")
    
    subject = f"Elmeg Postal SMTP Test - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    text_content = f"This is a test email from the Elmeg backend to verify Postal SMTP connectivity.\n\nSent at: {datetime.now()}"
    html_content = f"""
    <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px;">
        <h2 style="color: #2563eb; border-bottom: 2px solid #f0f0f0; padding-bottom: 10px;">Elmeg SMTP Test</h2>
        <p>Aloha!</p>
        <p>This email confirms that your <strong>Elmeg</strong> backend is successfully connected to the Postal SMTP server.</p>
        <div style="background-color: #f8fafc; padding: 15px; border-radius: 4px; margin: 20px 0;">
            <p style="margin: 0; font-family: monospace;">Server: {email_service.smtp_host}</p>
            <p style="margin: 0; font-family: monospace;">Port: {email_service.smtp_port}</p>
            <p style="margin: 0; font-family: monospace;">User: {email_service.smtp_username}</p>
        </div>
        <p style="color: #64748b; font-size: 12px; margin-top: 30px;">Sent at {datetime.now()}</p>
    </div>
    """

    try:
        success = email_service.send_email(recipient, subject, html_content, text_content)
        
        if success:
            print("\n[SUCCESS] Email accepted by SMTP server!")
            print("Check your inbox (and spam folder) for the message.")
        else:
            print("\n[FAILURE] SMTP server rejected the message or connection failed.")
    except Exception as e:
        print(f"\n[EXCEPTION] An unexpected error occurred: {e}")

if __name__ == "__main__":
    test_smtp_connection()
