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

def main():
    parser = argparse.ArgumentParser(description="Visualize Python execution flow.")
    parser.add_argument("file", help="The python script to visualize")
    args = parser.parse_args()

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

    print(f"Analyzing {args.file}...")
    
    # 1. Trace the execution
    tracer = TraceEngine(args.file)
    source_code, trace_data = tracer.run()

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

    # 2. Generate HTML
    output_file = "viz.html"
    abspath = os.path.abspath(output_file)
    
    print(f"Generating visualization with {len(trace_data)} steps...")
    generate_html(source_code, trace_data, output_file)

    # 3. Open in Browser
    print(f"Opening {abspath} in browser...")
    webbrowser.open('file://' + abspath)

if __name__ == "__main__":
    main()