#!/usr/bin/env python3
import os
import json
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/gmail.send']

def get_credentials():
    creds = None
    token_path = os.path.expanduser('~/.openclaw/credentials/gmail-token.json')
    cred_path = os.path.expanduser('~/.openclaw/credentials/gmail-oliveraibot.json')
    
    if os.path.exists(token_path):
        creds = Credentials.from_authorized_user_file(token_path, SCOPES)
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(cred_path, SCOPES)
            creds = flow.run_local_server(port=0)  # Use random available port
        
        with open(token_path, 'w') as token:
            token.write(creds.to_json())
    
    return creds

def send_email_with_attachments(to, subject, body, attachments):
    creds = get_credentials()
    service = build('gmail', 'v1', credentials=creds)
    
    message = MIMEMultipart()
    message['to'] = to
    message['from'] = 'oliveraibot@gmail.com'
    message['subject'] = subject
    
    message.attach(MIMEText(body, 'plain'))
    
    for attachment_path in attachments:
        with open(attachment_path, 'rb') as f:
            part = MIMEApplication(f.read(), Name=os.path.basename(attachment_path))
            part['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment_path)}"'
            message.attach(part)
    
    raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
    result = service.users().messages().send(userId='me', body={'raw': raw}).execute()
    
    return result

if __name__ == '__main__':
    to_email = 'shaycosolutions@gmail.com'
    subject = 'LAUNCHED Reports — Supplier Strategy & Happy Mammoth Case Study'
    body = '''Hi Shay,

Attached are two LAUNCHED branded reports:

1. Supplier Strategy Brief (Sleep Supplement)
2. Happy Mammoth Case Study (Louise's competitive analysis)

Key highlights:
• Bulk Nutrients recommended (100-250 MOQ, 2-4 weeks)
• Net investment: $360-820 after pre-orders
• Happy Mammoth gaps identified for competitive entry

Next steps: Email suppliers Monday using template in brief.

—
Oliver
LAUNCHED Portfolio Holdings'''
    
    attachments = [
        os.path.expanduser('~/.openclaw/workspace-oliver/launched-supplier-brief-rebuilt.pdf'),
        os.path.expanduser('~/.openclaw/workspace/workspace-marketer/case-studies/happy-mammoth-rebuilt.pdf')
    ]
    
    result = send_email_with_attachments(to_email, subject, body, attachments)
    print(f"✅ Email sent successfully! Message ID: {result['id']}")
