#!/usr/bin/env python3
"""
Enhanced Monitoring System for ASPEKT
Checks email, calendar, services, client health - only alerts when action needed
Based on 50+ day OpenClaw user patterns from velvet-shark gist
"""

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

def check_urgent_emails():
    """Check for urgent/time-sensitive emails from last 30 minutes"""
    try:
        # Use gog gmail to check recent urgent emails
        result = subprocess.run([
            'gog', 'gmail', 'search', 
            'is:unread newer_than:30m', 
            '-a', 'nikita@aspektagency.com',
            '--format', 'json'
        ], capture_output=True, text=True, timeout=30)
        
        if result.returncode == 0:
            emails = json.loads(result.stdout) if result.stdout else []
            
            urgent_keywords = [
                'payment failure', 'payment failed', 'card declined',
                'security alert', 'suspicious activity', 'account locked',
                'expires today', 'expiring soon', 'deadline',
                'meeting change', 'meeting moved', 'canceled meeting',
                'urgent', 'asap', 'immediate attention'
            ]
            
            urgent_emails = []
            for email in emails[:10]:  # Check last 10 emails
                subject = email.get('subject', '').lower()
                sender = email.get('sender', '')
                
                if any(keyword in subject for keyword in urgent_keywords):
                    urgent_emails.append({
                        'subject': email.get('subject'),
                        'sender': sender,
                        'snippet': email.get('snippet', '')[:100]
                    })
            
            return urgent_emails
        
        return []
    except Exception as e:
        return [{'error': f'Email check failed: {str(e)}'}]

def check_calendar_alerts():
    """Check for meetings in next 2 hours that need prep"""
    try:
        # Use gog calendar to check upcoming events
        result = subprocess.run([
            'gog', 'calendar', 'list', 
            '--hours', '2',
            '--format', 'json'
        ], capture_output=True, text=True, timeout=20)
        
        if result.returncode == 0:
            events = json.loads(result.stdout) if result.stdout else []
            
            prep_needed = []
            for event in events:
                # Check if event has video call links (needs prep)
                description = event.get('description', '').lower()
                summary = event.get('summary', '')
                
                if any(keyword in description for keyword in ['zoom', 'meet', 'teams', 'call']):
                    prep_needed.append({
                        'title': summary,
                        'time': event.get('start', {}).get('dateTime'),
                        'has_video': True
                    })
            
            return prep_needed
        
        return []
    except Exception as e:
        return [{'error': f'Calendar check failed: {str(e)}'}]

def check_service_health():
    """Check ASPEKT server and gateway health"""
    issues = []
    
    try:
        # Check main dashboard server
        response = requests.get('http://localhost:8899/', timeout=5)
        if response.status_code != 200:
            issues.append('ASPEKT dashboard server not responding')
    except:
        issues.append('ASPEKT dashboard server unreachable')
    
    try:
        # Check gateway health
        response = requests.get('http://localhost:18789/api/status', timeout=5)
        if response.status_code != 200:
            issues.append('OpenClaw gateway not responding')
    except:
        issues.append('OpenClaw gateway unreachable')
    
    try:
        # Check rescue bot if it should be running
        response = requests.get('http://localhost:19789/api/status', timeout=3)
        # Don't alert if rescue bot isn't running - it's backup only
    except:
        pass
    
    return issues

def check_client_health_summary():
    """Quick check of client health status"""
    try:
        # Read the latest health check report
        report_path = '/Users/neoclaw/.openclaw/workspace/tools/client-health-check/latest-report.md'
        if os.path.exists(report_path):
            with open(report_path, 'r') as f:
                content = f.read()
            
            # Look for alert keywords
            if 'ALERT' in content or 'WARNING' in content or 'CRITICAL' in content:
                return ['Client health check flagged issues - check #klaviyo-reports']
        
        return []
    except Exception as e:
        return [f'Client health check error: {str(e)}']

def main():
    """Main monitoring function - only alerts when action needed"""
    timestamp = datetime.now().strftime('%H:%M CST')
    alerts = []
    
    print(f"🔍 Enhanced Monitoring Scan - {timestamp}")
    
    # Check all systems
    urgent_emails = check_urgent_emails()
    calendar_alerts = check_calendar_alerts()
    service_issues = check_service_health()
    client_issues = check_client_health_summary()
    
    # Process urgent emails
    if urgent_emails and not any('error' in email for email in urgent_emails):
        for email in urgent_emails:
            if 'error' not in email:
                alerts.append(f"📧 URGENT EMAIL: {email['subject']} from {email['sender']}")
    elif any('error' in email for email in urgent_emails):
        alerts.append("⚠️ Email check failed - manual review needed")
    
    # Process calendar alerts
    if calendar_alerts and not any('error' in event for event in calendar_alerts):
        for event in calendar_alerts:
            if 'error' not in event and event.get('has_video'):
                time_str = event.get('time', 'soon')
                alerts.append(f"📅 MEETING PREP: {event['title']} at {time_str}")
    elif any('error' in event for event in calendar_alerts):
        alerts.append("⚠️ Calendar check failed - manual review needed")
    
    # Process service issues
    for issue in service_issues:
        alerts.append(f"🚨 SERVICE: {issue}")
    
    # Process client issues
    for issue in client_issues:
        alerts.append(f"👥 CLIENT: {issue}")
    
    # Output results
    if alerts:
        print(f"\n🚨 {len(alerts)} ALERTS REQUIRING ATTENTION:")
        for alert in alerts:
            print(f"  {alert}")
        
        # Update dashboard log
        alert_summary = f"Enhanced monitoring: {len(alerts)} alerts requiring attention"
        subprocess.run([
            'python3', '/Users/neoclaw/.openclaw/workspace/tools/update-dashboard-log.py',
            'alert', alert_summary
        ])
        
        return alerts
    else:
        print("✅ All systems normal - no alerts")
        return []

if __name__ == '__main__':
    main()