#!/usr/bin/env python3
import os
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_mail(smtp_host, smtp_port, user, password, from_addr, to_list, subject, body):
    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_list)
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    port = int(smtp_port)
    if port == 465:
        server = smtplib.SMTP_SSL(smtp_host, port, timeout=30)
    else:
        server = smtplib.SMTP(smtp_host, port, timeout=30)
        server.ehlo()
        try:
            server.starttls()
            server.ehlo()
        except Exception:
            pass
    server.login(user, password)
    server.sendmail(from_addr, to_list, msg.as_string())
    server.quit()

if __name__ == '__main__':
    # Usage: test_send_email_env.py SUBJECT BODY_FILE
    if len(sys.argv) < 3:
        print('Usage: test_send_email_env.py "SUBJECT" path/to/body.txt')
        sys.exit(2)
    subject = sys.argv[1]
    body_file = sys.argv[2]
    if not os.path.isfile(body_file):
        print('Body file not found:', body_file)
        sys.exit(2)
    with open(body_file, 'r', encoding='utf-8') as f:
        body = f.read()

    # Read env
    SMTP_HOST = os.environ.get('SMTP_HOST')
    SMTP_PORT = os.environ.get('SMTP_PORT', '587')
    SMTP_USER = os.environ.get('SMTP_USER')
    SMTP_PASS = os.environ.get('SMTP_PASS')
    FROM_ADDR = os.environ.get('FROM_ADDR', SMTP_USER)
    RECIPIENTS = os.environ.get('RECIPIENTS')  # comma-separated

    missing = [k for k, v in [('SMTP_HOST', SMTP_HOST), ('SMTP_USER', SMTP_USER), ('SMTP_PASS', SMTP_PASS), ('RECIPIENTS', RECIPIENTS)] if not v]
    if missing:
        print('Missing required environment variables:', ', '.join(missing))
        sys.exit(2)

    to_list = [r.strip() for r in RECIPIENTS.split(',') if r.strip()]
    if not to_list:
        print('No recipients specified in RECIPIENTS')
        sys.exit(2)

    # safety: don't run if SMTP_PASS is placeholder
    if SMTP_PASS.startswith('REPLACE_'):
        print('SMTP_PASS looks like a placeholder. Please set a real password in environment or .env.')
        sys.exit(2)

    try:
        send_mail(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, FROM_ADDR, to_list, subject, body)
        print('Sent')
    except Exception as e:
        print('Send failed:', str(e))
        sys.exit(1)
