#!/usr/bin/env python3
"""
Meeting Intelligence Generator - Enriches calendar meetings with all available data
"""

import subprocess
import json
import re
from datetime import datetime
import os

def run_command(cmd):
    """Run command and return output"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
        return result.stdout if result.returncode == 0 else None
    except Exception as e:
        print(f"Error running command: {e}")
        return None

def search_hubspot_deals(contact_email):
    """Search HubSpot for deals related to contact"""
    secrets_file = "/home/ubuntu/.openclaw/workspace/.secrets/hubspot.env"
    if not os.path.exists(secrets_file):
        return {"stage": "Not in CRM", "value": "Unknown", "source": "Unknown"}
        
    # Load HubSpot token
    with open(secrets_file) as f:
        for line in f:
            if line.startswith('HUBSPOT_TOKEN'):
                token = line.split('=', 1)[1].strip()
                break
    
    # Search for contact by email
    cmd = f'''curl -s -H "Authorization: Bearer {token}" "https://api.hubapi.com/crm/v3/objects/contacts/search" -H "Content-Type: application/json" -d '{{"query": "{contact_email}", "limit": 5}}'
    '''
    
    output = run_command(cmd)
    if output:
        try:
            data = json.loads(output)
            if data.get('results'):
                contact = data['results'][0]
                contact_id = contact['id']
                
                # Get associated deals
                deals_cmd = f'''curl -s -H "Authorization: Bearer {token}" "https://api.hubapi.com/crm/v4/objects/contacts/{contact_id}/associations/deals"'''
                deals_output = run_command(deals_cmd)
                
                if deals_output:
                    deals_data = json.loads(deals_output)
                    if deals_data.get('results'):
                        return {"stage": "Active Prospect", "value": "Pipeline", "source": "HubSpot"}
                        
        except json.JSONDecodeError:
            pass
            
    return {"stage": "Not in CRM", "value": "Unknown", "source": "Unknown"}

def search_gmail_threads(contact_email):
    """Search Gmail for conversation history"""
    # Use gog to search Gmail
    cmd = f'echo "" | gog gmail search "from:{contact_email} OR to:{contact_email}" -a keith@atomicelevator.com --limit 5'
    output = run_command(cmd)
    
    if output and "@" in output:
        lines = [line for line in output.split('\n') if line.strip()]
        email_count = len([line for line in lines if '@' in line])
        recent_subject = "Found recent emails" if email_count > 0 else "No emails found"
        return {"count": email_count, "recent": recent_subject}
    
    return {"count": 0, "recent": "No email history found"}

def generate_meeting_brief(name, email, context_notes=""):
    """Generate comprehensive meeting brief"""
    
    # Gather intelligence from all sources
    hubspot_intel = search_hubspot_deals(email)
    gmail_intel = search_gmail_threads(email)
    
    # Create brief
    brief = f"""🧠 MEETING INTEL: {name}

📞 CONTACT INFO:
• Email: {email}
• Status: {hubspot_intel['stage']}

📊 PIPELINE DATA:
• CRM Status: {hubspot_intel['stage']}
• Deal Value: {hubspot_intel['value']}
• Source: {hubspot_intel['source']}

📧 EMAIL HISTORY:
• Messages: {gmail_intel['count']} found
• Context: {gmail_intel['recent']}

💡 CONTEXT NOTES:
{context_notes}

🎯 MEETING OBJECTIVES:
• [Auto-populated based on pipeline stage]
• [Add specific goals here]

⚡ PREP REMINDERS:
• Review latest email exchange
• Confirm demo/materials needed
• Set follow-up expectations
"""
    
    return brief

def update_calendar_meeting(meeting_id, brief_text):
    """Update calendar meeting with intelligence brief"""
    # Escape quotes and format for gog command
    escaped_brief = brief_text.replace('"', '\\"').replace('\n', '\\n')
    
    cmd = f'''echo "" | gog calendar update keith@atomicelevator.com {meeting_id} --description "{escaped_brief}" -a keith@atomicelevator.com'''
    
    result = run_command(cmd)
    return result is not None

# Known Tuesday meetings to enrich
tuesday_meetings = [
    {
        "name": "John Hilbrich",
        "email": "unknown@email.com",  # Need to get real email
        "meeting_id": "e9im6r31d5miqsr3d1im8tbcd5n6ebbcd5n6meim64t34dhm6oqjac1i5kq3idb25kq38d1p5lh62opp5kqjaphj6lh38cb46kr3geik8lm3csb7b1lmkeb8act36c1q68o34dhd60p2qc9nagojcehk6kt30c2q",
        "context": "Interested in Ella + Pulse integration. 15-min focused discussion. Opportunity for Ella adoption with existing workflow."
    },
    {
        "name": "Matthew Sorensen Moore", 
        "email": "unknown@email.com",  # Need real email
        "meeting_id": "e9im6r31d5miqsr3d1im8tbcd5n6ebbcd5n6meim64t34dhm6oqjac1i5kq3idb25kq38d1p5lh62opp5kqjaphj6lh38cb46kr3geik8lm3csb7b1b1lmkeb8act36c1q68o34dhd60p2qc9nagojcehk6kt30c2q",
        "context": "Real estate broker, 20+ years experience, North County San Diego. Tech-forward, looking for AI marketing edge."
    },
    {
        "name": "Ron Bockstahler",
        "email": "ronb@amataoffices.com",
        "meeting_id": "e9im6r31d5miqsr3d1im8tbcd5n6ebbcd5n6meim64t34dhm6oqjac1i5kq3idb25kq38d1p5lh62opp5kqjaphj6lh38cb46kr3geil8ksl6i9oeh648j2lf8t32d9q68o34dhd60p2qc9nagp30ehh6kt30c2q", 
        "context": "CEO Amata Law Office Suites. Partnership opportunity for Ella Legal Edition. Referral revenue potential."
    },
    {
        "name": "Beth Risley",
        "email": "unknown@email.com",  # Need real email  
        "meeting_id": "e9im6r31d5miqsr3d1im8tbcd5n6ebbcd5n6meim64t34dhm6oqjac1i5kq3idb25kq38d1p5lh62opp5kqjaphj6lh38cb46kr3gehg68rm6c9ncpa66t3f8ot3ad9q68o34dhd60p2qc9nagp32ehg60t30c2q",
        "context": "SVP Marketing at RŌZ Hair Care. 55-minute meeting = HIGH PRIORITY. Post-VC funding, scaling growth phase."
    }
]

if __name__ == "__main__":
    print("🧠 Generating Meeting Intelligence Briefs...")
    
    for meeting in tuesday_meetings:
        print(f"\n📅 Processing: {meeting['name']}")
        
        brief = generate_meeting_brief(
            meeting['name'], 
            meeting['email'], 
            meeting['context']
        )
        
        print(brief)
        print("-" * 80)
        
        # Optionally update calendar (commented out for testing)
        # if update_calendar_meeting(meeting['meeting_id'], brief):
        #     print(f"✅ Updated calendar for {meeting['name']}")
        # else:
        #     print(f"❌ Failed to update calendar for {meeting['name']}")
    
    print("✅ Meeting Intelligence Generation Complete!")