#!/usr/bin/env python3
"""
souleyez.ui.tutorial - Interactive guided tutorial for first-time users
"""
import click
import time
from pathlib import Path


def clear_screen():
    """Clear the terminal screen."""
    click.clear()


def wait_for_enter(prompt="Press Enter to continue..."):
    """Wait for user to press Enter."""
    click.pause(prompt)


def show_header(title, subtitle=None):
    """Display a section header."""
    click.echo()
    click.echo(click.style("=" * 60, fg='cyan'))
    click.echo(click.style(f"  {title}", fg='cyan', bold=True))
    if subtitle:
        click.echo(click.style(f"  {subtitle}", fg='white'))
    click.echo(click.style("=" * 60, fg='cyan'))
    click.echo()


def type_text(text, delay=0.02):
    """Print text with a typewriter effect."""
    for char in text:
        click.echo(char, nl=False)
        time.sleep(delay)
    click.echo()


def run_tutorial():
    """Main tutorial flow."""
    clear_screen()

    # Welcome
    show_header("Welcome to SoulEyez!", "Your AI-Powered Penetration Testing Platform")

    click.echo("This tutorial will walk you through:")
    click.echo()
    click.echo("  1. Creating your first engagement")
    click.echo("  2. Running a basic reconnaissance scan")
    click.echo("  3. Viewing and understanding results")
    click.echo("  4. Using the real-time dashboard")
    click.echo("  5. Next steps and tips")
    click.echo()

    wait_for_enter()

    # Step 1: What is an Engagement?
    clear_screen()
    show_header("Step 1: Understanding Engagements")

    click.echo("An " + click.style("engagement", fg='cyan', bold=True) + " is a container for all your pentest data.")
    click.echo()
    click.echo("Think of it like a project folder that keeps everything organized:")
    click.echo()
    click.echo("  • " + click.style("Hosts", fg='green') + " - Target systems you discover")
    click.echo("  • " + click.style("Services", fg='green') + " - Open ports and running software")
    click.echo("  • " + click.style("Findings", fg='green') + " - Vulnerabilities you find")
    click.echo("  • " + click.style("Credentials", fg='green') + " - Usernames, passwords, keys")
    click.echo("  • " + click.style("Evidence", fg='green') + " - Screenshots, logs, artifacts")
    click.echo()
    click.echo("Each engagement is " + click.style("isolated", fg='yellow') + " - data from one")
    click.echo("pentest never mixes with another.")
    click.echo()

    wait_for_enter()

    # Step 2: Create an Engagement
    clear_screen()
    show_header("Step 2: Create Your First Engagement")

    click.echo("Let's create a test engagement to practice with.")
    click.echo()
    click.echo("We'll use a " + click.style("safe, legal target", fg='green', bold=True) + ":")
    click.echo()
    click.echo("  " + click.style("http://testhtml5.vulnweb.com", fg='cyan'))
    click.echo("  (Acunetix's intentionally vulnerable test site)")
    click.echo()

    if not click.confirm("Create a practice engagement?", default=True):
        click.echo()
        click.echo("No problem! You can run 'souleyez tutorial' anytime.")
        return

    click.echo()

    # Create the engagement
    try:
        from souleyez.storage.engagements import EngagementManager

        em = EngagementManager()
        engagement = em.create(
            name="Tutorial Engagement",
            scope="testhtml5.vulnweb.com",
            notes="Created by SoulEyez tutorial. Safe to delete after learning."
        )
        engagement_id = engagement['id']

        click.echo(click.style("✓ Created engagement: Tutorial Engagement", fg='green'))
        click.echo(f"  ID: {engagement_id}")
        click.echo()

    except Exception as e:
        click.echo(click.style(f"✗ Error creating engagement: {e}", fg='red'))
        click.echo("Please check 'souleyez doctor' for issues.")
        return

    wait_for_enter()

    # Step 3: Run a Scan
    clear_screen()
    show_header("Step 3: Running Your First Scan")

    click.echo("Now let's run a basic reconnaissance scan!")
    click.echo()
    click.echo("SoulEyez has " + click.style("40+ integrated tools", fg='cyan') + ", but for")
    click.echo("web targets, we typically start with:")
    click.echo()
    click.echo("  1. " + click.style("nmap", fg='green') + " - Port scanning")
    click.echo("  2. " + click.style("gobuster", fg='green') + " - Directory discovery")
    click.echo("  3. " + click.style("nikto", fg='green') + " - Web vulnerability scanning")
    click.echo()
    click.echo("SoulEyez's " + click.style("tool chaining", fg='yellow', bold=True) + " feature")
    click.echo("automatically queues follow-up scans based on findings!")
    click.echo()
    click.echo("For example:")
    click.echo("  • Find HTTP on port 80 → auto-queue nikto, gobuster")
    click.echo("  • Find MySQL on port 3306 → auto-queue hydra with mysql")
    click.echo()

    if click.confirm("Queue an nmap scan of the target?", default=True):
        try:
            from souleyez.engine.background import enqueue_job

            job = enqueue_job(
                engagement_id=engagement_id,
                plugin_name='nmap',
                target='testhtml5.vulnweb.com',
                args=['-sV', '-sC', '--top-ports', '100'],
                label='tutorial'
            )

            click.echo()
            click.echo(click.style(f"✓ Queued nmap scan (Job #{job['id']})", fg='green'))
            click.echo()
            click.echo("The scan is now running in the background.")
            click.echo("You can monitor it in the dashboard.")
            click.echo()

        except Exception as e:
            click.echo(click.style(f"Could not queue scan: {e}", fg='yellow'))
            click.echo("That's okay - you can queue scans manually later.")
            click.echo()

    wait_for_enter()

    # Step 4: Dashboard Overview
    clear_screen()
    show_header("Step 4: The Real-Time Dashboard")

    click.echo("The " + click.style("dashboard", fg='cyan', bold=True) + " is your mission control.")
    click.echo()
    click.echo("Launch it with: " + click.style("souleyez dashboard", fg='green'))
    click.echo()
    click.echo("It shows you:")
    click.echo()
    click.echo("  " + click.style("📊 Stats", fg='cyan') + " - Hosts, services, findings count")
    click.echo("  " + click.style("⚡ Active Jobs", fg='cyan') + " - Currently running scans")
    click.echo("  " + click.style("📡 Live Log", fg='cyan') + " - Real-time output from tools")
    click.echo("  " + click.style("🎯 Intelligence", fg='cyan') + " - AI-powered insights")
    click.echo("  " + click.style("💡 Recommendations", fg='cyan') + " - What to do next")
    click.echo()
    click.echo("Keyboard shortcuts:")
    click.echo("  " + click.style("[j]", fg='yellow') + " Jobs view")
    click.echo("  " + click.style("[h]", fg='yellow') + " Hosts view")
    click.echo("  " + click.style("[f]", fg='yellow') + " Findings view")
    click.echo("  " + click.style("[?]", fg='yellow') + " Help")
    click.echo("  " + click.style("[q]", fg='yellow') + " Quit")
    click.echo()

    wait_for_enter()

    # Step 5: Interactive Mode
    clear_screen()
    show_header("Step 5: Interactive Mode")

    click.echo("For more control, use " + click.style("interactive mode", fg='cyan', bold=True) + ":")
    click.echo()
    click.echo("  " + click.style("souleyez interactive", fg='green'))
    click.echo()
    click.echo("This gives you a menu-driven interface to:")
    click.echo()
    click.echo("  • Manage engagements")
    click.echo("  • Select and run specific tools")
    click.echo("  • View detailed results")
    click.echo("  • Configure settings")
    click.echo("  • Access Metasploit integration")
    click.echo("  • Generate reports")
    click.echo()

    wait_for_enter()

    # Step 6: Demo Target Options
    clear_screen()
    show_header("Practice Targets")

    click.echo("For learning, use these " + click.style("intentionally vulnerable", fg='green') + " sites:")
    click.echo()
    click.echo(click.style("Online (no setup needed):", bold=True))
    click.echo("  • http://testhtml5.vulnweb.com (Acunetix)")
    click.echo("  • http://testasp.vulnweb.com (Acunetix)")
    click.echo("  • http://testphp.vulnweb.com (Acunetix)")
    click.echo("  • https://demo.owasp-juice.shop (OWASP)")
    click.echo()
    click.echo(click.style("Local (more realistic):", bold=True))
    click.echo("  • DVWA: docker run -d -p 80:80 vulnerables/web-dvwa")
    click.echo("  • Juice Shop: docker run -d -p 3000:3000 bkimminich/juice-shop")
    click.echo("  • Metasploitable: Download VM from Rapid7")
    click.echo()
    click.echo(click.style("⚠️  NEVER scan systems without permission!", fg='red', bold=True))
    click.echo()

    wait_for_enter()

    # Summary
    clear_screen()
    show_header("Tutorial Complete!")

    click.echo(click.style("You're ready to start pentesting with SoulEyez!", fg='green', bold=True))
    click.echo()
    click.echo("Quick reference:")
    click.echo()
    click.echo("  " + click.style("souleyez interactive", fg='cyan') + "  - Menu-driven interface")
    click.echo("  " + click.style("souleyez dashboard", fg='cyan') + "    - Real-time monitoring")
    click.echo("  " + click.style("souleyez setup", fg='cyan') + "        - Install pentest tools")
    click.echo("  " + click.style("souleyez doctor", fg='cyan') + "       - Diagnose issues")
    click.echo("  " + click.style("souleyez run <tool>", fg='cyan') + "   - Run a specific tool")
    click.echo()
    click.echo("Your tutorial engagement is still active.")
    click.echo(f"Check results: souleyez interactive → Select engagement")
    click.echo()
    click.echo("Need help?")
    click.echo("  • In-app: Press " + click.style("[?]", fg='yellow') + " for help")
    click.echo("  • Docs: https://github.com/cyber-soul-security/SoulEyez")
    click.echo("  • Issues: https://github.com/cyber-soul-security/SoulEyez/issues")
    click.echo()
    click.echo(click.style("Happy hacking! 🎯", fg='cyan', bold=True))
    click.echo()


if __name__ == '__main__':
    run_tutorial()
