#!/usr/bin/env python3
"""
Recent Work Startup - Intelligent Session Context
=================================================

This module provides an enhanced startup experience that automatically discovers
and summarizes the most recent things we've been working on together. It leverages
the ML-powered conversation indexing and name detection systems to provide
personalized, context-aware session initialization.

Purpose:
    - Automatically detect and summarize recent collaborative work
    - Use ML-powered conversation analysis for intelligent context
    - Provide personalized greetings with detected user names
    - Show recent accomplishments and project progress
    - Display relevant memory highlights and suggestions
    - Integrate all enhanced MIRA capabilities

Features:
    - 🧠 ML-powered name detection from conversations
    - 🔄 Auto-ingestion of latest conversation data
    - 📊 Recent work analysis and summarization
    - 🎯 Intelligent project phase detection
    - 💭 Context-aware memory highlights
    - 🚀 Enhanced command suggestions

Author: MIRA Memory System
Version: 2.0 (ML-Enhanced Implementation)
"""

import logging
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Tuple
import subprocess
import json
import re
from collections import defaultdict

# Import MIRA components
from config import MEMORY_DIR
from intelligence.name_detection import detect_user_name, trigger_conversation_ingestion
from conversations.comprehensive_indexer import ComprehensiveIndexer
from interfaces.interface import MemoryInterface
from utils.claude_path_discovery import get_claude_conversations_path

logger = logging.getLogger(__name__)

class RecentWorkStartup:
    """
    🌟 INTELLIGENT SESSION STARTUP
    
    Provides context-aware session initialization with automatic discovery
    of recent collaborative work and intelligent summarization.
    """
    
    def __init__(self):
        self.memory_interface = MemoryInterface()
        self.indexer = ComprehensiveIndexer()
        self.git_root = self._detect_git_root()
        
    def display_enhanced_startup(self, minimal: bool = False, full: bool = False) -> str:
        """
        🌟 ENHANCED MIRA SESSION STARTUP
        
        Displays intelligent session context with recent work analysis.
        
        Args:
            minimal: Show minimal output
            full: Show comprehensive analysis
            
        Returns:
            Formatted startup display string
        """
        output_lines = []
        
        if not minimal:
            output_lines.append("🌟 MIRA Enhanced Session Startup")
            output_lines.append("=" * 60)
        
        try:
            # Initialize memory system
            self.memory_interface.initialize()
            
            # Step 1: Trigger conversation ingestion for latest data
            if not minimal:
                output_lines.append("\n🔄 Syncing latest conversation data...")
            
            ingestion_result = trigger_conversation_ingestion(hours_back=24)
            if ingestion_result['success'] and ingestion_result['new_messages'] > 0:
                output_lines.append(f"   ✅ Processed {ingestion_result['new_messages']} new messages")
            elif not minimal:
                output_lines.append(f"   ✅ All conversations up to date ({ingestion_result['messages_after']} total)")
            
            # Step 2: Intelligent name detection and personalized greeting
            if not minimal:
                greeting = self._get_personalized_greeting()
                output_lines.append(f"\n{greeting}")
            
            # Step 3: Recent work analysis
            recent_work = self._analyze_recent_work()
            if recent_work:
                output_lines.append("\n🔥 Recent Things We've Been Working On:")
                for item in recent_work[:5 if not full else 10]:
                    output_lines.append(f"   • {item}")
            
            # Step 4: Memory system status
            memory_stats = self.memory_interface.stats()
            if minimal:
                output_lines.append(f"✅ Memory system ready: {memory_stats['total_memories']} memories accessible")
            else:
                output_lines.append(f"\n🧠 Memory System Status:")
                output_lines.append(f"   📚 {memory_stats['total_memories']} memories accessible")
                output_lines.append(f"   🎯 Identity: {memory_stats['identity']}")
                intel_stats = memory_stats.get('intelligence', {})
                if intel_stats:
                    output_lines.append(f"   🤖 Intelligence: {intel_stats.get('embedding_model', 'Ready')}")
                    output_lines.append(f"   🔍 Vector Search: {intel_stats.get('vector_search', 'Ready')}")
            
            # Step 5: Project context
            project_context = self._get_project_context()
            if project_context and not minimal:
                output_lines.append(f"\n📍 Current Project Context:")
                output_lines.append(f"   {project_context}")
            
            # Step 6: Recent accomplishments
            accomplishments = self._get_recent_accomplishments()
            if accomplishments and (full or not minimal):
                output_lines.append(f"\n🎉 Recent Accomplishments:")
                for acc in accomplishments[:3]:
                    output_lines.append(f"   ✅ {acc}")
            
            # Step 7: Conversation statistics
            conv_stats = self.indexer.get_stats()
            if conv_stats['total_messages'] > 0:
                if minimal:
                    output_lines.append(f"💬 {conv_stats['total_messages']} conversation messages indexed")
                else:
                    output_lines.append(f"\n💬 Conversation Intelligence:")
                    output_lines.append(f"   📊 {conv_stats['total_messages']} messages indexed across {conv_stats['total_projects']} projects")
                    if conv_stats['cache_size'] > 0:
                        output_lines.append(f"   ⚡ {conv_stats['cache_size']} priority items cached for quick access")
            
            # Step 8: Current phase and suggestions
            if not minimal:
                phase, suggestions = self._get_phase_and_suggestions()
                if phase:
                    output_lines.append(f"\n🎯 Current Phase: {phase}")
                if suggestions:
                    output_lines.append(f"\n💡 Intelligent Suggestions:")
                    for suggestion in suggestions[:3]:
                        output_lines.append(f"   • {suggestion}")
            
            # Step 9: Available perspectives (if not minimal)
            if full:
                output_lines.append(f"\n🎭 Available AI Perspectives:")
                perspectives = self._get_available_perspectives()
                for persp in perspectives[:4]:
                    output_lines.append(f"   {persp}")
                if len(perspectives) > 4:
                    output_lines.append(f"   ... and {len(perspectives) - 4} more")
            
            # Step 10: Quick commands
            if not minimal:
                output_lines.append(f"\n🛠️ Quick Commands:")
                output_lines.append(f"   mira search <query>     - Search memories and conversations")
                output_lines.append(f"   mira store <content>    - Store new memory")
                output_lines.append(f"   mira recall <query>     - Intelligent memory recall")
                if full:
                    output_lines.append(f"   mira index-conversations - Update conversation index")
                    output_lines.append(f"   mira generate-video     - Create memory video")
                    output_lines.append(f"   mira journey <query>    - Semantic journey search")
        
        except Exception as e:
            logger.error(f"Error during startup: {e}")
            output_lines.append(f"⚠️ Startup completed with errors: {e}")
            output_lines.append("💡 Try running 'mira setup' to reconfigure the system")
        
        if not minimal:
            output_lines.append("\n" + "=" * 60)
        
        return "\n".join(output_lines)
    
    def _get_personalized_greeting(self) -> str:
        """Get personalized greeting using ML-powered name detection."""
        try:
            detection_result = detect_user_name()
            
            if detection_result['detected']:
                name = detection_result['name']
                confidence = detection_result['confidence']
                time_of_day = self._get_time_of_day_greeting()
                
                logger.info(f"Personalized greeting for {name} (confidence: {confidence:.2f})")
                return f"👋 {time_of_day}, {name}! Ready to continue our work together?"
            else:
                time_of_day = self._get_time_of_day_greeting()
                return f"👋 {time_of_day}! Ready to dive into our collaborative work?"
                
        except Exception as e:
            logger.debug(f"Name detection failed: {e}")
            return "👋 Hello! Ready to continue our development journey?"
    
    def _get_time_of_day_greeting(self) -> str:
        """Get appropriate greeting based on time of day."""
        hour = datetime.now().hour
        if 5 <= hour < 12:
            return "Good morning"
        elif 12 <= hour < 17:
            return "Good afternoon"
        elif 17 <= hour < 22:
            return "Good evening"
        else:
            return "Hello"
    
    def _analyze_recent_work(self) -> List[str]:
        """Analyze recent work from conversations and git history."""
        recent_work = []
        
        try:
            # Get recent conversation topics using FTS5 search
            conn = self.indexer._get_connection()
            cursor = conn.cursor()
            
            # Search for recent development activities
            development_queries = [
                "fix OR fixed OR fixing",
                "implement OR implemented OR implementing", 
                "create OR created OR creating",
                "enhance OR enhanced OR enhancing",
                "update OR updated OR updating",
                "build OR built OR building",
                "test OR tested OR testing",
                "debug OR debugging",
                "refactor OR refactored OR refactoring"
            ]
            
            work_items = defaultdict(int)
            
            for query in development_queries:
                try:
                    cursor.execute('''
                        SELECT c.content, c.timestamp
                        FROM conversations c
                        JOIN conversations_fts fts ON fts.content = c.content
                        WHERE conversations_fts MATCH ? 
                          AND c.role = 'assistant'
                          AND length(c.content) > 50
                          AND length(c.content) < 500
                        ORDER BY c.timestamp DESC
                        LIMIT 20
                    ''', (query,))
                    
                    for content, timestamp in cursor.fetchall():
                        # Extract work items using intelligent parsing
                        work_item = self._extract_work_item(content)
                        if work_item:
                            work_items[work_item] += 1
                
                except Exception as e:
                    logger.debug(f"Search failed for '{query}': {e}")
                    continue
            
            conn.close()
            
            # Get recent git commits for additional context
            git_work = self._get_recent_git_work()
            for item in git_work:
                work_items[item] += 2  # Weight git commits higher
            
            # Sort by frequency/importance and return top items
            sorted_work = sorted(work_items.items(), key=lambda x: x[1], reverse=True)
            recent_work = [item for item, _ in sorted_work[:10]]
            
        except Exception as e:
            logger.debug(f"Error analyzing recent work: {e}")
            # Fallback to git-only analysis
            recent_work = self._get_recent_git_work()
        
        return recent_work
    
    def _extract_work_item(self, content: str) -> Optional[str]:
        """Extract a concise work item description from conversation content."""
        # Look for patterns that indicate completed work
        patterns = [
            r"(?:Successfully|✅|Completed|Finished|Done|Fixed|Implemented|Created|Built|Enhanced|Updated)\s+([^.!?\n]{10,80})",
            r"I(?:'ve| have)\s+(fixed|implemented|created|built|enhanced|updated|added)\s+([^.!?\n]{10,80})",
            r"(?:The|This)\s+([^.!?\n]{10,80})\s+(?:is|has been|was)\s+(?:fixed|implemented|created|built|enhanced|updated|completed)"
        ]
        
        for pattern in patterns:
            matches = re.finditer(pattern, content, re.IGNORECASE)
            for match in matches:
                if len(match.groups()) >= 2:
                    # Extract the main part of the work item
                    work_item = match.group(2).strip()
                elif len(match.groups()) == 1:
                    work_item = match.group(1).strip()
                else:
                    continue
                
                # Clean up the work item
                work_item = re.sub(r'^(the|a|an)\s+', '', work_item, flags=re.IGNORECASE)
                work_item = work_item.strip(' .,!?;:')
                
                # Filter out overly generic items
                if len(work_item) >= 15 and not any(word in work_item.lower() for word in ['error', 'issue', 'problem', 'warning']):
                    return work_item
        
        return None
    
    def _get_recent_git_work(self) -> List[str]:
        """Get recent work items from git commit history."""
        if not self.git_root:
            return []
        
        try:
            result = subprocess.run([
                'git', 'log', '--oneline', '--max-count=10', 
                '--pretty=format:%s', '--since=7 days ago'
            ], capture_output=True, text=True, cwd=self.git_root)
            
            if result.returncode == 0 and result.stdout.strip():
                commits = result.stdout.strip().split('\n')
                work_items = []
                
                for commit in commits:
                    # Extract work item from commit message
                    # Remove conventional commit prefixes
                    clean_commit = re.sub(r'^(feat|fix|docs|style|refactor|test|chore)(\([^)]+\))?\s*:\s*', '', commit)
                    if len(clean_commit) > 10:
                        work_items.append(clean_commit)
                
                return work_items[:5]
        
        except Exception as e:
            logger.debug(f"Error getting git work: {e}")
        
        return []
    
    def _get_recent_accomplishments(self) -> List[str]:
        """Get recent accomplishments from conversations."""
        try:
            conn = self.indexer._get_connection()
            cursor = conn.cursor()
            
            # Search for accomplishment indicators
            cursor.execute('''
                SELECT c.content
                FROM conversations c
                JOIN conversations_fts fts ON fts.content = c.content
                WHERE conversations_fts MATCH "successfully OR completed OR finished OR working OR operational"
                  AND c.role = 'assistant'
                  AND length(c.content) > 30
                  AND length(c.content) < 200
                ORDER BY c.timestamp DESC
                LIMIT 10
            ''')
            
            accomplishments = []
            for (content,) in cursor.fetchall():
                # Extract accomplishment statements
                if any(word in content.lower() for word in ['✅', 'successfully', 'complete', 'working', 'operational', 'ready']):
                    # Clean up the text
                    clean_text = re.sub(r'[✅❌⚠️🔍🎉🚀💡📊🧠]+', '', content).strip()
                    if 20 <= len(clean_text) <= 150:
                        accomplishments.append(clean_text)
            
            conn.close()
            return accomplishments[:5]
            
        except Exception as e:
            logger.debug(f"Error getting accomplishments: {e}")
            return []
    
    def _get_project_context(self) -> Optional[str]:
        """Get current project context."""
        if not self.git_root:
            return None
        
        try:
            # Get current branch
            branch_result = subprocess.run(['git', 'branch', '--show-current'], 
                                         capture_output=True, text=True, cwd=self.git_root)
            
            # Get project name
            project_name = self.git_root.name
            
            if branch_result.returncode == 0:
                branch = branch_result.stdout.strip()
                return f"Project: {project_name} (branch: {branch})"
            else:
                return f"Project: {project_name}"
        
        except Exception:
            return None
    
    def _get_phase_and_suggestions(self) -> Tuple[Optional[str], List[str]]:
        """Get current development phase and intelligent suggestions."""
        phase = None
        suggestions = []
        
        try:
            # Detect phase from recent git activity
            if self.git_root:
                result = subprocess.run([
                    'git', 'log', '--oneline', '--max-count=3', '--pretty=format:%s'
                ], capture_output=True, text=True, cwd=self.git_root)
                
                if result.returncode == 0:
                    recent_commits = result.stdout.lower()
                    
                    if 'feat:' in recent_commits or 'implement' in recent_commits:
                        phase = "Implementation & Feature Development"
                        suggestions.append("Continue feature implementation")
                        suggestions.append("Add tests for new features")
                    elif 'fix:' in recent_commits or 'debug' in recent_commits:
                        phase = "Testing & Bug Fixing"
                        suggestions.append("Verify fixes work as expected")
                        suggestions.append("Consider adding preventive tests")
                    elif 'docs:' in recent_commits:
                        phase = "Documentation & Polish"
                        suggestions.append("Review documentation completeness")
                        suggestions.append("Update README and guides")
                    elif 'refactor:' in recent_commits:
                        phase = "Code Improvement & Optimization"
                        suggestions.append("Continue refactoring for clarity")
                        suggestions.append("Performance optimization opportunities")
                    else:
                        phase = "Active Development"
                        suggestions.append("Plan next development steps")
            
            # Add general suggestions
            suggestions.extend([
                "Use memory system to track progress",
                "Search conversation history for context",
                "Consider different analytical perspectives"
            ])
        
        except Exception as e:
            logger.debug(f"Error detecting phase: {e}")
        
        return phase, suggestions[:5]
    
    def _get_available_perspectives(self) -> List[str]:
        """Get available AI analytical perspectives."""
        perspectives = [
            "🏗️ Architecture - System design and structure",
            "🔍 Debug - Problem analysis and troubleshooting", 
            "⚡ Performance - Optimization and efficiency",
            "🛡️ Security - Safety and vulnerability analysis",
            "📚 Documentation - Clarity and completeness",
            "🎓 Learning - Best practices and growth",
            "👤 UX - User experience and usability",
            "🧪 Testing - Quality assurance and validation"
        ]
        return perspectives
    
    def _detect_git_root(self) -> Optional[Path]:
        """Detect git repository root."""
        try:
            current = Path.cwd()
            for parent in [current] + list(current.parents):
                if (parent / '.git').exists():
                    return parent
        except Exception:
            pass
        return None

# Main entry point for the startup command
def enhanced_startup_main(minimal: bool = False, full: bool = False) -> str:
    """
    Main entry point for enhanced startup display.
    
    Args:
        minimal: Show minimal output
        full: Show comprehensive analysis
        
    Returns:
        Formatted startup display
    """
    try:
        startup = RecentWorkStartup()
        return startup.display_enhanced_startup(minimal=minimal, full=full)
    except Exception as e:
        logger.error(f"Startup failed: {e}")
        return f"⚠️ Enhanced startup failed: {e}\n💡 Try running 'mira setup' to reconfigure"

if __name__ == "__main__":
    import sys
    
    # Parse command line arguments
    minimal = '--minimal' in sys.argv or '-q' in sys.argv
    full = '--full' in sys.argv or '-f' in sys.argv
    
    print(enhanced_startup_main(minimal=minimal, full=full))