#!/usr/bin/env python3
"""
Daily Meeting Intelligence System
Enriches Keith's calendar meetings with HubSpot, Asana, Gmail, and Contact insights
"""

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

class MeetingIntelligenceSystem:
    def __init__(self):
        self.workspace = "/home/ubuntu/.openclaw/workspace"
        self.secrets_dir = f"{self.workspace}/.secrets"
        
    def run_gog_command(self, cmd_parts):
        """Run gog command with PTY and keyring unlock"""
        try:
            # Run in PTY mode with empty keyring passphrase
            process = subprocess.Popen(
                cmd_parts,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            stdout, stderr = process.communicate(input="\n")  # Send empty passphrase
            
            if process.returncode == 0:
                return stdout
            else:
                print(f"Error running {' '.join(cmd_parts)}: {stderr}")
                return None
        except Exception as e:
            print(f"Exception running {' '.join(cmd_parts)}: {e}")
            return None
    
    def get_upcoming_meetings(self, days=5):
        """Get meetings for next N days"""
        meetings = []
        
        # Try to get calendar events
        cmd = ["gog", "calendar", "events", "-n", "50", "-a", "keith@atomicelevator.com"]
        output = self.run_gog_command(cmd)
        
        if output:
            # Parse calendar output
            # This is a simplified parser - would need to be more robust
            for line in output.split('\n'):
                if 'summary' in line and 'Keith Lauver' in line:
                    meetings.append(line)
        
        return meetings
    
    def search_hubspot_contact(self, name, email=None):
        """Search HubSpot for contact information"""
        # Load HubSpot credentials
        hubspot_file = f"{self.secrets_dir}/hubspot.env"
        if not os.path.exists(hubspot_file):
            return None
            
        with open(hubspot_file) as f:
            token = f.read().strip().split('=')[1]
        
        # Search HubSpot API
        # Implementation would go here
        return {
            "stage": "Unknown",
            "deal_value": None,
            "last_contact": None,
            "source": None
        }
    
    def search_gmail_history(self, email):
        """Search Gmail for conversation history"""
        cmd = ["gog", "gmail", "search", f"from:{email}", "-a", "keith@atomicelevator.com"]
        output = self.run_gog_command(cmd)
        
        if output:
            # Parse email results
            email_count = len([line for line in output.split('\n') if '@' in line])
            return {"email_count": email_count, "recent_subject": "Email found"}
        
        return {"email_count": 0, "recent_subject": None}
    
    def search_asana_tasks(self, name):
        """Search Asana for related tasks"""
        # Would integrate with Asana API here
        return {"related_tasks": 0, "recent_task": None}
    
    def search_contacts(self, name):
        """Search Google Contacts"""
        # Would search contacts here
        return {"found": False, "company": None, "notes": None}
    
    def generate_meeting_brief(self, meeting_data):
        """Generate TLDR brief for a meeting"""
        name = meeting_data.get('attendee_name', 'Unknown')
        email = meeting_data.get('attendee_email', '')
        
        # Gather intelligence
        hubspot_data = self.search_hubspot_contact(name, email)
        gmail_data = self.search_gmail_history(email)
        asana_data = self.search_asana_tasks(name)
        contact_data = self.search_contacts(name)
        
        # Generate brief
        brief = f"""MEETING INTEL: {name}

🎯 QUICK FACTS:
• Contact: {email}
• HubSpot Stage: {hubspot_data.get('stage', 'Not in CRM')}
• Email History: {gmail_data.get('email_count', 0)} messages
• Asana Tasks: {asana_data.get('related_tasks', 0)} items

💡 LIKELY DISCUSSION:
• [Auto-detected from context]

🎯 OBJECTIVE:
• [Based on pipeline stage]

📊 PIPELINE STATUS:
• Stage: {hubspot_data.get('stage', 'Unknown')}
• Value: ${hubspot_data.get('deal_value', 'TBD')}

🔗 REFERRAL SOURCE:
• {hubspot_data.get('source', 'Direct/Unknown')}

⏰ PREP REMINDERS:
• Check latest email thread
• Review any Asana follow-ups
• Confirm meeting objectives
"""
        
        return brief
    
    def update_calendar_with_intel(self, meeting_id, brief):
        """Update calendar meeting with intelligence brief"""
        # Would update calendar here
        print(f"Would update meeting {meeting_id} with brief")
        
    def run_daily_intelligence(self):
        """Main function to run daily intelligence gathering"""
        print("🧠 Running Daily Meeting Intelligence System...")
        
        meetings = self.get_upcoming_meetings()
        
        for meeting in meetings:
            # Parse meeting data (simplified)
            meeting_data = {"attendee_name": "Test User", "attendee_email": "test@example.com"}
            
            brief = self.generate_meeting_brief(meeting_data)
            print(brief)
            
        print("✅ Daily Meeting Intelligence Complete")

if __name__ == "__main__":
    system = MeetingIntelligenceSystem()
    system.run_daily_intelligence()