#!/usr/bin/env python3
"""Search Gmail for emails about ClawPod/Massive Unblocker."""

import os
import json
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import pickle
from datetime import datetime

# Gmail API scopes
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def authenticate_gmail():
    """Authenticate and return Gmail service."""
    creds = None
    
    # Check for existing token
    token_file = '/home/clawd/.openclaw/skills/gmail/tokens/token.pickle'
    if os.path.exists(token_file):
        with open(token_file, 'rb') as token:
            creds = pickle.load(token)
    
    # If no valid credentials, try JSON token file
    if not creds or not creds.valid:
        json_token = '/home/clawd/.openclaw/skills/gmail/tokens/cos.json'
        if os.path.exists(json_token):
            creds = Credentials.from_authorized_user_file(json_token, SCOPES)
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            print("No valid Gmail credentials found")
            return None
    
    return build('gmail', 'v1', credentials=creds)

def search_emails(service, query, max_results=20):
    """Search Gmail with query and return results."""
    try:
        results = service.users().messages().list(
            userId='me', 
            q=query, 
            maxResults=max_results
        ).execute()
        
        messages = results.get('messages', [])
        
        email_details = []
        for msg in messages:
            msg_detail = service.users().messages().get(
                userId='me', 
                id=msg['id'],
                format='full'
            ).execute()
            
            headers = msg_detail['payload'].get('headers', [])
            subject = next((h['value'] for h in headers if h['name'] == 'Subject'), 'No Subject')
            sender = next((h['value'] for h in headers if h['name'] == 'From'), 'Unknown Sender')
            date = next((h['value'] for h in headers if h['name'] == 'Date'), 'Unknown Date')
            
            # Get snippet
            snippet = msg_detail.get('snippet', '')
            
            email_details.append({
                'id': msg['id'],
                'subject': subject,
                'from': sender,
                'date': date,
                'snippet': snippet
            })
        
        return email_details
    
    except HttpError as error:
        print(f'Gmail API error: {error}')
        return []

def main():
    print("🔍 Searching Gmail for ClawPod/Massive emails...")
    
    service = authenticate_gmail()
    if not service:
        print("❌ Could not authenticate with Gmail")
        return
    
    # Search terms related to ClawPod/Massive
    search_terms = [
        'clawpod',
        'massive unblocker', 
        'joinmassive',
        'unblocker api',
        'massive.com',
        'clawpod.joinmassive.com'
    ]
    
    all_results = []
    
    for term in search_terms:
        print(f"\n🔎 Searching for: '{term}'")
        emails = search_emails(service, term)
        
        if emails:
            print(f"✅ Found {len(emails)} emails")
            all_results.extend(emails)
        else:
            print(f"❌ No emails found for '{term}'")
    
    # Remove duplicates by ID
    unique_emails = {email['id']: email for email in all_results}.values()
    
    print(f"\n📧 Total unique emails found: {len(unique_emails)}")
    
    if unique_emails:
        print("\n" + "="*80)
        print("FOUND EMAILS:")
        print("="*80)
        
        for email in sorted(unique_emails, key=lambda x: x['date'], reverse=True):
            print(f"\n📨 FROM: {email['from']}")
            print(f"📋 SUBJECT: {email['subject']}")
            print(f"📅 DATE: {email['date']}")
            print(f"💬 SNIPPET: {email['snippet'][:200]}...")
            print("-" * 80)
    else:
        print("\n❌ No emails found about ClawPod/Massive Unblocker")
    
    return list(unique_emails)

if __name__ == "__main__":
    results = main()