#!/usr/bin/env python3
"""
MIRA Startup Customization Utility
Allows stewards to easily customize their startup experience
"""

import json
from pathlib import Path
from datetime import datetime
import argparse


def load_current_preferences():
    """Load current startup preferences"""
    mira_home = Path.home() / '.mira'
    prefs_path = mira_home / 'steward_profiles' / 'startup_preferences.json'
    
    if prefs_path.exists():
        with open(prefs_path, 'r') as f:
            return json.load(f)
    else:
        return create_default_preferences()


def create_default_preferences():
    """Create default preferences structure"""
    return {
        "steward_id": "steward_default",
        "version": "1.0",
        "startup_customization": {
            "display_mode": "standard",
            "enabled_sections": {
                "identity": True,
                "project": True,
                "work": True,
                "continuity": True,
                "system": True,
                "philosophy": False,
                "quick_reference": True
            },
            "section_order": [
                "identity",
                "project",
                "work",
                "continuity", 
                "system",
                "quick_reference"
            ],
            "personalization": {
                "greeting_style": "casual",
                "detail_level": "balanced",
                "show_encouragement": True,
                "focus_areas": ["development"]
            },
            "advanced_features": {
                "performance_metrics": False,
                "debug_info": False,
                "memory_diagnostics": True,
                "session_insights": True
            }
        },
        "created_at": datetime.now().isoformat(),
        "updated_at": datetime.now().isoformat()
    }


def save_preferences(preferences):
    """Save preferences to file"""
    mira_home = Path.home() / '.mira'
    prefs_path = mira_home / 'steward_profiles' / 'startup_preferences.json'
    
    # Ensure directory exists
    prefs_path.parent.mkdir(parents=True, exist_ok=True)
    
    # Update timestamp
    preferences['updated_at'] = datetime.now().isoformat()
    
    with open(prefs_path, 'w') as f:
        json.dump(preferences, f, indent=2)
    
    print(f"✓ Startup preferences saved to {prefs_path}")


def show_current_settings():
    """Display current startup settings"""
    prefs = load_current_preferences()
    config = prefs.get('startup_customization', {})
    
    print("🌟 Current MIRA Startup Settings")
    print("=" * 50)
    print()
    
    print(f"Display Mode: {config.get('display_mode', 'standard')}")
    print()
    
    print("Enabled Sections:")
    sections = config.get('enabled_sections', {})
    for section, enabled in sections.items():
        status = "✅" if enabled else "❌"
        print(f"  {status} {section.title()}")
    print()
    
    print(f"Section Order: {' → '.join(config.get('section_order', []))}")
    print()
    
    person = config.get('personalization', {})
    print("Personalization:")
    print(f"  Greeting Style: {person.get('greeting_style', 'casual')}")
    print(f"  Show Encouragement: {person.get('show_encouragement', True)}")
    print(f"  Focus Areas: {', '.join(person.get('focus_areas', []))}")
    print()
    
    advanced = config.get('advanced_features', {})
    print("Advanced Features:")
    for feature, enabled in advanced.items():
        status = "✅" if enabled else "❌"
        print(f"  {status} {feature.replace('_', ' ').title()}")


def interactive_customize():
    """Interactive customization mode"""
    prefs = load_current_preferences()
    config = prefs['startup_customization']
    
    print("🔧 MIRA Startup Customization")
    print("=" * 50)
    print()
    
    # Display mode
    print("1. Display Mode")
    modes = ['minimal', 'standard', 'full']
    current_mode = config.get('display_mode', 'standard')
    print(f"   Current: {current_mode}")
    for i, mode in enumerate(modes, 1):
        print(f"   {i}) {mode}")
    
    choice = input("Choose display mode (1-3, or press Enter to keep current): ").strip()
    if choice and choice.isdigit() and 1 <= int(choice) <= 3:
        config['display_mode'] = modes[int(choice) - 1]
        print(f"✓ Display mode set to: {config['display_mode']}")
    print()
    
    # Philosophy section
    current_philosophy = config['enabled_sections'].get('philosophy', False)
    print(f"2. Philosophy Section (currently: {'enabled' if current_philosophy else 'disabled'})")
    choice = input("Enable philosophy section? (y/n, or press Enter to keep current): ").strip().lower()
    if choice == 'y':
        config['enabled_sections']['philosophy'] = True
        # Add to section order if not present
        if 'philosophy' not in config['section_order']:
            config['section_order'].insert(-1, 'philosophy')  # Before quick_reference
        print("✓ Philosophy section enabled")
    elif choice == 'n':
        config['enabled_sections']['philosophy'] = False
        if 'philosophy' in config['section_order']:
            config['section_order'].remove('philosophy')
        print("✓ Philosophy section disabled")
    print()
    
    # Greeting style
    print("3. Greeting Style")
    styles = ['casual', 'formal']
    current_style = config['personalization'].get('greeting_style', 'casual')
    print(f"   Current: {current_style}")
    for i, style in enumerate(styles, 1):
        print(f"   {i}) {style}")
    
    choice = input("Choose greeting style (1-2, or press Enter to keep current): ").strip()
    if choice and choice.isdigit() and 1 <= int(choice) <= 2:
        config['personalization']['greeting_style'] = styles[int(choice) - 1]
        print(f"✓ Greeting style set to: {config['personalization']['greeting_style']}")
    print()
    
    # Focus areas
    current_focus = config['personalization'].get('focus_areas', [])
    print(f"4. Focus Areas (currently: {', '.join(current_focus)})")
    new_focus = input("Enter focus areas (comma-separated, or press Enter to keep current): ").strip()
    if new_focus:
        config['personalization']['focus_areas'] = [area.strip() for area in new_focus.split(',')]
        print(f"✓ Focus areas set to: {', '.join(config['personalization']['focus_areas'])}")
    print()
    
    # Advanced features
    print("5. Advanced Features")
    advanced = config['advanced_features']
    for feature in ['performance_metrics', 'debug_info', 'memory_diagnostics']:
        current = advanced.get(feature, False)
        print(f"   {feature.replace('_', ' ').title()} (currently: {'enabled' if current else 'disabled'})")
        choice = input(f"   Enable {feature.replace('_', ' ')}? (y/n, or press Enter to keep current): ").strip().lower()
        if choice == 'y':
            advanced[feature] = True
            print(f"   ✓ {feature.replace('_', ' ').title()} enabled")
        elif choice == 'n':
            advanced[feature] = False
            print(f"   ✓ {feature.replace('_', ' ').title()} disabled")
    print()
    
    # Save changes
    save_preferences(prefs)
    print()
    print("🎉 Startup customization complete!")
    print("Run MIRA startup to see your personalized experience.")


def main():
    parser = argparse.ArgumentParser(description='Customize MIRA startup experience')
    parser.add_argument('--show', action='store_true', help='Show current settings')
    parser.add_argument('--interactive', action='store_true', help='Interactive customization')
    parser.add_argument('--reset', action='store_true', help='Reset to defaults')
    
    args = parser.parse_args()
    
    if args.show:
        show_current_settings()
    elif args.interactive:
        interactive_customize()
    elif args.reset:
        prefs = create_default_preferences()
        save_preferences(prefs)
        print("✓ Startup preferences reset to defaults")
    else:
        # Default to showing current settings
        show_current_settings()


if __name__ == "__main__":
    main()