#!/usr/bin/env python3
"""
souleyez.ui.setup_wizard - First-run setup wizard for new users
"""
import os
import time
import click
import getpass
import shutil
from pathlib import Path
from souleyez.ui.design_system import DesignSystem


# Wizard state file
WIZARD_STATE_FILE = Path.home() / '.souleyez' / '.wizard_completed'


def is_wizard_completed() -> bool:
    """Check if wizard has been completed."""
    return WIZARD_STATE_FILE.exists()


def mark_wizard_completed():
    """Mark wizard as completed."""
    WIZARD_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    WIZARD_STATE_FILE.touch()



def _show_wizard_banner():
    """Display the SoulEyez ASCII banner for wizard steps."""
    banner = """
   ███████╗ ██████╗ ██╗   ██╗██╗         ██╗  ██╗ █████╗  ██████╗██╗  ██╗███████╗██████╗ ███████╗
   ██╔════╝██╔═══██╗██║   ██║██║         ██║  ██║██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗██╔════╝
   ███████╗██║   ██║██║   ██║██║         ███████║███████║██║     █████╔╝ █████╗  ██████╔╝███████╗
   ╚════██║██║   ██║██║   ██║██║         ██╔══██║██╔══██║██║     ██╔═██╗ ██╔══╝  ██╔══██╗╚════██║
   ███████║╚██████╔╝╚██████╔╝███████╗    ██║  ██║██║  ██║╚██████╗██║  ██╗███████╗██║  ██║███████║
   ╚══════╝ ╚═════╝  ╚═════╝ ╚══════╝    ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚══════╝
"""
    click.echo(click.style(banner, fg='bright_cyan', bold=True))
    click.echo(click.style("  Created by CyberSoul SecurITy", fg='yellow'))
    click.echo()


def run_setup_wizard() -> bool:
    """
    Run the setup wizard for new users.
    
    Returns:
        bool: True if wizard completed, False if skipped/cancelled
    """
    try:
        # Check if user has Pro tier
        from souleyez.auth import get_current_user, Tier
        user = get_current_user()
        is_pro = user and user.tier == Tier.PRO
        
        # Step 1: Welcome
        if not _wizard_welcome(is_pro):
            mark_wizard_completed()  # Mark as completed even if skipped
            return False
        
        # Step 2: Encryption Setup
        encryption_enabled = _wizard_encryption_setup()
        
        # Step 3: Create First Engagement
        engagement_info = _wizard_create_engagement()
        if not engagement_info:
            return False
        
        # Step 4: Tool Check
        tool_status = _wizard_tool_check()

        # Step 5: AI Setup (Optional - Ollama)
        ai_enabled = _wizard_ai_setup()

        # Step 6: Automation Preferences (Pro only)
        if is_pro:
            automation_prefs = _wizard_automation_prefs()
        else:
            automation_prefs = {'enabled': False, 'mode': None}
        
        # Step 7: Deliverable Templates (Pro only)
        if is_pro:
            templates = _wizard_deliverables(engagement_info.get('type'))
        else:
            templates = []

        # Step 8: Summary (adjust step numbers for FREE)
        _wizard_summary(
            encryption_enabled,
            engagement_info,
            tool_status,
            ai_enabled,
            automation_prefs,
            templates,
            is_pro
        )
        
        mark_wizard_completed()
        return True
        
    except (KeyboardInterrupt, click.Abort):
        click.echo(click.style("\n\n  Setup wizard cancelled.", fg='yellow'))
        mark_wizard_completed()  # Don't show wizard again
        click.pause()
        return False


def _wizard_welcome(is_pro: bool = False) -> bool:
    """Show welcome screen with ASCII banner."""
    DesignSystem.clear_screen()
    width = DesignSystem.get_terminal_width()
    
    # Header
    click.echo("\n┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" WELCOME TO SOULEYEZ - SETUP WIZARD ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    
    # ASCII Art Banner
    banner = """
   ███████╗ ██████╗ ██╗   ██╗██╗         ██╗  ██╗ █████╗  ██████╗██╗  ██╗███████╗██████╗ ███████╗
   ██╔════╝██╔═══██╗██║   ██║██║         ██║  ██║██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗██╔════╝
   ███████╗██║   ██║██║   ██║██║         ███████║███████║██║     █████╔╝ █████╗  ██████╔╝███████╗
   ╚════██║██║   ██║██║   ██║██║         ██╔══██║██╔══██║██║     ██╔═██╗ ██╔══╝  ██╔══██╗╚════██║
   ███████║╚██████╔╝╚██████╔╝███████╗    ██║  ██║██║  ██║╚██████╗██║  ██╗███████╗██║  ██║███████║
   ╚══════╝ ╚═════╝  ╚═════╝ ╚══════╝    ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚══════╝
"""
    click.echo(click.style(banner, fg='bright_cyan', bold=True))
    
    # Tagline and description
    click.echo(click.style("  Created by CyberSoul SecurITy", fg='yellow'))
    click.echo()
    click.echo("  SoulEyez brings your hacking tools together so you can spend less time switching windows")
    click.echo("  and more time breaking things (ethically, of course). Launch scans with Nmap, Metasploit,")
    click.echo("  Gobuster, theHarvester, and many more. Manage engagements, review findings, generate reports,")
    click.echo("  and let AI recommend your next moves — all in one place.")
    click.echo()
    click.echo(click.style("  SETUP WIZARD", bold=True, fg='cyan'))
    click.echo("  ─────────────")
    click.echo()
    click.echo("  This wizard will help you get started:")
    click.echo("  " + click.style("✓", fg='green') + " Set up encryption for credentials")
    click.echo("  " + click.style("✓", fg='green') + " Create your first engagement")
    click.echo("  " + click.style("✓", fg='green') + " Check installed tools")
    click.echo("  " + click.style("✓", fg='green') + " Set up AI features (optional)")

    # Only show Pro steps if user has Pro tier
    if is_pro:
        click.echo("  " + click.style("✓", fg='green') + " Configure automation preferences")
        click.echo("  " + click.style("✓", fg='green') + " Select report templates")

    click.echo()
    click.pause("  Press ENTER to continue...")

    return True


def _wizard_encryption_setup() -> bool:
    """Set up encryption for credentials."""
    from souleyez.storage.crypto import CryptoManager

    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 2: ENCRYPTION SETUP ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    
    crypto = CryptoManager()
    
    if crypto.is_encryption_enabled():
        click.echo("  " + click.style("✓ Encryption already configured", fg='green'))
        click.echo()
        click.pause("  Press any key to continue...")
        return True
    
    click.echo("  SoulEyez encrypts all credentials (passwords, API keys, tokens)")
    click.echo("  with a master password. This is " + click.style("required", fg='green', bold=True) + " for security.")
    click.echo()
    click.echo("  " + click.style("[y]", fg='green') + " Enable encryption (recommended)")
    click.echo("  " + click.style("[n]", fg='bright_black') + " Skip encryption")
    click.echo()

    choice = click.prompt("  Enable encryption? [y/n]", default='y').strip().lower()

    if choice in ('n', 's', 'no', 'skip'):
        click.echo()
        time.sleep(0.5)
        click.echo("  " + click.style("SIKE! 😏", fg='magenta', bold=True))
        time.sleep(0.8)
        click.echo()
        click.echo("  " + click.style("Security is not optional.", fg='cyan', bold=True))
        click.echo("  " + "We're a security company. Encryption is mandatory.")
        click.echo()
        time.sleep(1)
        click.echo("  " + click.style("Let's set up your vault password...", fg='green'))
        click.pause("  Press any key to continue...")

    click.echo()
    click.echo("  " + click.style("Password Requirements:", bold=True))
    click.echo("    • At least 12 characters")
    click.echo("    • Mix of uppercase and lowercase")
    click.echo("    • At least one number")
    click.echo("    • At least one special character (!@#$%^&*)")
    click.echo()
    click.echo("  " + click.style("⚠️  If you lose this password, encrypted credentials cannot be recovered!", 
                                  fg='yellow', bold=True))
    click.echo()
    
    import re
    password_set = False
    while not password_set:
        password = getpass.getpass("  Enter master password: ")
        
        # Validate password strength
        if len(password) < 12:
            click.echo(click.style("  ✗ Password must be at least 12 characters.", fg='red'))
            continue
        
        if not re.search(r'[a-z]', password):
            click.echo(click.style("  ✗ Password must contain at least one lowercase letter.", fg='red'))
            continue
        
        if not re.search(r'[A-Z]', password):
            click.echo(click.style("  ✗ Password must contain at least one uppercase letter.", fg='red'))
            continue
        
        if not re.search(r'\d', password):
            click.echo(click.style("  ✗ Password must contain at least one number.", fg='red'))
            continue
        
        if not re.search(r'[!@#$%^&*()_+\-=\[\]{};:\'",.<>?/\\|`~]', password):
            click.echo(click.style("  ✗ Password must contain at least one special character.", fg='red'))
            continue
        
        password_confirm = getpass.getpass("  Confirm master password: ")
        if password != password_confirm:
            click.echo(click.style("  ✗ Passwords don't match!", fg='red'))
            continue
        
        password_set = True
    
    click.echo()
    click.echo("  Enabling encryption...")
    
    try:
        if crypto.enable_encryption(password):
            click.echo("  " + click.style("✓ Encryption enabled!", fg='green'))
        else:
            click.echo("  " + click.style("✗ Failed to enable encryption!", fg='red'))
            click.pause("  Press any key to continue...")
            return False
    except Exception as e:
        click.echo("  " + click.style(f"✗ Error: {e}", fg='red'))
        click.pause("  Press any key to continue...")
        return False
    
    click.pause("  Press any key to continue...")
    return True


def _wizard_create_engagement() -> dict:
    """Create first engagement."""
    from souleyez.storage.engagements import EngagementManager

    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 3: CREATE YOUR ENGAGEMENT ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    click.echo("  An engagement organizes all your work for a specific target.")
    click.echo("  Give it a descriptive name like 'Acme Corp Pentest' or 'HackTheBox Lab'.")
    click.echo()

    name = click.prompt("  Engagement Name").strip()

    # Require a name
    while not name:
        click.echo(click.style("  ✗ Name is required!", fg='red'))
        name = click.prompt("  Engagement Name").strip()

    click.echo()
    click.echo("  " + click.style("Engagement Type:", bold=True))
    click.echo("    [1] Penetration Test  - Full-scope security assessment")
    click.echo("    [2] Bug Bounty        - Vulnerability hunting with defined scope")
    click.echo("    [3] CTF / Lab         - Practice environment, aggressive scanning OK")
    click.echo("    [4] Red Team          - Adversary simulation, stealth preferred")
    click.echo("    [5] Custom            - Define your own")
    click.echo()
    click.echo("  " + click.style("NOTE:", fg='yellow') + " Type affects default automation and scan aggressiveness")
    click.echo()
    
    type_choice = click.prompt("  Select option", type=click.IntRange(1, 5), default=1, show_default=False)
    
    engagement_types = {
        1: 'penetration_test',
        2: 'bug_bounty',
        3: 'ctf',
        4: 'red_team',
        5: 'custom'
    }
    
    engagement_type = engagement_types[type_choice]
    
    # Create engagement and set it as active
    em = EngagementManager()
    engagement_id = em.create_engagement(name, f"Created via Setup Wizard - Type: {engagement_type}")
    em.set_current(name)  # Set as active so user drops into this engagement

    click.echo()
    click.echo("  " + click.style(f"✓ Engagement '{name}' created and set as active!", fg='green'))
    click.pause("  Press any key to continue...")
    
    return {
        'id': engagement_id,
        'name': name,
        'type': engagement_type
    }


def _wizard_tool_check() -> dict:
    """Check installed tools using the centralized tool_checker module."""
    from souleyez.utils.tool_checker import check_tool, EXTERNAL_TOOLS

    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 4: TOOL AVAILABILITY ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    click.echo("  Checking installed tools...")
    click.echo()

    # Core tools to check in the wizard (subset of full tool list)
    # Maps display name -> tool_checker key (category, tool_name)
    wizard_tools = {
        'nmap': ('reconnaissance', 'nmap'),
        'gobuster': ('web_scanning', 'gobuster'),
        'sqlmap': ('exploitation', 'sqlmap'),
        'nuclei': ('web_scanning', 'nuclei'),
        'hydra': ('credential_attacks', 'hydra'),
        'theHarvester': ('reconnaissance', 'theharvester'),
        'wpscan': ('web_scanning', 'wpscan'),
        'netexec': ('windows_ad', 'netexec'),
        'enum4linux': ('windows_ad', 'enum4linux'),
        'dnsrecon': ('reconnaissance', 'dnsrecon'),
        'whois': ('reconnaissance', 'whois'),
    }

    found = 0
    total = len(wizard_tools)
    tool_status = {}

    for display_name, (category, tool_key) in wizard_tools.items():
        tool_info = EXTERNAL_TOOLS[category][tool_key]
        command = tool_info['command']
        alt_commands = tool_info.get('alt_commands')

        if check_tool(command, alt_commands):
            # Find the actual path for display
            path = shutil.which(command)
            if not path and alt_commands:
                for alt in alt_commands:
                    path = shutil.which(alt)
                    if path:
                        break
            click.echo(f"  {click.style('✓', fg='green')} {display_name:<15} Found: {path}")
            tool_status[display_name] = {'found': True, 'path': path}
            found += 1
        else:
            click.echo(f"  {click.style('✗', fg='red')} {display_name:<15} NOT FOUND")
            tool_status[display_name] = {'found': False, 'path': None}

    click.echo()
    click.echo(f"  Found {found}/{total} recommended tools")
    click.echo()

    if found < total:
        click.echo("  " + click.style("TIP:", fg='yellow', bold=True) +
                  " You can install missing tools later. SoulEyez will work")
        click.echo("  with the tools you have available.")

    click.echo()
    click.pause("  Press any key to continue...")

    return {'found': found, 'total': total, 'tools': tool_status}


def _wizard_ai_setup() -> bool:
    """Set up AI features with Ollama."""
    import subprocess
    import time

    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 5: AI FEATURES (OPTIONAL) ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    click.echo("  SoulEyez can use AI to suggest scanning strategies and")
    click.echo("  prioritize targets. This requires " + click.style("Ollama", bold=True) + " (local AI runtime).")
    click.echo()

    # Check if Ollama is installed
    ollama_path = shutil.which('ollama')

    if ollama_path:
        click.echo("  " + click.style("✓", fg='green') + " Ollama is installed")

        # Check if it's running
        try:
            result = subprocess.run(
                ['curl', '-s', 'http://localhost:11434/api/tags'],
                capture_output=True, timeout=5
            )
            if result.returncode == 0:
                click.echo("  " + click.style("✓", fg='green') + " Ollama is running")

                # Check for models
                import json
                try:
                    data = json.loads(result.stdout)
                    models = data.get('models', [])
                    if models:
                        click.echo(f"  " + click.style("✓", fg='green') + f" {len(models)} model(s) available")
                        click.echo()
                        click.echo("  " + click.style("AI features are ready!", fg='green', bold=True))
                        click.echo()
                        click.pause("  Press any key to continue...")
                        return True
                    else:
                        click.echo("  " + click.style("!", fg='yellow') + " No models installed")
                except:
                    pass

                # Offer to pull a model
                click.echo()
                click.echo("  Would you like to download a model now?")
                click.echo("  Recommended: " + click.style("llama3.1:8b", fg='cyan') + " (~4.7GB)")
                click.echo()

                try:
                    response = input("  Download model? (y/n): ").strip().lower()
                    if response == 'y':
                        return _pull_ollama_model()
                except (KeyboardInterrupt, EOFError):
                    click.echo("\n  Skipped.")

                click.pause("  Press any key to continue...")
                return False
            else:
                # Ollama installed but not running
                click.echo("  " + click.style("!", fg='yellow') + " Ollama is not running")
                return _start_ollama_and_setup()

        except subprocess.TimeoutExpired:
            click.echo("  " + click.style("!", fg='yellow') + " Ollama is not responding")
            return _start_ollama_and_setup()
        except FileNotFoundError:
            # curl not found, try another method
            pass

    else:
        # Ollama not installed - offer to install
        click.echo("  " + click.style("!", fg='yellow') + " Ollama is not installed")
        click.echo()
        click.echo("  Would you like to install Ollama now?")
        click.echo("  This will download and install the Ollama runtime (~100MB).")
        click.echo()

        try:
            response = input("  Install Ollama? (y/n): ").strip().lower()
            if response == 'y':
                return _install_ollama()
        except (KeyboardInterrupt, EOFError):
            click.echo("\n  Skipped.")

    click.echo()
    click.echo("  " + click.style("Skipping AI setup.", fg='bright_black') + " You can enable it later in Settings.")
    click.pause("  Press any key to continue...")
    return False


def _install_ollama() -> bool:
    """Install Ollama using the official install script."""
    import subprocess

    click.echo()
    click.echo("  Installing Ollama...")
    click.echo("  " + click.style("(This may take a minute)", fg='bright_black'))
    click.echo()

    try:
        # Run the official Ollama install script - let it output directly to terminal
        result = subprocess.run(
            ['bash', '-c', 'curl -fsSL https://ollama.ai/install.sh | sh'],
            check=False
        )

        if result.returncode == 0:
            click.echo()
            click.echo("  " + click.style("✓ Ollama installed successfully!", fg='green'))

            # Start Ollama and set up model
            return _start_ollama_and_setup()
        else:
            click.echo()
            click.echo("  " + click.style("✗ Installation failed", fg='red'))
            click.echo("  You can install manually from https://ollama.ai")
            click.pause("  Press any key to continue...")
            return False

    except Exception as e:
        click.echo()
        click.echo(click.style(f"  ✗ Error: {e}", fg='red'))
        click.echo("  You can install manually from https://ollama.ai")
        click.pause("  Press any key to continue...")
        return False


def _start_ollama_and_setup() -> bool:
    """Start Ollama service and optionally pull a model."""
    import subprocess
    import time

    click.echo()
    click.echo("  Starting Ollama service...")

    try:
        # Start ollama serve in background
        subprocess.Popen(
            ['ollama', 'serve'],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            start_new_session=True
        )

        # Wait for it to start
        click.echo("  Waiting for Ollama to start...")
        time.sleep(3)

        # Verify it's running
        result = subprocess.run(
            ['curl', '-s', 'http://localhost:11434/api/tags'],
            capture_output=True, timeout=5
        )

        if result.returncode == 0:
            click.echo("  " + click.style("✓ Ollama started!", fg='green'))

            # Offer to pull model
            click.echo()
            click.echo("  Would you like to download a model now?")
            click.echo("  Recommended: " + click.style("llama3.1:8b", fg='cyan') + " (~4.7GB)")
            click.echo()

            try:
                response = input("  Download model? (y/n): ").strip().lower()
                if response == 'y':
                    return _pull_ollama_model()
            except (KeyboardInterrupt, EOFError):
                click.echo("\n  Skipped.")

            click.pause("  Press any key to continue...")
            return True
        else:
            click.echo("  " + click.style("✗ Failed to start Ollama", fg='red'))
            click.pause("  Press any key to continue...")
            return False

    except Exception as e:
        click.echo(click.style(f"  ✗ Error: {e}", fg='red'))
        click.pause("  Press any key to continue...")
        return False


def _pull_ollama_model() -> bool:
    """Pull the recommended Ollama model."""
    import subprocess

    model = "llama3.1:8b"

    click.echo()
    click.echo(f"  Downloading {model}...")
    click.echo("  " + click.style("(This may take several minutes depending on your connection)", fg='bright_black'))
    click.echo()

    try:
        # Run ollama pull and let it output directly to terminal for proper progress bar
        result = subprocess.run(
            ['ollama', 'pull', model],
            check=False
        )

        if result.returncode == 0:
            click.echo()
            click.echo("  " + click.style(f"✓ Model {model} ready!", fg='green'))
            click.echo()
            click.echo("  " + click.style("AI features are now enabled!", fg='green', bold=True))
            click.pause("  Press any key to continue...")
            return True
        else:
            click.echo()
            click.echo("  " + click.style("✗ Failed to download model", fg='red'))
            click.echo("  You can try later with: ollama pull " + model)
            click.pause("  Press any key to continue...")
            return False

    except Exception as e:
        click.echo(click.style(f"  ✗ Error: {e}", fg='red'))
        click.pause("  Press any key to continue...")
        return False


def _wizard_automation_prefs() -> dict:
    """Configure automation preferences."""
    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 6: AUTOMATION PREFERENCES ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    click.echo("  SoulEyez can automatically chain tools based on discoveries.")
    click.echo("  Example: Finding port 80 → auto-run gobuster + nuclei")
    click.echo()
    click.echo("  " + click.style("Chain Mode:", bold=True))
    click.echo("    [1] AUTO     - Execute chains immediately (recommended for labs)")
    click.echo("    [2] APPROVAL - Queue chains for your approval first")
    click.echo("    [3] DISABLED - No automatic chaining")
    click.echo()

    mode_choice = click.prompt("  Select option", type=click.IntRange(1, 3), default=1)

    if mode_choice == 3:
        click.echo()
        click.echo(f"  {click.style('✓', fg='green')} Auto-chaining disabled")
        click.pause("  Press any key to continue...")
        return {'enabled': False, 'mode': None}

    mode = 'auto' if mode_choice == 1 else 'approval'

    click.echo()
    click.echo(f"  {click.style('✓', fg='green')} Auto-chaining enabled in {mode.upper()} mode")
    click.pause("  Press any key to continue...")

    return {'enabled': True, 'mode': mode}


def _wizard_deliverables(engagement_type: str) -> list:
    """Select deliverable templates."""
    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60
    
    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(" STEP 7: REPORT TEMPLATES ".center(width - 2), bold=True, fg='cyan') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()
    click.echo("  Pre-select report templates that will be available for export.")
    click.echo("  You can change these later in Reports & Export menu.")
    click.echo()
    click.echo("  " + click.style("NOTE:", fg='yellow') + " Templates help generate professional reports from your findings")
    click.echo()
    
    # Default templates based on engagement type
    type_templates = {
        'penetration_test': ['Executive Summary', 'Technical Findings Report', 'Vulnerability Details'],
        'bug_bounty': ['Vulnerability Details', 'Proof of Concept'],
        'ctf': ['Technical Findings Report', 'Attack Narrative'],
        'red_team': ['Attack Narrative', 'Remediation Roadmap'],
        'custom': ['Technical Findings Report']
    }
    
    recommended = type_templates.get(engagement_type, ['Technical Findings Report'])
    
    click.echo(f"  Recommended for {engagement_type.replace('_', ' ').title()}:")
    for template in recommended:
        click.echo(f"    {click.style('✓', fg='green')} {template}")

    click.echo()
    click.echo(f"  {click.style('✓', fg='green')} Templates configured!")
    click.pause("  Press any key to continue...")

    return recommended


def _wizard_summary(encryption_enabled, engagement_info, tool_status, ai_enabled, automation_prefs, templates, is_pro=False):
    """Show wizard summary."""
    DesignSystem.clear_screen()
    _show_wizard_banner()
    width = 60

    # Adjust step number based on tier
    step_num = "8" if is_pro else "6"
    click.echo("┌" + "─" * (width - 2) + "┐")
    click.echo("│" + click.style(f" STEP {step_num}: SETUP COMPLETE! ".center(width - 2), bold=True, fg='green') + "│")
    click.echo("└" + "─" * (width - 2) + "┘")
    click.echo()

    # Summary
    enc_status = click.style("Enabled", fg='green') if encryption_enabled else click.style("Disabled", fg='yellow')
    click.echo(f"  {click.style('✓', fg='green')} Encryption: {enc_status}")

    eng_name = engagement_info['name']
    eng_type = engagement_info['type'].replace('_', ' ').title()
    click.echo(f"  {click.style('✓', fg='green')} Engagement: \"{eng_name}\" ({eng_type})")

    tools_found = tool_status['found']
    tools_total = tool_status['total']
    click.echo(f"  {click.style('✓', fg='green')} Tools: {tools_found}/{tools_total} available")

    # AI status
    if ai_enabled:
        click.echo(f"  {click.style('✓', fg='green')} AI Features: Enabled (Ollama)")
    else:
        click.echo(f"  {click.style('○', fg='bright_black')} AI Features: Not configured")
    
    # Show tier status
    if is_pro:
        click.echo(f"  {click.style('💎', fg='magenta')} License: PRO")
        if automation_prefs['enabled']:
            auto_mode = automation_prefs['mode'].upper()
            click.echo(f"  {click.style('✓', fg='green')} Auto-Chain: ON ({auto_mode} mode)")
        else:
            click.echo(f"  {click.style('✓', fg='green')} Auto-Chain: OFF")
        
        if templates:
            click.echo(f"  {click.style('✓', fg='green')} Templates: {len(templates)} selected")
    else:
        click.echo(f"  {click.style('○', fg='bright_black')} License: FREE")
        click.echo()
        click.echo(click.style("  Upgrade to Pro for:", fg='yellow'))
        click.echo("    • AI Execute - Autonomous exploitation")
        click.echo("    • Automation - Smart tool chaining")
        click.echo("    • MSF Integration - Advanced attack chains")
        click.echo("    • Reports - Professional deliverables")
        click.echo(f"    {click.style('→ cybersoulsecurity.com/upgrade', fg='cyan')}")
    
    click.echo()
    click.echo("  " + click.style("You're ready to start!", bold=True, fg='cyan'))
    click.echo()

    # Prompt for interactive tutorial
    click.echo("  ┌" + "─" * 56 + "┐")
    click.echo("  │" + click.style(" Would you like to run the interactive tutorial?", fg='cyan').center(65) + "│")
    click.echo("  │" + " Recommended for new users - takes about 5 minutes".center(56) + "│")
    click.echo("  └" + "─" * 56 + "┘")
    click.echo()
    click.echo("  " + click.style("[Y]", fg='green', bold=True) + " Yes, show me around")
    click.echo("  " + click.style("[n]", fg='bright_black') + " No, go to main menu")
    click.echo()

    choice = click.prompt("  Run tutorial?", default='y', show_default=False).strip().lower()

    if choice in ('y', 'yes', ''):
        from souleyez.ui.tutorial import run_tutorial
        run_tutorial()
    else:
        click.echo()
        click.echo("  " + click.style("No problem!", fg='cyan') + " You can run the tutorial anytime from:")
        click.echo("  " + click.style("Settings & Security → [t] Tutorial", fg='yellow'))
        click.echo()
        click.pause("  Press any key to continue to main menu...")
