#!/usr/bin/env python3
"""
Enhanced Startup - Comprehensive session initialization with full steward context
================================================================================

Provides enhanced startup with complete steward profile, work context, and
memory analysis for optimal Claude instance handoff.
"""

import os
import json
import sys
import time
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List

# Add parent directory to path to access modules
sys.path.insert(0, str(Path(__file__).parent.parent))

try:
    from config import MEMORY_DIR
    def get_mira_memory_dir():
        return MEMORY_DIR
except ImportError:
    # Fallback if config not found
    def get_mira_memory_dir():
        return str(Path.home() / ".mira")
from interfaces.interface import MemoryInterface
from conversations.comprehensive_indexer import ComprehensiveIndexer
from intelligence.claude_session_handoff import ClaudeSessionHandoff
from intelligence.claude_message_intelligence import ClaudeMessageIntelligence
from intelligence.steward_profile import StewardProfile
from intelligence.work_context_intelligence import get_work_context_intelligence
from intelligence.adaptive_pattern_evolution import get_adaptive_pattern_evolution
from intelligence.meta_pattern_learning import get_meta_pattern_learning
from intelligence.project_context_detection import get_project_context_detector
from core.memory.memory_essence import MemoryEssence
from core.memory.memory_manager import MemoryManager


def enhanced_startup_main(minimal: bool = False, full: bool = False) -> str:
    """Enhanced startup with full steward context and memory analysis"""
    start_time = time.time()
    section_times = {}
    output_lines = []
    
    if not minimal:
        output_lines.append("🌟 MIRA Enhanced Session Startup")
        output_lines.append("=" * 60)
        output_lines.append("Initializing comprehensive steward profile and context...")
        output_lines.append("")
    
    try:
        # Initialize all intelligence systems
        section_start = time.time()
        steward_profile = StewardProfile()
        profile = steward_profile.get_profile()
        behavioral_insights = steward_profile.get_behavioral_insights()
        section_times['steward_profile'] = time.time() - section_start
        
        section_start = time.time()
        essence = MemoryEssence()
        essence_data = essence.load_essence()
        section_times['memory_essence'] = time.time() - section_start
        
        section_start = time.time()
        work_context = get_work_context_intelligence()
        work_analysis = work_context.analyze_current_context(hours_back=72)
        section_times['work_context'] = time.time() - section_start
        
        # Get project context
        section_start = time.time()
        project_detector = get_project_context_detector()
        project_context = project_detector.detect_project_context()
        section_times['project_context'] = time.time() - section_start
        
        section_start = time.time()
        memory_manager = MemoryManager()
        section_times['memory_manager'] = time.time() - section_start
        
        # Get pattern evolution stats
        section_start = time.time()
        try:
            pattern_evolution = get_adaptive_pattern_evolution(get_mira_memory_dir())
            evolution_stats = pattern_evolution.get_evolution_stats()
            meta_learning = get_meta_pattern_learning(get_mira_memory_dir())
            meta_stats = meta_learning.get_meta_learning_statistics()
        except:
            evolution_stats = {}
            meta_stats = {}
        section_times['pattern_evolution'] = time.time() - section_start
        
        # Initialize Claude Message Intelligence for steward rules
        section_start = time.time()
        claude_intelligence = ClaudeMessageIntelligence()
        steward_messages = claude_intelligence.load_all_messages(get_mira_memory_dir())
        section_times['claude_intelligence'] = time.time() - section_start
        
        # SECTION 1: STEWARD IDENTITY AND RECOGNITION
        output_lines.append("👤 STEWARD IDENTITY")
        output_lines.append("-" * 50)
        
        # Try to get name from name detection system first
        steward_name = "Unknown"
        name_confidence = 0
        try:
            from intelligence.name_detection import detect_user_name
            name_result = detect_user_name()
            if name_result.get('detected') and name_result.get('name') != 'User':
                steward_name = name_result['name']
                name_confidence = name_result.get('confidence', 0)
                output_lines.append(f"Name: {steward_name} (confidence: {name_confidence:.1f})")
            else:
                output_lines.append(f"Name: {steward_name}")
        except Exception as e:
            # Fallback to essence data
            if essence_data:
                relationship = essence_data.get("relationship", {})
                steward_name = relationship.get("steward_name", "Unknown")
            output_lines.append(f"Name: {steward_name}")
        
        # Get relationship details from essence
        if essence_data:
            relationship = essence_data.get("relationship", {})
            trust_level = relationship.get("trust_level", "developing")
            collaboration_style = relationship.get("collaboration_style", "professional")
            
            output_lines.append(f"Relationship Level: {trust_level}")
            output_lines.append(f"Collaboration Style: {collaboration_style}")
            output_lines.append(f"Profile Created: {profile.get('created_at', 'Unknown')}")
            
            # Add identity essence
            if relationship.get("essence_statement"):
                output_lines.append(f"\nEssence: {relationship['essence_statement']}")
            
            # Add name detection source if available
            if name_confidence > 0:
                output_lines.append(f"Name Source: Conversation analysis (ML-detected)")
        else:
            output_lines.append("Relationship Level: developing")
            output_lines.append("Collaboration Style: professional")
            if name_confidence > 0:
                output_lines.append(f"Name Source: Conversation analysis (ML-detected)")
        
        # SECTION 1B: STEWARD RULES & PREFERENCES
        output_lines.append("\n\n🔧 STEWARD RULES & PREFERENCES")
        output_lines.append("-" * 50)
        
        if steward_messages:
            # Filter and organize messages by type and priority
            rules = [m for m in steward_messages if m.message_type.value in ['rule', 'preference', 'instruction']]
            high_priority = [m for m in rules if m.priority >= 7]
            medium_priority = [m for m in rules if 4 <= m.priority < 7]
            
            if high_priority:
                output_lines.append("🚨 Critical Rules & Instructions:")
                for msg in high_priority[:5]:  # Top 5 high priority
                    output_lines.append(f"   • {msg.content}")
                    if msg.message_type.value == 'rule':
                        output_lines.append(f"     (RULE - Priority: {msg.priority})")
                    elif msg.message_type.value == 'preference':
                        output_lines.append(f"     (PREFERENCE - Priority: {msg.priority})")
                    elif msg.message_type.value == 'instruction':
                        output_lines.append(f"     (INSTRUCTION - Priority: {msg.priority})")
            
            if medium_priority:
                if high_priority:
                    output_lines.append("")
                output_lines.append("📋 Important Preferences & Guidelines:")
                for msg in medium_priority[:5]:  # Top 5 medium priority
                    output_lines.append(f"   • {msg.content}")
                    if len(msg.keywords) > 0:
                        output_lines.append(f"     (Tags: {', '.join(msg.keywords[:3])})")
            
            # Show guidance and context messages
            guidance = [m for m in steward_messages if m.message_type.value in ['guidance', 'context', 'warning']]
            if guidance:
                if high_priority or medium_priority:
                    output_lines.append("")
                output_lines.append("💡 Additional Guidance:")
                for msg in guidance[:3]:  # Top 3 guidance messages
                    msg_type_icon = {"guidance": "🎯", "context": "📝", "warning": "⚠️"}.get(msg.message_type.value, "💡")
                    output_lines.append(f"   {msg_type_icon} {msg.content}")
            
            # Summary
            total_active_rules = len([m for m in rules if m.priority >= 4])
            if total_active_rules > 0:
                output_lines.append(f"\nTotal Active Rules/Preferences: {total_active_rules}")
        else:
            output_lines.append("No specific rules or preferences detected yet.")
            output_lines.append("Use natural language to tell MIRA to remember rules, preferences, or instructions.")
            output_lines.append("Example: 'Remember this rule: always run tests before committing'")
        
        # SECTION 2: PROJECT OVERVIEW & MISSION
        output_lines.append("\n\n📁 PROJECT OVERVIEW & MISSION")
        output_lines.append("-" * 50)
        
        if not project_context.get("error"):
            summary = project_context.get("summary", {})
            purpose = project_context.get("project_purpose", {})
            project_type = project_context.get("project_type", {})
            tech_stack = project_context.get("tech_stack", {})
            health = project_context.get("project_health", {})
            os_info = project_context.get("operating_system", {})
            
            # Project Identity and Mission
            project_name = summary.get('name', 'Unknown')
            output_lines.append(f"🎯 Project: {project_name}")
            output_lines.append(f"📋 Type: {summary.get('type', 'Unknown')}")
            
            # Operating System Information
            if os_info and not os_info.get("error"):
                platform_name = os_info.get("platform", "Unknown")
                system_alias = os_info.get("system_alias")
                architecture = os_info.get("architecture", "")
                
                # Create OS display string
                if system_alias:
                    os_display = f"{system_alias}"
                    if architecture and architecture not in system_alias:
                        os_display += f" ({architecture})"
                else:
                    os_display = f"{platform_name}"
                    if architecture:
                        os_display += f" {architecture}"
                
                # Add environment context
                env_contexts = []
                if os_info.get("is_codespace"):
                    env_contexts.append("GitHub Codespaces")
                elif os_info.get("is_container"):
                    env_contexts.append("Container")
                elif os_info.get("is_wsl"):
                    env_contexts.append("WSL")
                
                if env_contexts:
                    os_display += f" [{', '.join(env_contexts)}]"
                
                output_lines.append(f"💻 OS Environment: {os_display}")
            
            # Project Description and Purpose
            description = purpose.get("description", "No description available")
            if not description.startswith("No description"):
                output_lines.append(f"\n🌟 Mission:")
                # Wrap description for better readability
                words = description.split()
                line_length = 0
                current_line = "   "
                for word in words:
                    if line_length + len(word) + 1 > 70:
                        output_lines.append(current_line)
                        current_line = "   " + word
                        line_length = len(word) + 3
                    else:
                        if line_length > 3:
                            current_line += " "
                            line_length += 1
                        current_line += word
                        line_length += len(word)
                if current_line.strip():
                    output_lines.append(current_line)
            
            # Key Features
            features = purpose.get("key_features", [])
            if features:
                output_lines.append(f"\n🔧 Key Capabilities:")
                for feature in features[:4]:
                    output_lines.append(f"   • {feature}")
            
            # Technology Stack
            if tech_stack.get("languages"):
                languages = ", ".join(tech_stack["languages"])
                output_lines.append(f"\n💻 Tech Stack: {languages}")
            
            if tech_stack.get("frameworks"):
                frameworks = ", ".join(tech_stack["frameworks"])
                output_lines.append(f"🛠️  Frameworks: {frameworks}")
            
            # Project Health and Status
            status_emoji = {"excellent": "🟢", "good": "🟡", "fair": "🟠", "needs_improvement": "🔴"}.get(health.get("status"), "⚪")
            output_lines.append(f"\n📊 Project Health: {status_emoji} {health.get('status', 'unknown').title()} ({health.get('score', 0)}/100)")
            
            # Show specific health indicators
            health_indicators = health.get("indicators", [])
            for indicator in health_indicators[:4]:
                output_lines.append(f"   {indicator}")
        
        # SECTION 2B: SYSTEM ARCHITECTURE OVERVIEW
        output_lines.append("\n\n🏗️  SYSTEM ARCHITECTURE OVERVIEW")
        output_lines.append("-" * 50)
        
        if not project_context.get("error"):
            framework_info = project_context.get("framework_info", {})
            dependencies = project_context.get("dependencies", {})
            structure = project_context.get("project_structure", {})
            build_system = project_context.get("build_system", {})
            
            # Architecture Description - Generic for any project
            framework_type = framework_info.get('type', 'Custom')
            project_type_desc = summary.get('type', 'application')
            
            if framework_type != 'Custom':
                output_lines.append(f"🏛️  Architecture: {framework_type} {project_type_desc}")
                
                # Add framework-specific details if available
                if framework_type in ['Next.js', 'React']:
                    output_lines.append("   🌐 Frontend-focused with server-side capabilities")
                elif framework_type in ['Express.js', 'Fastify']:
                    output_lines.append("   🔧 Backend API server with middleware architecture")
                elif framework_type in ['Django', 'Flask']:
                    output_lines.append("   🐍 Python web framework with MVC architecture")
                elif project_type_desc == 'Node.js Application':
                    output_lines.append("   ⚡ Node.js runtime with JavaScript/TypeScript execution")
                elif project_type_desc == 'Python Project':
                    output_lines.append("   🐍 Python-based application with modular architecture")
            else:
                # Detect architecture from project structure and tech stack
                languages = tech_stack.get("languages", [])
                if len(languages) > 1:
                    lang_desc = " + ".join(languages[:3])
                    output_lines.append(f"🏛️  Architecture: Multi-language {project_type_desc} ({lang_desc})")
                    if 'JavaScript' in languages or 'TypeScript' in languages:
                        output_lines.append("   🌐 JavaScript/TypeScript components for user interfaces and APIs")
                    if 'Python' in languages:
                        output_lines.append("   🐍 Python components for data processing and business logic")
                else:
                    output_lines.append(f"🏛️  Architecture: {framework_type} {project_type_desc}")
                    if languages:
                        output_lines.append(f"   📝 Primary language: {languages[0]}")
            
            # Dependencies and Scale
            if dependencies.get("total", 0) > 0:
                output_lines.append(f"\n📦 Dependencies: {dependencies['total']} total ({dependencies.get('production', 0)} production)")
                key_deps = dependencies.get("key_dependencies", [])
                if key_deps:
                    output_lines.append(f"   Key packages: {', '.join(key_deps[:5])}")
            
            # Project Structure
            source_dirs = structure.get("source_dirs", [])
            if source_dirs:
                output_lines.append(f"\n📁 Source Structure: {', '.join(source_dirs)}")
            
            output_lines.append(f"📄 Total Files: {structure.get('total_files', 0)}")
            
            # Build System
            if build_system.get("system"):
                output_lines.append(f"⚙️  Build System: {build_system['system']}")
                scripts = build_system.get("scripts", [])
                if scripts:
                    output_lines.append(f"   Available scripts: {', '.join(scripts[:5])}")
        
        # SECTION 2C: RECENT DEVELOPMENT CONTEXT
        output_lines.append("\n\n🚀 RECENT DEVELOPMENT CONTEXT")
        output_lines.append("-" * 50)
        
        if not project_context.get("error"):
            dev_patterns = project_context.get("development_patterns", {})
            recent_commits = project_context.get("recent_commits", {})
            git_status = project_context.get("git_status", {})
            recent_activity = project_context.get("recent_activity", {})
            
            # Current Development Phase
            dev_phase = dev_patterns.get("development_phase", "unknown")
            dev_velocity = dev_patterns.get("development_velocity", "unknown")
            
            phase_descriptions = {
                "active_feature_development": "🎯 Active Feature Development - Building new capabilities",
                "stabilization": "🔧 Stabilization Phase - Fixing bugs and improving reliability", 
                "refactoring_and_optimization": "⚡ Refactoring & Optimization - Improving code quality",
                "maintenance": "🛠️  Maintenance Mode - Routine updates and minor fixes"
            }
            
            phase_desc = phase_descriptions.get(dev_phase, f"📋 {dev_phase.replace('_', ' ').title()}")
            output_lines.append(f"📈 Current Phase: {phase_desc}")
            output_lines.append(f"🏃 Development Velocity: {dev_velocity.title()}")
            
            # Recent Focus Areas
            recent_focus = dev_patterns.get("recent_focus", [])
            if recent_focus:
                output_lines.append(f"\n🎯 Recent Development Focus:")
                for focus_area in recent_focus:
                    output_lines.append(f"   • {focus_area}")
            
            # Git Status and Recent Activity
            if git_status.get("is_git_repo"):
                branch = git_status.get("current_branch", "unknown")
                has_changes = git_status.get("has_changes", False)
                changed_files = git_status.get("changed_files", 0)
                
                status_indicator = "🔴 uncommitted changes" if has_changes else "🟢 clean working tree"
                output_lines.append(f"\n🌿 Git Status: {branch} branch, {status_indicator}")
                
                if has_changes:
                    output_lines.append(f"   📝 Modified files: {changed_files}")
            
            # Recent Activity Summary
            recent_changes = recent_activity.get("recent_changes", 0)
            if recent_changes > 0:
                output_lines.append(f"⚡ Recent Activity: {recent_changes} files modified this week")
                
                active_files = recent_activity.get("active_files", [])
                if active_files:
                    output_lines.append(f"   Most active: {', '.join(active_files[:3])}")
            
            # Recent Commits Context
            commits = recent_commits.get("recent_commits", [])
            if commits:
                output_lines.append(f"\n📝 Recent Commits ({len(commits)} commits):")
                for commit in commits[:3]:
                    message = commit.get("message", "")[:60] + ("..." if len(commit.get("message", "")) > 60 else "")
                    relative_date = commit.get("relative_date", "")
                    output_lines.append(f"   • {message} ({relative_date})")
                
                if len(commits) > 3:
                    output_lines.append(f"   ... and {len(commits) - 3} more commits")
        
        # SECTION 2D: PROJECT STATUS & HEALTH
        output_lines.append("\n\n📊 PROJECT STATUS & CAPABILITIES")
        output_lines.append("-" * 50)
        
        if not project_context.get("error"):
            testing = project_context.get("testing", {})
            docs = project_context.get("documentation", {})
            deployment = project_context.get("deployment", [])
            
            # Testing Status
            test_files = testing.get("test_files", 0)
            test_framework = testing.get("framework")
            if test_files > 0:
                output_lines.append(f"✅ Testing: {test_files} test files")
                if test_framework:
                    output_lines.append(f"   Framework: {test_framework}")
            else:
                output_lines.append("⚠️ Testing: No tests detected")
            
            # Documentation Status
            doc_coverage = docs.get("coverage", "none")
            doc_files = docs.get("doc_files", [])
            if docs.get("has_readme"):
                output_lines.append(f"✅ Documentation: {doc_coverage.title()} coverage ({len(doc_files)} files)")
            else:
                output_lines.append("⚠️ Documentation: No README found")
            
            # Deployment Configuration
            if deployment:
                output_lines.append(f"🚀 Deployment: {', '.join(deployment[:3])}")
            
            # Summary Assessment - Generic for any project
            health_status = health.get("status", "unknown")
            test_files = testing.get("test_files", 0)
            
            # Create dynamic status message based on project health and activity
            status_messages = {
                "excellent": "🌟 Fully operational with excellent project health",
                "good": "✅ Operational with good project health", 
                "fair": "⚠️ Operational with some areas for improvement",
                "needs_improvement": "🔧 Needs attention in several areas"
            }
            
            status_msg = status_messages.get(health_status, f"📊 Project status: {health_status}")
            output_lines.append(f"\n{status_msg}")
            
            # Add project-specific details
            details = []
            if test_files > 0:
                details.append(f"extensive test coverage ({test_files} files)")
            if docs.get("has_readme"):
                doc_coverage = docs.get("coverage", "basic")
                details.append(f"{doc_coverage} documentation")
            
            git_status = project_context.get("git_status", {})
            if git_status.get("has_changes"):
                changed_files = git_status.get("changed_files", 0)
                details.append("active development")
            
            if details:
                details_text = ", ".join(details)
                output_lines.append(f"   Features: {details_text}")
                
                if git_status.get("has_changes"):
                    changed_files = git_status.get("changed_files", 0)
                    output_lines.append(f"   Currently developing: {changed_files} files being modified")
        
        if project_context.get("error"):
            output_lines.append(f"⚠️ Could not detect full project context: {project_context.get('error')}")
            output_lines.append(f"Working Directory: {project_context.get('project_root', 'Unknown')}")
            output_lines.append("\nNote: Limited context available - operating with basic project awareness.")
        
        # SECTION 3: PERSONALITY PROFILE
        output_lines.append("\n\n🧠 PERSONALITY PROFILE")
        output_lines.append("-" * 50)
        
        output_lines.append(f"Communication Style: {profile.get('communication_style', 'unknown')}")
        output_lines.append(f"Decision Style: {profile.get('decision_style', 'unknown')}")
        
        if behavioral_insights:
            personality = behavioral_insights.get("personality_profile", {})
            output_lines.append(f"Work Style: {personality.get('work_style', 'unknown')}")
            output_lines.append(f"Emotional Baseline: {personality.get('emotional_baseline', 'neutral')}")
            
            # Interaction preferences
            interaction = behavioral_insights.get("interaction_preferences", {})
            if interaction:
                output_lines.append(f"\nInteraction Preferences:")
                output_lines.append(f"  • Emotional Stability: {interaction.get('emotional_stability', 'unknown')}")
                output_lines.append(f"  • Stress Tolerance: {interaction.get('stress_tolerance', 'unknown')}")
        
        # SECTION 4: TECHNICAL PROFILE
        output_lines.append("\n\n💻 TECHNICAL PROFILE")
        output_lines.append("-" * 50)
        
        tech_prefs = profile.get("technical_preferences", {})
        if tech_prefs:
            output_lines.append(f"Coding Style: {tech_prefs.get('coding_style', 'unknown')}")
            output_lines.append(f"Testing Preference: {tech_prefs.get('testing_preference', 'unknown')}")
            output_lines.append(f"Documentation Style: {tech_prefs.get('documentation_style', 'unknown')}")
            
            if tech_prefs.get("preferred_languages"):
                output_lines.append(f"Preferred Languages: {', '.join(tech_prefs['preferred_languages'])}")
            if tech_prefs.get("valued_practices"):
                output_lines.append(f"Valued Practices: {', '.join(tech_prefs['valued_practices'])}")
        
        if behavioral_insights:
            tech_profile = behavioral_insights.get("technical_profile", {})
            if tech_profile.get("paradigms"):
                paradigms = [p[0] for p in tech_profile["paradigms"]]
                output_lines.append(f"Programming Paradigms: {', '.join(paradigms)}")
        
        # SECTION 5: WORK PATTERNS AND RHYTHMS
        output_lines.append("\n\n⏰ WORK PATTERNS")
        output_lines.append("-" * 50)
        
        work_patterns = profile.get("work_patterns", {})
        if work_patterns.get("peak_hours"):
            peak_hours = [f"{h}:00" for h in work_patterns["peak_hours"]]
            output_lines.append(f"Peak Productivity Hours: {', '.join(peak_hours)}")
        if work_patterns.get("style"):
            output_lines.append(f"Work Style: {work_patterns['style']}")
        
        if behavioral_insights:
            patterns = behavioral_insights.get("work_patterns", {})
            if patterns.get("session_style"):
                output_lines.append(f"Session Style: {patterns['session_style']}")
            if patterns.get("preferred_days"):
                output_lines.append(f"Preferred Days: {', '.join(patterns['preferred_days'])}")
        
        # SECTION 6: CURRENT WORK CONTEXT
        output_lines.append("\n\n💼 CURRENT WORK CONTEXT")
        output_lines.append("-" * 50)
        
        # Active projects
        active_projects = work_analysis.get("active_projects", {})
        if active_projects:
            output_lines.append(f"Active Projects: {len(active_projects)}")
            for name, proj in list(active_projects.items())[:5]:
                status = proj.get("status", "unknown")
                activity = proj.get("total_activity", 0)
                output_lines.append(f"  • {name} ({status}) - {activity} activities")
        
        # Work momentum
        momentum = work_analysis.get("momentum_indicators", {})
        output_lines.append(f"\nMomentum Status: {momentum.get('momentum_status', 'unknown')}")
        output_lines.append(f"Momentum Score: {momentum.get('momentum_score', 0)}")
        output_lines.append(f"Pending Items: {momentum.get('pending_thread_count', 0)}")
        if momentum.get("critical_items", 0) > 0:
            output_lines.append(f"⚠️  Critical Items: {momentum['critical_items']}")
        
        # Recent topics
        recent_topics = work_analysis.get("recent_topics", [])
        if recent_topics:
            output_lines.append(f"\nRecent Focus Areas: {', '.join(recent_topics[:10])}")
        
        # Priorities
        priorities = work_analysis.get("priorities", [])
        if priorities:
            output_lines.append("\nTop Priorities:")
            for priority in priorities[:5]:
                output_lines.append(f"  [{priority['urgency']}] {priority['name']}")
        
        # SECTION 7: JOURNEY AND MEMORIES
        output_lines.append("\n\n🗝️  JOURNEY HIGHLIGHTS")
        output_lines.append("-" * 50)
        
        if essence_data:
            # Key memories
            key_memories = essence_data.get("key_memories", [])
            if key_memories:
                output_lines.append(f"Key Memories: {len(key_memories)}")
                for mem in key_memories[:5]:
                    content = mem.get("content", "")[:100]
                    output_lines.append(f"  • {content}...")
            
            # Emotional highlights
            emotional = essence_data.get("emotional_highlights", [])
            if emotional:
                output_lines.append("\nEmotional Highlights:")
                for highlight in emotional[:3]:
                    output_lines.append(f"  • {highlight}")
            
            # Project achievements
            project = essence_data.get("project_context", {})
            achievements = project.get("achievements", [])
            if achievements:
                output_lines.append(f"\nRecent Achievements: {len(achievements)}")
                for achievement in achievements[-3:]:
                    output_lines.append(f"  • {achievement}")
        
        # SECTION 8: PATTERN LEARNING AND INTELLIGENCE
        if evolution_stats and not minimal:
            output_lines.append("\n\n🧬 INTELLIGENCE EVOLUTION")
            output_lines.append("-" * 50)
            output_lines.append(f"Patterns Learned: {evolution_stats.get('total_patterns', 0)}")
            output_lines.append(f"Pattern Types: {evolution_stats.get('pattern_types', 0)}")
            output_lines.append(f"Domains Covered: {evolution_stats.get('domains_covered', 0)}")
            
            if meta_stats:
                output_lines.append(f"Meta-Learning Insights: {len(meta_stats.get('insights_by_type', {}))}")
                output_lines.append(f"Learning Velocity: {meta_stats.get('learning_velocity', 0):.2f}")
        
        # SECTION 9: MEMORY SYSTEM STATUS
        output_lines.append("\n\n📊 MEMORY SYSTEM STATUS")
        output_lines.append("-" * 50)
        
        # Count memories
        memory_count = 0
        memories_dir = os.path.join(get_mira_memory_dir(), "memories")
        if os.path.exists(memories_dir):
            memory_count = len([f for f in os.listdir(memories_dir) if f.endswith('.json')])
        
        # Get conversation stats
        section_start = time.time()
        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
        section_times['conversation_indexing'] = time.time() - section_start
        
        output_lines.append(f"Memories Stored: {memory_count}")
        output_lines.append(f"Messages Indexed: {total_messages}")
        output_lines.append(f"Conversations Tracked: {total_conversations}")
        
        # Active memories
        try:
            active_memories = memory_manager.get_active_memories(max_chars=1000)
            output_lines.append(f"Active Memories: {len(active_memories)}")
        except:
            pass
        
        # SECTION 10: CONTINUATION SUGGESTIONS
        output_lines.append("\n\n💡 CONTINUATION RECOMMENDATIONS")
        output_lines.append("-" * 50)
        
        # Get handoff suggestions
        section_start = time.time()
        try:
            handoff = ClaudeSessionHandoff()
            handoff_summary = handoff.generate_handoff_summary(verbose=False)
            suggestions = handoff_summary.get("continuation_suggestions", [])
            
            for i, suggestion in enumerate(suggestions[:5], 1):
                output_lines.append(f"{i}. {suggestion['description']}")
                if suggestion.get('command'):
                    output_lines.append(f"   → {suggestion['command']}")
        except:
            pass
        section_times['session_handoff'] = time.time() - section_start
        
        # Work recommendations
        recommendations = work_analysis.get("recommendations", [])
        if recommendations:
            output_lines.append("\nWork Recommendations:")
            for rec in recommendations[:3]:
                output_lines.append(f"  {rec}")
        
        # SECTION 11: QUICK REFERENCE
        if not minimal:
            output_lines.append("\n\n🛠️  QUICK REFERENCE")
            output_lines.append("-" * 50)
            output_lines.append("Key Commands:")
            output_lines.append("  • mira search <query> - Search memories and conversations")
            output_lines.append("  • mira store <content> - Store new memory")
            output_lines.append("  • mira work-context - View work context and priorities")
            output_lines.append("  • mira analyze-behavior - Analyze behavior patterns")
            output_lines.append("  • mira essence - View memory essence")
            output_lines.append("  • mira journey - Explore development journey")
            
            # Preferences summary
            preferences = profile.get("preferences", {})
            if preferences:
                output_lines.append("\nSteward Preferences:")
                if preferences.get("likes_examples"):
                    output_lines.append("  • Prefers examples in responses")
                output_lines.append(f"  • Detail level: {preferences.get('detail_level', 'balanced')}")
                output_lines.append(f"  • Interaction style: {preferences.get('interaction_style', 'collaborative')}")
        
        # SECTION 12: PERFORMANCE TIMING DEBUG
        total_time = time.time() - start_time
        output_lines.append("\n\n⏱️  STARTUP PERFORMANCE DEBUG")
        output_lines.append("-" * 50)
        output_lines.append(f"Total Startup Time: {total_time:.2f} seconds")
        output_lines.append("\nSection Timings:")
        
        # Sort sections by time taken (slowest first)
        sorted_sections = sorted(section_times.items(), key=lambda x: x[1], reverse=True)
        for section, duration in sorted_sections:
            percentage = (duration / total_time) * 100 if total_time > 0 else 0
            output_lines.append(f"  • {section.replace('_', ' ').title()}: {duration:.2f}s ({percentage:.1f}%)")
        
        # Warning for slow sections
        slow_sections = [name for name, duration in section_times.items() if duration > 10]
        if slow_sections:
            output_lines.append(f"\n⚠️  Slow sections (>10s): {', '.join(slow_sections)}")
        
        if total_time > 60:
            output_lines.append(f"\n🔴 WARNING: Startup took {total_time:.1f} seconds (>{60}s threshold)")
        elif total_time > 30:
            output_lines.append(f"\n🟡 NOTICE: Startup took {total_time:.1f} seconds (>{30}s threshold)")
        else:
            output_lines.append(f"\n✅ Startup completed within acceptable time ({total_time:.1f}s)")
        
        # Footer
        output_lines.append("\n" + "=" * 60)
        output_lines.append("MIRA is ready with full steward context loaded")
        output_lines.append("Your journey continues...")
        
        return '\n'.join(output_lines)
        
    except Exception as e:
        import traceback
        error_trace = traceback.format_exc()
        return f"⚠️  Enhanced startup encountered an error: {str(e)}\n\nFalling back to quick startup...\n\nDebug trace:\n{error_trace}"


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