"""
Create launcher scripts for the progress tracker.
"""

import os
import sys
from typing import List, Tuple


def create_python_launcher(
    output_path: str, dest_dir: str, project_name: str
) -> bool:
    """Create a Python launcher script."""
    content = f"""#!/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)
"""

    try:
        with open(output_path, "w", encoding="utf-8", newline="\n") as f:
            f.write(content)
        return True
    except Exception as e:
        print(f"Error creating Python launcher: {e}")
        return False


def create_shell_launcher(output_path: str) -> bool:
    """Create a shell launcher script."""
    content = """#!/bin/bash

# Get the directory of this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TRACKER_DIR="$(dirname "$SCRIPT_DIR")"
EXE_PATH="$TRACKER_DIR/track_progress"
PY_PATH="$TRACKER_DIR/track_progress.py"

# Check if executable exists and is executable
if [ -x "$EXE_PATH" ]; then
    echo "Running Progress Tracker (executable version)..."
    "$EXE_PATH" "$@"
elif [ -f "$PY_PATH" ]; then
    echo "Executable not found, trying Python version..."
    echo "Running Progress Tracker (Python version)..."
    python "$PY_PATH" "$@"
else
    echo "Error: Neither executable nor Python script found at:"
    echo "- $EXE_PATH"
    echo "- $PY_PATH"
    exit 1
fi

EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
    echo "Progress tracking completed successfully!"
else
    echo "Error running progress tracker! (Exit code: $EXIT_CODE)"
fi
"""

    try:
        with open(output_path, "w", encoding="utf-8", newline="\n") as f:
            f.write(content)

        # Make the script executable on Unix-like systems
        if sys.platform != "win32":
            os.chmod(output_path, 0o755)

        return True
    except Exception as e:
        print(f"Error creating shell launcher: {e}")
        return False


def create_batch_launcher(output_path: str) -> bool:
    """Create a batch launcher script."""
    content = """@echo off
setlocal enabledelayedexpansion

REM Get the directory of this script
set "SCRIPT_DIR=%~dp0"
set "TRACKER_DIR=%SCRIPT_DIR%.."
set "EXE_PATH=%TRACKER_DIR%\\track_progress.exe"
set "PY_PATH=%TRACKER_DIR%\\track_progress.py"

REM Check if executable exists
if exist "%EXE_PATH%" (
    echo Running Progress Tracker (executable version)...
    "%EXE_PATH%" %*
) else (
    echo Executable not found, trying Python version...
    if exist "%PY_PATH%" (
        echo Running Progress Tracker (Python version)...
        python "%PY_PATH%" %*
    ) else (
        echo Error: Neither executable nor Python script found at:
        echo - %EXE_PATH%
        echo - %PY_PATH%
        exit /b 1
    )
)

if %ERRORLEVEL% EQU 0 (
    echo Progress tracking completed successfully!
) else (
    echo Error running progress tracker! (Exit code: %ERRORLEVEL%)
)
pause
"""

    try:
        with open(output_path, "w", encoding="utf-8", newline="\n") as f:
            f.write(content)
        return True
    except Exception as e:
        print(f"Error creating batch launcher: {e}")
        return False


def ensure_launcher_scripts(
    script_dir: str,
    dest_dir: str,
    project_name: str,
    verbose: bool = False,
    force: bool = False,
) -> List[str]:
    """Ensure all launcher scripts exist in the script directory."""
    created_scripts = []

    # Define the scripts to check/create
    scripts_to_ensure = [
        ("run_progress_tracker.py", create_python_launcher),
        ("run_progress_tracker.sh", create_shell_launcher),
        ("run_progress_tracker.bat", create_batch_launcher),
    ]

    for script_name, create_func in scripts_to_ensure:
        script_path = os.path.join(script_dir, script_name)

        if not os.path.exists(script_path) or force:
            if verbose:
                print(f"Creating launcher script: {script_path}")

            if create_func(script_path, dest_dir, project_name):
                created_scripts.append(script_path)
                if verbose:
                    print(f"Created {script_path}")
            else:
                print(f"Failed to create {script_path}")
        elif verbose:
            print(f"Launcher script already exists: {script_path}")

    return created_scripts
