#!/usr/bin/env python3
"""Check Rob's Gmail inbox for actionable emails since last check."""

import json
import os
import sys
import base64
import re
from datetime import datetime, timezone
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

CONFIG_DIR = os.path.dirname(os.path.abspath(__file__))
TOKEN_FILE = os.path.join(CONFIG_DIR, "token.json")
STATE_FILE = os.path.join(CONFIG_DIR, "rob-gmail-state.json")

def get_service():
    creds = Credentials.from_authorized_user_file(TOKEN_FILE)
    if creds.expired and creds.refresh_token:
        creds.refresh(Request())
        with open(TOKEN_FILE, 'w') as f:
            f.write(creds.to_json())
    return build('gmail', 'v1', credentials=creds)

def get_body(msg):
    """Extract plain text body from message."""
    payload = msg.get('payload', {})
    
    def extract_text(part):
        if part.get('mimeType') == 'text/plain':
            data = part.get('body', {}).get('data', '')
            if data:
                return base64.urlsafe_b64decode(data).decode('utf-8', errors='replace')
        if 'parts' in part:
            for p in part['parts']:
                result = extract_text(p)
                if result:
                    return result
        return ''
    
    return extract_text(payload)

def main():
    # Load state
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            state = json.load(f)
    else:
        state = {"seenIds": [], "historyId": None}
    
    seen_ids = set(state.get("seenIds", []))
    
    service = get_service()
    
    # Fetch recent messages - get last 50 to catch anything since last check
    result = service.users().messages().list(
        userId='me',
        maxResults=50,
        labelIds=['INBOX']
    ).execute()
    
    messages = result.get('messages', [])
    
    new_emails = []
    new_ids = []
    
    for msg_ref in messages:
        msg_id = msg_ref['id']
        if msg_id in seen_ids:
            continue
        
        # New message - fetch details
        msg = service.users().messages().get(
            userId='me',
            id=msg_id,
            format='full'
        ).execute()
        
        headers = {h['name'].lower(): h['value'] for h in msg.get('payload', {}).get('headers', [])}
        subject = headers.get('subject', '(no subject)')
        sender = headers.get('from', '')
        date = headers.get('date', '')
        body = get_body(msg)
        
        new_emails.append({
            'id': msg_id,
            'subject': subject,
            'from': sender,
            'date': date,
            'body': body[:2000]  # limit body
        })
        new_ids.append(msg_id)
    
    # Get current historyId
    profile = service.users().getProfile(userId='me').execute()
    new_history_id = profile.get('historyId')
    
    # Update state
    state['seenIds'] = list(seen_ids) + new_ids
    state['historyId'] = new_history_id
    state['lastCheck'] = datetime.now(timezone.utc).isoformat()
    state['lastCheckEpoch'] = int(datetime.now(timezone.utc).timestamp())
    
    with open(STATE_FILE, 'w') as f:
        json.dump(state, f, indent=2)
    
    # Output results
    output = {
        'new_count': len(new_emails),
        'emails': new_emails
    }
    print(json.dumps(output, indent=2))

if __name__ == '__main__':
    main()
