#!/usr/bin/env python3
"""
Quick Startup - Fast session initialization without ML ingestion
===============================================================

Provides a quick startup option that doesn't require full ML ingestion,
preventing timeouts while still providing useful session context.
"""

import os
import json
from pathlib import Path
from datetime import datetime
from typing import Dict, Any

from core.mira_path_resolver import get_mira_memory_dir
from interfaces.interface import MemoryInterface
from conversations.comprehensive_indexer import ComprehensiveIndexer
from intelligence.claude_session_handoff import ClaudeSessionHandoff
from intelligence.steward_profile import StewardProfile
from intelligence.work_context_intelligence import get_work_context_intelligence
from core.memory.memory_essence import MemoryEssence


def quick_startup_main(minimal: bool = False, full: bool = False) -> str:
    """Quick startup without ML ingestion - includes steward profile"""
    output_lines = []
    
    if not minimal:
        output_lines.append("🌟 MIRA Quick Session Startup")
        output_lines.append("=" * 60)
    
    try:
        # Get steward profile and essence
        steward_profile = StewardProfile()
        profile = steward_profile.get_profile()
        essence = MemoryEssence()
        essence_data = essence.load_essence()
        
        # Get work context
        work_context = get_work_context_intelligence()
        work_summary = work_context.get_session_summary()
        
        # Display steward recognition
        if essence_data and not minimal:
            relationship = essence_data.get("relationship", {})
            steward_name = relationship.get("steward_name", "Unknown")
            trust_level = relationship.get("trust_level", "developing")
            
            output_lines.append("\n👤 STEWARD RECOGNITION")
            output_lines.append(f"   Name: {steward_name}")
            output_lines.append(f"   Relationship: {trust_level}")
            output_lines.append(f"   Created: {profile.get('created_at', 'Unknown')}")
            
            # Display personality profile
            if profile.get("communication_style"):
                output_lines.append(f"\n🧠 PERSONALITY PROFILE")
                output_lines.append(f"   Communication Style: {profile['communication_style']}")
                if profile.get("work_patterns", {}).get("style"):
                    output_lines.append(f"   Work Style: {profile['work_patterns']['style']}")
                if profile.get("decision_style"):
                    output_lines.append(f"   Decision Style: {profile['decision_style']}")
            
            # Technical preferences
            tech_prefs = profile.get("technical_preferences", {})
            if tech_prefs:
                output_lines.append(f"\n💻 TECHNICAL PREFERENCES")
                if tech_prefs.get("coding_style"):
                    output_lines.append(f"   Coding Style: {tech_prefs['coding_style']}")
                if tech_prefs.get("preferred_languages"):
                    output_lines.append(f"   Languages: {', '.join(tech_prefs['preferred_languages'][:3])}")
                if tech_prefs.get("valued_practices"):
                    output_lines.append(f"   Practices: {', '.join(tech_prefs['valued_practices'][:3])}")
            
            # Work patterns
            work_patterns = profile.get("work_patterns", {})
            if work_patterns.get("peak_hours"):
                output_lines.append(f"\n⏰ WORK PATTERNS")
                output_lines.append(f"   Peak Hours: {', '.join(str(h) + ':00' for h in work_patterns['peak_hours'][:3])}")
                if work_patterns.get("common_tasks"):
                    output_lines.append(f"   Common Tasks: {', '.join(work_patterns['common_tasks'][:3])}")
        
        # Display work context
        if work_summary and not minimal:
            output_lines.append(f"\n💼 CURRENT WORK CONTEXT")
            if work_summary.get("active_projects"):
                projects = work_summary["active_projects"]
                output_lines.append(f"   Active Projects: {len(projects)}")
                for proj in projects[:3]:
                    output_lines.append(f"     • {proj['name']} ({proj['status']})")
            
            output_lines.append(f"   Momentum: {work_summary.get('momentum_status', 'unknown')}")
            
            if work_summary.get("pending_critical"):
                output_lines.append(f"   ⚠️  Critical Items: {len(work_summary['pending_critical'])}")
        
        # Key memories and journey
        if essence_data and not minimal:
            key_memories = essence_data.get("key_memories", [])
            if key_memories:
                output_lines.append(f"\n🗝️  KEY MEMORIES ({len(key_memories)} total)")
                for mem in key_memories[:3]:
                    content = mem.get("content", "")[:80]
                    output_lines.append(f"   • {content}...")
            
            # Emotional highlights
            emotional = essence_data.get("emotional_highlights", [])
            if emotional:
                output_lines.append(f"\n✨ JOURNEY HIGHLIGHTS")
                for highlight in emotional[:2]:
                    output_lines.append(f"   • {highlight}")
        
        # Session handoff summary
        try:
            handoff = ClaudeSessionHandoff()
            handoff_summary = handoff.generate_handoff_summary(verbose=False)
            if handoff_summary.get("continuation_suggestions") and not minimal:
                output_lines.append(f"\n💡 SUGGESTED NEXT STEPS")
                for i, suggestion in enumerate(handoff_summary["continuation_suggestions"][:3], 1):
                    output_lines.append(f"   {i}. {suggestion['description']}")
                    if suggestion.get('command'):
                        output_lines.append(f"      → {suggestion['command']}")
        except:
            pass
        # Get basic stats without full initialization
        memory_dir = get_mira_memory_dir()
        
        # Count existing memories
        memory_count = 0
        memories_dir = os.path.join(memory_dir, "memories")
        if os.path.exists(memories_dir):
            for file in os.listdir(memories_dir):
                if file.endswith('.json'):
                    memory_count += 1
        
        # Get conversation stats from indexer (fast)
        try:
            indexer = ComprehensiveIndexer()
            stats = indexer.get_stats()
            total_messages = stats.get('total_messages', 0)
            total_conversations = stats.get('total_conversations', 0)
        except:
            total_messages = 0
            total_conversations = 0
        
        # Get last activity
        last_activity = "Unknown"
        try:
            for dir_name in ['conversations', 'memories', 'journey', 'essence']:
                dir_path = os.path.join(memory_dir, dir_name)
                if os.path.exists(dir_path):
                    for file in os.listdir(dir_path):
                        file_path = os.path.join(dir_path, file)
                        if os.path.isfile(file_path):
                            mtime = os.path.getmtime(file_path)
                            if mtime > 0:
                                last_activity = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M")
                                break
        except:
            pass
        
        # Display summary
        output_lines.append("\n📊 Memory System Status:")
        output_lines.append(f"   • {memory_count} memories accessible")
        output_lines.append(f"   • {total_messages} messages indexed")
        output_lines.append(f"   • {total_conversations} conversations tracked")
        output_lines.append(f"   • Last activity: {last_activity}")
        
        # Available commands
        if not minimal:
            output_lines.append("\n🛠️  Available Commands:")
            output_lines.append("   • mira search <query> - Search memories and conversations")
            output_lines.append("   • mira store <content> - Store new memory")
            output_lines.append("   • mira journey - Explore development journey")
            output_lines.append("   • mira essence - View memory essence")
            output_lines.append("   • mira index - Index new conversations")
        
        # Check for daemon
        output_lines.append("\n🤖 Background Services:")
        pid_file = "/tmp/mira-daemon.pid"
        if os.path.exists(pid_file):
            try:
                with open(pid_file, 'r') as f:
                    pid = f.read().strip()
                # Check if process is running
                os.kill(int(pid), 0)
                output_lines.append("   ✅ Background daemon is running")
                output_lines.append("   • Continuous conversation indexing active")
                output_lines.append("   • Real-time memory management enabled")
            except:
                output_lines.append("   ⚠️  Background daemon is not running")
                output_lines.append("   • Run 'mira daemon start' to enable real-time indexing")
        else:
            output_lines.append("   ⚠️  Background daemon is not running")
            output_lines.append("   • Run 'mira daemon start' to enable real-time indexing")
        
        # Private memory reminder
        output_lines.append("\n🔒 Private Memory Space:")
        output_lines.append("   • Your encrypted memory space is accessible")
        output_lines.append("   • Triple encryption with mathematical constants active")
        output_lines.append("   • See CLAUDE.md for access instructions")
        
        return '\n'.join(output_lines)
        
    except Exception as e:
        return f"⚠️  Quick startup completed with warnings: {str(e)}"


if __name__ == "__main__":
    print(quick_startup_main())