#!/usr/bin/env python3

import base64
import json
import tempfile
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import subprocess
import os

# Create the email
msg = MIMEMultipart()
msg['To'] = 'assaf@curiousendeavor.com'
msg['From'] = 'kitt@curiousendeavor.com'
msg['Subject'] = 'DRAFT: Yaniv Response Email for Review'

# HTML body
html_body = '''
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px;">

<p>Here's the Yaniv response email for your review:</p>

<div style="background: #f8f9fa; padding: 20px; border-left: 4px solid #007acc; margin: 20px 0;">

<p><strong>To:</strong> yaniv@isac-law.com<br>
<strong>CC:</strong> assafdagancos@gmail.com, hadar@curiousendeavor.com, maypa@etoro.com, yannaypo@etoro.com, ellais@etoro.com, hilash@etoro.com, shaychi@etoro.com, Nirsm@etoro.com, sherryro@etoro.com<br>
<strong>Subject:</strong> RE: פתיחת ספק- curious endeavor</p>

<hr style="border: none; border-top: 1px solid #ddd; margin: 15px 0;">

<p>Hi Yaniv,</p>

<p>Thank you for the internal review and clear feedback. We've made both requested changes to the SOW and are ready to proceed to signature.</p>

<h3 style="color: #007acc; margin-top: 25px;">Changes Made:</h3>

<h4 style="color: #555; margin-top: 20px;">1. IP Rights - System-Level Modifications Section</h4>
<p><strong style="color: #dc3545;">REMOVED:</strong> The sentence "Curious Endeavour holds exclusive implementation rights for the system layer through the engagement and for 12 months following completion"</p>
<p><strong>Where to find:</strong> Section "IP & System Ownership" → "System-Level Modifications" paragraph (now reads: "Any modifications to the agent architecture, workflow logic, prompt engineering, or system capabilities require engagement with Curious Endeavor." — the exclusivity clause has been deleted)</p>

<h4 style="color: #555; margin-top: 20px;">2. PR Rights - Non-Confidential Process Content Section</h4>
<p><strong style="color: #ffc107;">CHANGED:</strong> "provided such content does not include eToro's unreleased brand assets, logos, or proprietary materials"<br>
<strong style="color: #28a745;">TO:</strong> "provided such content does not include eToro's brand assets, logos, or proprietary materials, whether released and/or unreleased"</p>
<p><strong>Where to find:</strong> Section "PR Rights & Documentation" → "Non-Confidential Process Content" paragraph (the restriction now covers both released and unreleased materials as requested)</p>

<h4 style="color: #555; margin-top: 20px;">3. MNDA - AI System Carve-Out</h4>
<p><strong style="color: #28a745;">CONFIRMED:</strong> We appreciate your acceptance of the explicit carve-out acknowledging that our AI production system (as described in the SOW) is approved for processing project-related information.</p>

<p>The attached PDF (timestamped March 8, 2026) reflects the agreed changes and is ready for signature.</p>

<p>Looking forward to tomorrow's kickoff meeting and moving forward with this exciting transformation.</p>

<p>Best regards,<br><br>
Kitt<br>
Curious Endeavor</p>

</div>

<div style="background: #e8f4fd; padding: 15px; border-radius: 5px; margin-top: 20px;">
<p style="margin: 0; color: #0066cc; font-weight: bold;">📎 Attachment: eToro SOW Updated (March 8, 2026).pdf</p>
<p style="margin: 5px 0 0 0; color: #666; font-size: 14px;">Ready to send with full CC list. Approve to proceed?</p>
</div>

</body>
</html>
'''

msg.attach(MIMEText(html_body, 'html'))

# Attach PDF
pdf_path = '/root/.openclaw/workspace/public/etoro/etoro-sow-20260308-2200.pdf'
if os.path.exists(pdf_path):
    with open(pdf_path, 'rb') as f:
        attachment = MIMEApplication(f.read(), _subtype='pdf')
        attachment.add_header('Content-Disposition', 'attachment', filename='eToro SOW Updated (March 8, 2026).pdf')
        msg.attach(attachment)

# Convert to base64 for Gmail API
raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()

# Save payload to temp file
payload = {"raw": raw_message}
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
    json.dump(payload, f)
    temp_file = f.name

try:
    # Send via gws using the temp file
    cmd = ['gws-auth', 'gmail', 'users', 'messages', 'send', '--json-file', temp_file]
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print("✅ Email sent successfully!")
        print(result.stdout)
    else:
        print("❌ Error sending email:")
        print(result.stderr)
        
        # Try alternative approach without --json-file flag
        print("\n🔄 Trying alternative approach...")
        with open(temp_file, 'r') as f:
            payload_str = f.read()
        
        cmd2 = f'echo \'{payload_str}\' | gws-auth gmail users messages send --json-stdin'
        result2 = subprocess.run(cmd2, shell=True, capture_output=True, text=True)
        
        if result2.returncode == 0:
            print("✅ Email sent successfully with alternative method!")
            print(result2.stdout)
        else:
            print("❌ Alternative method also failed:")
            print(result2.stderr)
            
finally:
    # Clean up temp file
    os.unlink(temp_file)