#!/usr/bin/env python3
"""
Build the progress tracker with Nuitka.
"""
import os
import sys
import shutil
import subprocess
import argparse


def main():
    """Build the progress tracker with Nuitka."""
    parser = argparse.ArgumentParser(
        description="Build the progress tracker with Nuitka"
    )
    parser.add_argument(
        "--output-dir", default="dist", help="Output directory for the build"
    )
    parser.add_argument(
        "--verbose", "-v", action="store_true", help="Enable verbose output"
    )
    parser.add_argument(
        "--move-exe",
        action="store_true",
        help="Move executable to parent directory after build",
    )
    args = parser.parse_args()

    verbose = args.verbose
    output_dir = args.output_dir
    move_exe = args.move_exe

    # Get the directory of this script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    parent_dir = os.path.dirname(script_dir)  # scripts/track_progress

    # Check if Nuitka is installed
    try:
        subprocess.check_call(
            [sys.executable, "-m", "pip", "show", "nuitka"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
    except subprocess.CalledProcessError:
        print("Nuitka is not installed. Installing...")
        try:
            subprocess.check_call(
                [sys.executable, "-m", "pip", "install", "nuitka"]
            )
        except subprocess.CalledProcessError:
            print(
                "Failed to install Nuitka. Please install it manually with 'pip install nuitka'."
            )
            return 1

    # Create output directory
    dist_dir = os.path.join(parent_dir, output_dir)
    os.makedirs(dist_dir, exist_ok=True)

    # Path to the main script
    main_script = os.path.join(parent_dir, "track_progress.py")

    if not os.path.exists(main_script):
        print(f"Error: Main script not found at {main_script}")
        return 1

    # Build command
    cmd = [
        sys.executable,
        "-m",
        "nuitka",
        "--standalone",
        "--onefile",
        "--lto=auto",
        "--jobs=4",
        "--include-package=track_progress",
        "--include-data-dir="
        + os.path.join(parent_dir, "templates")
        + "=templates",
        "--output-dir=" + dist_dir,
        main_script,
    ]

    # Try to enable UPX if available
    try:
        subprocess.check_call(
            ["upx", "--version"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        cmd.append("--enable-plugin=upx")
    except (subprocess.CalledProcessError, FileNotFoundError):
        if verbose:
            print("UPX not found, continuing without compression")

    if verbose:
        print(f"Building with command: {' '.join(cmd)}")
    else:
        cmd.append("--quiet")

    # Run Nuitka
    try:
        subprocess.check_call(cmd)
        print(f"Build successful! Executable is in {dist_dir}")

        # Move the executable to the parent directory if requested
        if move_exe:
            exe_ext = ".exe" if sys.platform == "win32" else ""
            exe_name = f"track_progress{exe_ext}"
            src_exe = os.path.join(dist_dir, exe_name)
            dst_exe = os.path.join(parent_dir, exe_name)

            if os.path.exists(src_exe):
                # Remove existing executable if it exists
                if os.path.exists(dst_exe):
                    os.remove(dst_exe)

                # Move the executable
                shutil.move(src_exe, dst_exe)
                if verbose:
                    print(f"Moved executable from {src_exe} to {dst_exe}")
            else:
                print(f"Warning: Built executable not found at {src_exe}")

        return 0
    except subprocess.CalledProcessError as e:
        print(f"Build failed: {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
