#!/usr/bin/env python3
"""
Proactive Task Intelligence Demo - Shows how 2-day ahead scanning works
"""

import json
from datetime import datetime, timedelta

def analyze_task_complexity(task_title, task_description="", source=""):
    """Analyze if a task needs significant prep time (>1 hour)"""
    
    # High-prep keywords
    high_prep_indicators = [
        "demo", "presentation", "pitch", "board", "investor", 
        "research", "analysis", "proposal", "strategy", "review",
        "prepare", "setup", "configure", "build", "create",
        "read", "study", "learn", "training", "onboard"
    ]
    
    # Check if task likely needs prep
    text_to_check = f"{task_title} {task_description}".lower()
    prep_score = sum(1 for keyword in high_prep_indicators if keyword in text_to_check)
    
    # Estimate prep time based on task type
    if "demo" in text_to_check or "presentation" in text_to_check:
        return {"needs_prep": True, "estimated_hours": 2, "type": "demo_prep"}
    elif "research" in text_to_check or "analysis" in text_to_check:
        return {"needs_prep": True, "estimated_hours": 3, "type": "research"}
    elif "read" in text_to_check or "book" in text_to_check:
        return {"needs_prep": True, "estimated_hours": 4, "type": "reading"}
    elif "board" in text_to_check or "investor" in text_to_check:
        return {"needs_prep": True, "estimated_hours": 5, "type": "board_prep"}
    elif prep_score >= 2:
        return {"needs_prep": True, "estimated_hours": 1.5, "type": "general_prep"}
    
    return {"needs_prep": False, "estimated_hours": 0.5, "type": "quick_task"}

def generate_prep_offers(task_type, task_details):
    """Generate specific prep work offers based on task type"""
    
    offers = {
        "demo_prep": [
            "Research prospect's website and convert key info into Ella brand environment",
            "Identify 3-5 specific use cases they'd likely need (based on their business)",
            "Prepare customized demo script with their company examples",
            "Set up test workspace with their industry terminology",
            "Create follow-up email templates tailored to their pain points"
        ],
        
        "reading": [
            "Read the full book/document and create comprehensive summary",
            "Extract key actionable insights relevant to Ella/business strategy", 
            "Create mind map of main concepts for quick review",
            "Identify quotable passages for presentations/content",
            "Build implementation checklist from recommendations"
        ],
        
        "research": [
            "Conduct competitive analysis and market positioning research",
            "Analyze company website, recent news, and social presence",
            "Identify decision makers and organizational structure",
            "Research their current marketing stack and pain points",
            "Create comprehensive company profile and opportunity assessment"
        ],
        
        "board_prep": [
            "Gather latest metrics and prepare executive dashboard",
            "Research industry trends and competitive updates",
            "Compile customer feedback and success stories",
            "Prepare answers to likely board questions",
            "Create supporting documents and backup data"
        ],
        
        "general_prep": [
            "Research background context and related materials",
            "Prepare supporting documents and resources",
            "Create agenda or outline for structured approach",
            "Identify potential challenges and solutions",
            "Set up necessary tools or environments"
        ]
    }
    
    return offers.get(task_type, ["General research and preparation support"])

def create_email_draft(task_name, due_date, prep_analysis, task_source):
    """Create Gmail draft for Keith's review"""
    
    prep_offers = generate_prep_offers(prep_analysis['type'], task_name)
    suggested_time = datetime.now() + timedelta(days=1)  # Tomorrow
    
    email_content = f"""Subject: 🚨 2-Day Alert: {task_name} needs prep time

Hey Keith,

I found something coming up in 2 days that might need significant prep time:

📊 **TASK:** {task_name}
🗓️ **DUE:** {due_date}
⏱️ **ESTIMATED PREP:** {prep_analysis['estimated_hours']} hours  
💼 **SOURCE:** {task_source}

💡 **PREP WORK I CAN DO:**
{chr(10).join(f"• {offer}" for offer in prep_offers[:3])}

🗓️ **CALENDAR BLOCKING:**
Want me to block {prep_analysis['estimated_hours']} hours on {suggested_time.strftime('%A %B %d')} for this prep work?

Reply with:
• **YES** - Block the time + do the prep work
• **PARTIAL** - Just block time, I'll handle prep  
• **NO** - I'll manage it myself

Averaine ⚔️

P.S. I can start the research immediately if you give the go-ahead."""

    return email_content

# Example upcoming tasks (what the system would find)
example_tasks = [
    {
        "name": "Demo for Enterprise Beauty Brand",
        "due": "Feb 17, 2:00 PM", 
        "source": "Calendar Meeting",
        "description": "55-minute demo for RŌZ Hair Care SVP Marketing"
    },
    {
        "name": "Read 'Metronomics' chapters 4-7", 
        "due": "Feb 19, EOD",
        "source": "Asana Task",
        "description": "CEO Vision & Alignment Playbook prep"
    },
    {
        "name": "Board presentation Q1 metrics",
        "due": "Feb 20, 9:00 AM", 
        "source": "HubSpot Task",
        "description": "Prepare quarterly review for investor update"
    }
]

def demo_proactive_system():
    """Demonstrate how the proactive system would work"""
    
    print("🧠 PROACTIVE TASK INTELLIGENCE DEMO")
    print("=" * 60)
    print("Scanning tasks 2 days ahead for prep requirements...\n")
    
    high_prep_tasks = []
    
    for task in example_tasks:
        analysis = analyze_task_complexity(task['name'], task['description'])
        
        print(f"📋 TASK: {task['name']}")
        print(f"   Due: {task['due']}")
        print(f"   Prep needed: {analysis['needs_prep']}")
        print(f"   Estimated time: {analysis['estimated_hours']} hours")
        print(f"   Type: {analysis['type']}")
        
        if analysis['needs_prep']:
            high_prep_tasks.append({**task, 'analysis': analysis})
            print("   ⚠️  HIGH-PREP TASK - Will email Keith")
        else:
            print("   ✅ Quick task - No email needed")
        
        print()
    
    print("=" * 60)
    print("📧 EMAIL DRAFTS THAT WOULD BE CREATED:")
    print("=" * 60)
    
    for task in high_prep_tasks:
        email = create_email_draft(
            task['name'], 
            task['due'], 
            task['analysis'], 
            task['source']
        )
        print(email)
        print("\n" + "="*60 + "\n")

if __name__ == "__main__":
    demo_proactive_system()