#!/usr/bin/env python3
"""
Simple SMTP email sender for echo@romfast.ro
Usage: python3 email_send.py "recipient@email.com" "Subject" "Body text"
"""

import smtplib
import ssl
import sys
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
from pathlib import Path

# Load .env file
env_path = Path(__file__).parent.parent / '.env'
if env_path.exists():
    with open(env_path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, value = line.split('=', 1)
                os.environ.setdefault(key, value)

# SMTP Configuration from environment
# Try Gmail first, fall back to romfast
if os.environ.get('GMAIL_PASSWORD'):
    SMTP_SERVER = 'smtp.gmail.com'
    SMTP_PORT = 465
    SMTP_USER = os.environ.get('GMAIL_USER', 'mmarius28@gmail.com')
    SMTP_PASS = os.environ.get('GMAIL_PASSWORD', '')
else:
    SMTP_SERVER = os.environ.get('EMAIL_SERVER', 'mail.romfast.ro')
    SMTP_PORT = 465
    SMTP_USER = os.environ.get('EMAIL_USER', 'echo@romfast.ro')
    SMTP_PASS = os.environ.get('EMAIL_PASSWORD', '')
FROM_NAME = "Echo"

def send_email(to_email: str, subject: str, body: str, html: bool = False) -> dict:
    """Send an email via SMTP SSL"""
    try:
        # Create message
        msg = MIMEMultipart("alternative")
        msg["Subject"] = Header(subject, 'utf-8')
        msg["From"] = formataddr((FROM_NAME, SMTP_USER))
        msg["To"] = to_email
        msg["Reply-To"] = "echo@romfast.ro"
        
        # Attach body
        if html:
            msg.attach(MIMEText(body, "html", "utf-8"))
        else:
            msg.attach(MIMEText(body, "plain", "utf-8"))
        
        # Connect and send
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server:
            server.login(SMTP_USER, SMTP_PASS)
            server.sendmail(SMTP_USER, to_email, msg.as_string())
        
        return {"ok": True, "to": to_email, "subject": subject}
    
    except Exception as e:
        return {"ok": False, "error": str(e)}

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: python3 email_send.py <to> <subject> <body> [--html]")
        sys.exit(1)
    
    to = sys.argv[1]
    subject = sys.argv[2]
    body = sys.argv[3]
    
    # Auto-detect HTML or use --html flag
    # Check for common HTML patterns, not just doctype/html tags
    body_lower = body.strip().lower()
    has_html_tags = any(tag in body_lower for tag in ['<html', '<!doctype', '<div', '<p>', '<br', '<table', '<h1', '<h2', '<h3', '<span', '<style'])
    is_html = "--html" in sys.argv or has_html_tags
    
    result = send_email(to, subject, body, html=is_html)
    
    import json
    print(json.dumps(result))
