#!/usr/bin/env python3
"""
send-email.py — Send HTML or plain text emails via Proton Bridge SMTP.
Bypasses Apple Mail entirely to avoid the html content bug.

Usage:
  python3 send-email.py --to EMAIL --subject SUBJECT --body "text" [--html] [--body-file FILE]
  python3 send-email.py --setup  (store SMTP password in macOS Keychain)

Password is stored in macOS Keychain under service "ProtonBridge-SMTP".
"""

import argparse
import email.mime.multipart
import email.mime.text
import json
import os
import smtplib
import ssl
import subprocess
import sys
from datetime import datetime

# Config
SMTP_HOST = "127.0.0.1"
SMTP_PORT = 1025
FROM_EMAIL = "TonyOClaw1990@proton.me"
FROM_NAME = "Tony"
KEYCHAIN_SERVICE = "ProtonBridge-SMTP"
KEYCHAIN_ACCOUNT = FROM_EMAIL


def keychain_get_password():
    """Retrieve SMTP password from macOS Keychain."""
    try:
        result = subprocess.run(
            ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE,
             "-a", KEYCHAIN_ACCOUNT, "-w"],
            capture_output=True, text=True, timeout=5
        )
        if result.returncode == 0:
            return result.stdout.strip()
    except Exception:
        pass
    return None


def keychain_set_password(password):
    """Store SMTP password in macOS Keychain."""
    # Delete existing entry if any
    subprocess.run(
        ["security", "delete-generic-password", "-s", KEYCHAIN_SERVICE,
         "-a", KEYCHAIN_ACCOUNT],
        capture_output=True, timeout=5
    )
    # Add new entry
    result = subprocess.run(
        ["security", "add-generic-password", "-s", KEYCHAIN_SERVICE,
         "-a", KEYCHAIN_ACCOUNT, "-w", password,
         "-T", "", "-U"],
        capture_output=True, text=True, timeout=5
    )
    if result.returncode != 0:
        print(f"Error storing password: {result.stderr}", file=sys.stderr)
        return False
    return True


def send_email(to_addr, subject, body, is_html=False, cc=None):
    """Send an email via Proton Bridge SMTP (SSL on port 1025)."""
    password = keychain_get_password()
    if not password:
        print("ERROR: No SMTP password found in Keychain.", file=sys.stderr)
        print("Run: python3 send-email.py --setup", file=sys.stderr)
        sys.exit(1)

    # Build the message
    if is_html:
        msg = email.mime.multipart.MIMEMultipart("alternative")
        # Plain text fallback (strip HTML tags roughly)
        import re
        plain = re.sub(r'<[^>]+>', '', body)
        plain = re.sub(r'\s+', ' ', plain).strip()
        msg.attach(email.mime.text.MIMEText(plain, "plain", "utf-8"))
        msg.attach(email.mime.text.MIMEText(body, "html", "utf-8"))
    else:
        msg = email.mime.text.MIMEText(body, "plain", "utf-8")

    msg["From"] = f"{FROM_NAME} <{FROM_EMAIL}>"
    msg["To"] = to_addr
    if cc:
        msg["Cc"] = cc
    msg["Subject"] = subject
    msg["Date"] = email.utils.formatdate(localtime=True)
    # Unique Message-ID prevents Gmail/Proton from threading emails as replies
    msg["Message-ID"] = email.utils.make_msgid(domain="proton.me")

    # Connect and send
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE  # Local bridge uses self-signed cert

    try:
        with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, timeout=30, context=ctx) as server:
            server.login(FROM_EMAIL, password)
            recipients = [to_addr]
            if cc:
                recipients.extend([a.strip() for a in cc.split(",")])
            server.sendmail(FROM_EMAIL, recipients, msg.as_string())
        print(f"✅ Email sent to {to_addr}" + (f" (cc: {cc})" if cc else ""))
        return True
    except smtplib.SMTPAuthenticationError as e:
        print(f"❌ Authentication failed: {e}", file=sys.stderr)
        print("Password may be wrong. Run: python3 send-email.py --setup", file=sys.stderr)
        return False
    except Exception as e:
        print(f"❌ Send failed: {e}", file=sys.stderr)
        return False


def setup():
    """Interactive setup: store SMTP password in Keychain."""
    print("=" * 50)
    print("Proton Bridge SMTP Password Setup")
    print("=" * 50)
    print()
    print("To find your bridge password:")
    print("1. Open Proton Mail Bridge app")
    print("2. Click on your account (TonyOClaw1990@proton.me)")
    print("3. Copy the 'Password' shown under SMTP settings")
    print()
    password = input("Paste the bridge SMTP password: ").strip()
    if not password:
        print("No password entered. Aborting.")
        sys.exit(1)

    if keychain_set_password(password):
        print("✅ Password stored in macOS Keychain.")
        print()
        # Test connection
        print("Testing connection...")
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, timeout=10, context=ctx) as server:
                server.login(FROM_EMAIL, password)
            print("✅ SMTP connection and auth successful!")
        except Exception as e:
            print(f"⚠️  Connection test failed: {e}")
            print("Check that Proton Bridge is running and the password is correct.")
    else:
        print("❌ Failed to store password.")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="Send email via Proton Bridge SMTP")
    parser.add_argument("--setup", action="store_true", help="Store SMTP password in Keychain")
    parser.add_argument("--to", help="Recipient email address")
    parser.add_argument("--cc", help="CC email address(es), comma-separated")
    parser.add_argument("--subject", help="Email subject")
    parser.add_argument("--body", help="Email body text")
    parser.add_argument("--body-file", help="Read body from file")
    parser.add_argument("--html", action="store_true", help="Send as HTML email")
    parser.add_argument("--test", action="store_true", help="Send a test HTML email to yourself")

    args = parser.parse_args()

    if args.setup:
        setup()
        return

    if args.test:
        html_body = """
        <html>
        <body style="font-family: -apple-system, Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #6d28d9;">🐾 HTML Email Test</h1>
            <p>If you're reading this with proper formatting, <strong>HTML email via Proton Bridge is working!</strong></p>
            <ul>
                <li>✅ Direct SMTP connection (bypasses Apple Mail)</li>
                <li>✅ HTML content preserved</li>
                <li>✅ Styled formatting works</li>
            </ul>
            <hr style="border: 1px solid #e5e7eb;">
            <p style="color: #6b7280; font-size: 12px;">Sent by Tony via send-email.py at {time}</p>
        </body>
        </html>
        """.format(time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        send_email(FROM_EMAIL, "HTML Email Test — Proton Bridge Direct SMTP", html_body, is_html=True)
        return

    if not args.to or not args.subject:
        parser.error("--to and --subject are required (or use --setup / --test)")

    body = args.body or ""
    if args.body_file:
        with open(args.body_file, "r") as f:
            body = f.read()

    if not body:
        parser.error("Provide --body or --body-file")

    send_email(args.to, args.subject, body, is_html=args.html, cc=args.cc)


if __name__ == "__main__":
    import email.utils
    main()

# TONY-APPROVED: 2026-03-01 | sha:b7744c07
