import argparse
import sys
import os
import webbrowser
from .tracer import TraceEngine
from .viewer import generate_html

def print_banner():
    """Print a beautiful banner"""
    banner = """
    ╔═══════════════════════════════════════════════════════╗
    ║                                                       ║
    ║     🐍  PyViz Pro - Advanced Python Visualizer  🚀   ║
    ║                                                       ║
    ║     Visualize • Learn • Master Data Structures        ║
    ║                                                       ║
    ╚═══════════════════════════════════════════════════════╝
    """
    print(banner)

def main():
    print_banner()
    
    parser = argparse.ArgumentParser(
        description="🔍 Visualize Python execution flow with beautiful UI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  pyviz script.py              # Visualize a Python script
  pyviz sorting.py             # Great for learning sorting algorithms
  pyviz data_structures.py     # Visualize stacks, queues, trees, etc.

Features:
  ✨ Beautiful dark/light mode interface
  ⚡ Variable speed playback control
  📚 Built-in data structures learning guide
  🎯 Real-time code highlighting
  🔗 Visual pointer connections
  📊 Stack frame and heap visualization

Keyboard Shortcuts:
  ← →     Navigate steps
  Space   Play/Pause
  Home    First step
  End     Last step
        """
    )
    
    parser.add_argument(
        "file", 
        help="The Python script to visualize"
    )
    
    parser.add_argument(
        "-o", "--output",
        default="viz.html",
        help="Output HTML filename (default: viz.html)"
    )
    
    parser.add_argument(
        "--no-browser",
        action="store_true",
        help="Don't automatically open in browser"
    )
    
    args = parser.parse_args()

    # Check if file exists
    if not os.path.exists(args.file):
        print(f"❌ Error: File '{args.file}' not found.")
        sys.exit(1)

    print(f"\n🔍 Analyzing: {args.file}")
    print(f"📊 Tracing execution...")
    
    # 1. Trace the execution
    try:
        tracer = TraceEngine(args.file)
        source_code, trace_data = tracer.run()
    except Exception as e:
        print(f"\n❌ Error during execution: {e}")
        sys.exit(1)

    if not trace_data:
        print("\n⚠️  No execution steps captured. (Is the file empty?)")
        sys.exit(0)

    # 2. Generate HTML
    output_file = args.output
    abspath = os.path.abspath(output_file)
    
    print(f"✅ Captured {len(trace_data)} execution steps")
    print(f"🎨 Generating beautiful visualization...")
    
    try:
        generate_html(source_code, trace_data, output_file)
        print(f"💾 Saved to: {abspath}")
    except Exception as e:
        print(f"\n❌ Error generating visualization: {e}")
        sys.exit(1)

    # 3. Open in Browser
    if not args.no_browser:
        print(f"🌐 Opening in browser...")
        webbrowser.open('file://' + abspath)
        print("\n✨ Visualization ready! Use keyboard shortcuts:")
        print("   ← → to navigate, Space to play/pause")
    else:
        print(f"\n✅ Done! Open this file in your browser:")
        print(f"   {abspath}")
    
    print("\n🎓 Pro Tips:")
    print("   • Toggle dark mode with the button in top-right")
    print("   • Adjust playback speed for complex algorithms")
    print("   • Check the Learning Guide sidebar for DS concepts")
    print("   • Hover over objects to see details")
    print("\n")

if __name__ == "__main__":
    main()