#!/usr/bin/env python3
"""
Enhanced Ella Slack Automation with Google Contacts Integration
Processes new users from #ae-sales-closed-deals and manages contacts
"""

import re
import subprocess
import json
from datetime import datetime, timedelta
import os

def search_existing_contact(email, company=None):
    """Search for existing contact by email or company"""
    try:
        # Search by email first
        result = subprocess.run([
            '/home/linuxbrew/.linuxbrew/bin/gog', 'contacts', 'list',
            '--account', 'keith@atomicelevator.com',
            '--query', email,
            '--json'
        ], capture_output=True, text=True, input='\n')
        
        if result.returncode == 0:
            contacts = json.loads(result.stdout)
            if contacts.get('connections'):
                return contacts['connections'][0]  # Return first match
        
        # Search by company if no email match
        if company:
            result = subprocess.run([
                '/home/linuxbrew/.linuxbrew/bin/gog', 'contacts', 'list', 
                '--account', 'keith@atomicelevator.com',
                '--query', company,
                '--json'
            ], capture_output=True, text=True, input='\n')
            
            if result.returncode == 0:
                contacts = json.loads(result.stdout)
                if contacts.get('connections'):
                    return contacts['connections'][0]
        
        return None
        
    except Exception as e:
        print(f"Error searching contacts: {e}")
        return None

def lookup_contact_info(email):
    """Get additional context about a contact from Google Contacts"""
    contact = search_existing_contact(email)
    
    if contact:
        contact_info = {
            'existing_contact': True,
            'resource_name': contact.get('resourceName', ''),
            'display_name': contact.get('names', [{}])[0].get('displayName', ''),
            'company': '',
            'phone': '',
            'notes': []
        }
        
        # Extract company
        if contact.get('organizations'):
            contact_info['company'] = contact['organizations'][0].get('name', '')
            
        # Extract phone
        if contact.get('phoneNumbers'):
            contact_info['phone'] = contact['phoneNumbers'][0].get('value', '')
            
        # Extract notes/biography  
        if contact.get('biographies'):
            contact_info['notes'] = [bio.get('value', '') for bio in contact['biographies']]
            
        return contact_info
    
    return {'existing_contact': False}

def create_enhanced_welcome_email(user_info, contact_info, message_context):
    """Create welcome email with additional context from contacts"""
    
    name = user_info.get('name', 'there')
    email = user_info.get('email', '')
    company = user_info.get('company', contact_info.get('company', 'your company'))
    
    # Check if this is a returning/existing contact
    is_existing = contact_info.get('existing_contact', False)
    
    if is_existing:
        # Personalized message for existing contacts
        greeting = f"Great to connect with {company} again!"
        context_note = f"I see we've worked together before. "
    else:
        # Standard new contact greeting
        greeting = f"Welcome to Ellavator AI!"
        context_note = f"We're thrilled to have {company} join our community. "
    
    # Build email subject
    subject = f"{greeting} Your Marketing Intelligence Journey with Ella"
    
    # Enhanced email body with contact context
    body = f"""Hi {name},

{greeting} {context_note}We're excited to help you escape the age of average.

🚀 **Get Started Fast:**
- Log into your Ella dashboard: https://app.ellavator.ai
- Complete your Brand Voice setup (takes 5 minutes)  
- Try your first playbook from your edition

📚 **Helpful Resources:**
- Support team: support@ellavator.com
- Keith's calendar (if you need strategy time): https://app.reclaim.ai/m/atomicelevator-keith

🎯 **Your Success Matters:**
Our mission is simple: help you escape the age of average. Your success is our success.

Questions? Just reply to this email - we're here to help.

Never average, always unmistakable,

Keith Lauver  
Founder, Ellavator AI

P.S. Keep an eye out for a check-in from our team in a couple days to see how you're doing!

---
Deal context: {message_context}
{f'Contact history: {contact_info}' if is_existing else ''}"""

    return subject, body

def process_enhanced_slack_message(message_text, channel_name):
    """Enhanced processing with contacts integration"""
    
    if channel_name != 'ae-sales-closed-deals':
        return
        
    # Look for new user indicators
    trigger_phrases = [
        'new customer', 'new client', 'signed up', 'deal closed',
        'welcome', 'onboard', 'new user', 'just signed'
    ]
    
    if not any(phrase in message_text.lower() for phrase in trigger_phrases):
        return
    
    print(f"Processing new user with contacts lookup: {message_text[:100]}...")
    
    # Extract user information (same as before)
    from ella_slack_automation import extract_user_info
    user_info = extract_user_info(message_text)
    
    if not user_info.get('email'):
        print("No email found - skipping automation")
        return
    
    # NEW: Lookup contact information
    print(f"Looking up contact info for {user_info['email']}...")
    contact_info = lookup_contact_info(user_info['email'])
    
    # Create enhanced welcome email with contact context
    subject, body = create_enhanced_welcome_email(user_info, contact_info, message_text)
    
    # Create Gmail draft
    try:
        result = subprocess.run([
            '/home/ubuntu/.openclaw/workspace/create-gmail-draft.sh',
            user_info['email'],
            subject,
            body
        ], capture_output=True, text=True)
        
        draft_created = result.returncode == 0
        if draft_created:
            context = "existing contact" if contact_info.get('existing_contact') else "new contact"
            print(f"Enhanced Gmail draft created for {user_info['name']} ({context})")
        
    except Exception as e:
        print(f"Error creating enhanced draft: {e}")
        draft_created = False
    
    # Schedule Tom follow-up (same as before)
    from ella_slack_automation import schedule_tom_followup
    followup_scheduled = schedule_tom_followup(user_info, message_text)
    
    # Enhanced logging with contact context
    log_entry = {
        'timestamp': datetime.now().isoformat(),
        'user_info': user_info,
        'contact_info': contact_info,
        'message_context': message_text,
        'draft_created': draft_created,
        'followup_scheduled': followup_scheduled,
        'existing_contact': contact_info.get('existing_contact', False)
    }
    
    with open('/home/ubuntu/.openclaw/workspace/ella-enhanced-automation-log.json', 'a') as f:
        f.write(json.dumps(log_entry) + '\n')
    
    print(f"Enhanced automation completed for {user_info.get('name', 'user')}")

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 2:
        message_text = sys.argv[1]
        channel_name = sys.argv[2]
        process_enhanced_slack_message(message_text, channel_name)
    else:
        print("Usage: python3 ella-contacts-automation.py <message> <channel>")