#!/usr/bin/env python3
"""
send_email_gws.py - Send an email via gws CLI (moon.clawdbot@gmail.com → recipient)
Usage: python3 send_email_gws.py <to> <subject> <body_file_or_stdin>
"""

import sys
import base64
import json
import subprocess
from email.mime.text import MIMEText
from datetime import datetime

def send(to: str, subject: str, body: str):
    msg = MIMEText(body, "plain", "utf-8")
    msg["To"]      = to
    msg["From"]    = "moon.clawdbot@gmail.com"
    msg["Subject"] = subject
    msg["Date"]    = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")

    raw    = base64.urlsafe_b64encode(msg.as_bytes()).decode("utf-8")
    body   = json.dumps({"raw": raw})
    params = json.dumps({"userId": "me"})

    result = subprocess.run(
        ["gws", "gmail", "users", "messages", "send", "--params", params, "--json", body],
        capture_output=True, text=True
    )
    if result.returncode != 0:
        print(f"ERROR: {result.stderr}", file=sys.stderr)
        sys.exit(1)
    print(f"Email sent to {to}")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: send_email_gws.py <to> <subject>  (body from stdin)")
        sys.exit(1)
    to      = sys.argv[1]
    subject = sys.argv[2]
    body    = sys.stdin.read() if not sys.stdin.isatty() else ""
    send(to, subject, body)
