#!/usr/bin/env python3
"""
Send a short themed email via your SMTP relay.

Assumes your IP is allowlisted for relay with no SMTP AUTH.
If AUTH is actually required, set:
  export CPMTA_SMTP_USER="your_user"
  export CPMTA_SMTP_PASS="your_pass"

Optional:
  export CPMTA_SMTP_DEBUG="1"   # enables SMTP protocol debug output

"""

import os
import sys
import ssl
import smtplib
from socket import timeout as SocketTimeout
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate, make_msgid

# === SMTP Relay Settings ===
SMTP_HOST = "us-east-1.cp-mta.com"
SMTP_PORT = 25

# Socket timeout (connect + read/write)
TIMEOUT_SECONDS = 30

# Try STARTTLS if the server advertises it
USE_STARTTLS = True

# Optional AUTH via env vars (only used if both are present)
SMTP_USER = os.getenv("CPMTA_SMTP_USER", "").strip()
SMTP_PASS = os.getenv("CPMTA_SMTP_PASS", "").strip()

# Optional verbose protocol debug
SMTP_DEBUG = os.getenv("CPMTA_SMTP_DEBUG", "").strip() in ("1", "true", "TRUE", "yes", "YES")

# === EDIT SENDER HERE ===
# === Message Settings ===
SENDER_EMAIL = "jen.barber@acmemx.com"
SENDER_NAME = "Jen Barber"

# === EDIT RECIPIENT HERE ===
# Change this to your recipient
RECIPIENT_EMAIL = "maurice.moss@acmemx.com"

# === EDIT SUBJECT AND MESSAGE HERE ===
SUBJECT = "Nostromo loss confirmed. Crew missing. Salvage mission canceled."

# Themed email body to match subject
BODY = "\n".join([
    "Hi team,",
    "",
    "This is a formal update regarding the Nostromo spacecraft.",
    "The vessel is now listed as lost, with the full crew status marked as missing.",
    "",
    "As a result, the planned salvage operation is canceled effective immediately.",
    "All recovery logistics, vendor holds, and transit clearances are to be stood down",
    "until further notice from Special Operations.",
    "",
    "Do not initiate independent search, retrieval, or comms outreach.",
    "Any inbound inquiries should be routed through the authorized incident channel.",
    "",
    "Please confirm cancellation acknowledgement and ensure all related documentation",
    "is archived under restricted access protocols.",
    "",
    "Best,",
    "Jen Barber",
])

def build_message() -> MIMEMultipart:
    msg = MIMEMultipart()
    msg["From"] = f'"{SENDER_NAME}" <{SENDER_EMAIL}>'
    msg["To"] = RECIPIENT_EMAIL
    msg["Subject"] = SUBJECT
    msg["Date"] = formatdate(localtime=True)
    msg["Message-ID"] = make_msgid()
    msg.attach(MIMEText(BODY, "plain", "utf-8"))
    return msg

def send_email() -> None:
    msg = build_message()

    print(f"[INFO] Connecting to {SMTP_HOST}:{SMTP_PORT} (timeout={TIMEOUT_SECONDS}s) ...")

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=TIMEOUT_SECONDS) as server:
        if SMTP_DEBUG:
            server.set_debuglevel(1)

        code, resp = server.ehlo()
        print(f"[INFO] EHLO response: {code}")

        if USE_STARTTLS:
            if server.has_extn("starttls"):
                print("[INFO] STARTTLS advertised by server. Attempting TLS upgrade ...")
                context = ssl.create_default_context()
                server.starttls(context=context)
                code, resp = server.ehlo()
                print(f"[INFO] EHLO after STARTTLS: {code}")
            else:
                print("[WARN] STARTTLS not advertised. Continuing without TLS.")

        if SMTP_USER and SMTP_PASS:
            print(f"[INFO] AUTH credentials found in env. Attempting login as {SMTP_USER!r} ...")
            server.login(SMTP_USER, SMTP_PASS)
            print("[INFO] AUTH success.")
        else:
            print("[INFO] No AUTH credentials provided. Assuming IP-allowlisted relay.")

        print(f"[INFO] Sending email from {SENDER_EMAIL} to {RECIPIENT_EMAIL} ...")
        server.sendmail(SENDER_EMAIL, [RECIPIENT_EMAIL], msg.as_string())

    print("[SUCCESS] Email sent (or accepted by relay).")

def main():
    try:
        send_email()
        return 0

    except smtplib.SMTPConnectError as e:
        print(f"[ERROR] Could not connect to SMTP server: {e}")
    except smtplib.SMTPServerDisconnected as e:
        print(f"[ERROR] Server disconnected unexpectedly: {e}")
    except smtplib.SMTPHeloError as e:
        print(f"[ERROR] HELO/EHLO error: {e}")
    except smtplib.SMTPNotSupportedError as e:
        print(f"[ERROR] SMTP feature not supported by server: {e}")
    except smtplib.SMTPAuthenticationError as e:
        print(f"[ERROR] AUTH failed: {e}")
    except smtplib.SMTPSenderRefused as e:
        print(f"[ERROR] Sender refused: {e}")
    except smtplib.SMTPRecipientsRefused as e:
        print(f"[ERROR] Recipients refused: {e.recipients}")
    except smtplib.SMTPDataError as e:
        print(f"[ERROR] SMTP DATA error: {e}")
    except smtplib.SMTPResponseException as e:
        print(f"[ERROR] SMTP error: {e.smtp_code} {e.smtp_error!r}")
    except (SocketTimeout, TimeoutError):
        print(f"[ERROR] Timed out after {TIMEOUT_SECONDS}s while contacting the relay.")
    except OSError as e:
        print(f"[ERROR] Network/OS error: {e}")
    except Exception as e:
        print(f"[ERROR] Unexpected error: {e}")

    return 1

if __name__ == "__main__":
    sys.exit(main())
