#!/usr/bin/env python3
"""
Launcher for the progress tracker.
Tries to use the executable version first, then falls back to the Python version.
"""
import os
import sys
import subprocess


def main():
    """Main function to run the tracker."""
    # Get the directory of this script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    tracker_dir = os.path.dirname(script_dir)

    # Paths to executable and Python script
    exe_ext = ".exe" if sys.platform == "win32" else ""
    exe_path = os.path.join(tracker_dir, f"track_progress{exe_ext}")
    py_path = os.path.join(tracker_dir, "track_progress.py")

    # Command-line arguments to pass through
    args = sys.argv[1:]

    # Try executable first
    if os.path.exists(exe_path) and (
        sys.platform == "win32" or os.access(exe_path, os.X_OK)
    ):
        print("Running Progress Tracker (executable version)...")
        try:
            return subprocess.call([exe_path] + args)
        except Exception as e:
            print(f"Error running executable: {e}")
            print("Falling back to Python version...")
    else:
        print("Executable not found, trying Python version...")

    # Fall back to Python script
    if os.path.exists(py_path):
        print("Running Progress Tracker (Python version)...")
        try:
            # Add the tracker directory to the Python path
            sys.path.insert(0, tracker_dir)

            # Change to the tracker directory
            os.chdir(tracker_dir)

            # Run the Python script
            return subprocess.call([sys.executable, py_path] + args)
        except Exception as e:
            print(f"Error running Python script: {e}")
            return 1
    else:
        print("Error: Neither executable nor Python script found at:")
        print(f"- {exe_path}")
        print(f"- {py_path}")
        return 1


if __name__ == "__main__":
    exit_code = main()
    if exit_code == 0:
        print("Progress tracking completed successfully!")
    else:
        print(f"Error running progress tracker! (Exit code: {exit_code})")

    # On Windows, pause to see the output
    if sys.platform == "win32":
        input("Press Enter to continue...")

    sys.exit(exit_code)
