#!/usr/bin/env python3
"""
Rob Lobster Email Sender
WHITELIST: Only sends to approved addresses. NEVER to anyone else.
"""

import json
import base64
import sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# === SECURITY: APPROVED RECIPIENTS ONLY ===
WHITELIST = ['jlynch@tlcnj.com']

SEND_TOKEN_FILE = '/Users/joemac/.openclaw/workspace/config/gmail/token-send.json'
READ_TOKEN_FILE = '/Users/joemac/.openclaw/workspace/config/gmail/token.json'

def get_service():
    """Use dedicated send token file so readonly cron doesn't overwrite it."""
    import os
    from google.auth.transport.requests import Request
    
    token_file = SEND_TOKEN_FILE if os.path.exists(SEND_TOKEN_FILE) else READ_TOKEN_FILE
    
    with open(token_file) as f:
        token_data = json.load(f)
    
    SEND_SCOPES = [
        'https://www.googleapis.com/auth/gmail.send',
        'https://www.googleapis.com/auth/gmail.readonly'
    ]
    
    creds = Credentials(
        token=token_data.get('access_token', token_data.get('token')),
        refresh_token=token_data['refresh_token'],
        token_uri=token_data['token_uri'],
        client_id=token_data['client_id'],
        client_secret=token_data['client_secret'],
        scopes=SEND_SCOPES
    )
    
    # Auto-refresh if expired
    if not creds.valid:
        creds.refresh(Request())
        token_data['token'] = creds.token
        token_data['access_token'] = creds.token
        token_data['scopes'] = SEND_SCOPES
        with open(SEND_TOKEN_FILE, 'w') as f:
            json.dump(token_data, f, indent=2)
    
    return build('gmail', 'v1', credentials=creds)

def send_email(to, subject, body, attachment_path=None):
    """Send email. ONLY to whitelisted addresses."""
    if to not in WHITELIST:
        raise ValueError(f"BLOCKED: {to} is not in the approved whitelist: {WHITELIST}")
    
    if attachment_path:
        message = MIMEMultipart()
        message.attach(MIMEText(body))
        
        import os
        filename = os.path.basename(attachment_path)
        with open(attachment_path, 'rb') as f:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(f.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename={filename}')
        message.attach(part)
    else:
        message = MIMEText(body)
    
    message['to'] = to
    message['from'] = 'rob.lobster.claw@gmail.com'
    message['subject'] = subject
    
    service = get_service()
    raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
    result = service.users().messages().send(
        userId='me',
        body={'raw': raw}
    ).execute()
    
    return result

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: send_email.py <subject> <body> [attachment_path]")
        sys.exit(1)
    
    subject = sys.argv[1]
    body = sys.argv[2]
    attachment = sys.argv[3] if len(sys.argv) > 3 else None
    
    result = send_email('jlynch@tlcnj.com', subject, body, attachment)
    print(f"Sent! ID: {result['id']}")
