#!/usr/bin/env python3
"""
Ella Slack Automation for Welcome Email Drafts
Triggered when new users/deals are mentioned in #ae-sales-closed-deals
"""

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

def extract_user_info(message_text):
    """Extract user information from Slack message"""
    info = {}
    
    # Look for email addresses
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    emails = re.findall(email_pattern, message_text)
    if emails:
        info['email'] = emails[0]
    
    # Look for company names (common patterns)
    company_patterns = [
        r'(?:from |at |with |@)([A-Z][A-Za-z\s&\.]{2,30}(?:Inc|LLC|Corp|Ltd|Co)?)',
        r'([A-Z][A-Za-z\s&\.]{2,30}(?:Inc|LLC|Corp|Ltd|Co))',
    ]
    for pattern in company_patterns:
        matches = re.findall(pattern, message_text)
        if matches:
            info['company'] = matches[0].strip()
            break
    
    # Look for names (capitalized words near certain keywords)
    name_patterns = [
        r'(?:customer|client|user|signed up|new|welcome)\s*:?\s*([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)',
        r'([A-Z][a-z]+\s+[A-Z][a-z]+)(?:\s+from|\s+@|\s+signed)',
    ]
    for pattern in name_patterns:
        matches = re.findall(pattern, message_text)
        if matches:
            info['name'] = matches[0].strip()
            break
    
    # Look for deal values
    value_pattern = r'\$([0-9,]+(?:\.[0-9]{2})?)'
    values = re.findall(value_pattern, message_text)
    if values:
        info['deal_value'] = f"${values[0]}"
    
    return info

def create_welcome_email_draft(user_info, message_context):
    """Create personalized welcome email draft"""
    
    # Extract user details
    name = user_info.get('name', 'there')
    email = user_info.get('email', '')
    company = user_info.get('company', 'your company')
    
    if not email:
        print("No email found - cannot create draft")
        return False
    
    # Personalize the subject
    if company and company != 'your company':
        subject = f"Welcome to Ellavator AI, {company}! Your Marketing Intelligence Journey Starts Now"
    else:
        subject = "Welcome to Ellavator AI - Your Marketing Intelligence Journey Starts Now"
    
    # Create personalized email body
    body = f"""Hi {name},

Welcome to Ellavator AI! We're thrilled to have {company} join the community of forward-thinking marketers who refuse to settle for 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!

---
Context from team: {message_context}"""

    # Create the Gmail draft
    try:
        result = subprocess.run([
            '/home/ubuntu/.openclaw/workspace/create-gmail-draft.sh',
            email,
            subject,
            body
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"Gmail draft created for {name} ({email})")
            return True
        else:
            print(f"Error creating draft: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"Error creating Gmail draft: {e}")
        return False

def schedule_tom_followup(user_info, message_context):
    """Schedule 2-day follow-up ping to Tom Hilbrich"""
    
    name = user_info.get('name', 'New User')
    company = user_info.get('company', '')
    
    # Create follow-up message
    followup_text = f"""Hey @Tom Hilbrich! 👋

Checking on {name}{' from ' + company if company else ''} who signed up 2 days ago for Ella:
- Have they logged in yet?
- Getting that initial "a-ha" moment?
- Need any onboarding assistance?

Let's make sure they're getting value right away!

Deal context: {message_context}"""

    # Calculate 2 days from now
    followup_date = datetime.now() + timedelta(days=2)
    iso_date = followup_date.strftime('%Y-%m-%d')
    
    # Create cron job for the follow-up
    cron_job = {
        "name": f"Tom Follow-up: {name}",
        "schedule": {
            "kind": "at",
            "at": f"{iso_date}T09:00:00-07:00"  # 9 AM MST
        },
        "payload": {
            "kind": "systemEvent",
            "text": f"Send follow-up to Tom Hilbrich: {followup_text}"
        },
        "sessionTarget": "main",
        "enabled": True
    }
    
    # Save cron job request
    with open('/home/ubuntu/.openclaw/workspace/tom-followup.json', 'w') as f:
        json.dump(cron_job, f, indent=2)
    
    print(f"Scheduled follow-up for {name} on {iso_date}")
    return True

def process_slack_message(message_text, channel_name):
    """Main processing function for Slack messages"""
    
    if channel_name != 'ae-sales-closed-deals':
        return
    
    # Look for indicators of new users/deals
    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 potential new user from: {message_text[:100]}...")
    
    # Extract user information
    user_info = extract_user_info(message_text)
    
    if not user_info.get('email'):
        print("No email found - skipping automation")
        return
    
    # Create welcome email draft
    draft_created = create_welcome_email_draft(user_info, message_text)
    
    # Schedule Tom follow-up
    followup_scheduled = schedule_tom_followup(user_info, message_text)
    
    # Log the automation
    log_entry = {
        'timestamp': datetime.now().isoformat(),
        'user_info': user_info,
        'message_context': message_text,
        'draft_created': draft_created,
        'followup_scheduled': followup_scheduled
    }
    
    # Save to automation log
    with open('/home/ubuntu/.openclaw/workspace/ella-automation-log.json', 'a') as f:
        f.write(json.dumps(log_entry) + '\n')
    
    print(f"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_slack_message(message_text, channel_name)
    else:
        print("Usage: python3 ella-slack-automation.py <message> <channel>")