#!/bin/bash

get_pid() {
# Loop through python processes and resolve each script path
PID=""
for pid in $(pgrep -f python); do
    if [[ -r "/proc/$pid/cmdline" ]]; then
        # Get the full command line, null-separated
        cmdline=$(tr '\0' ' ' < "/proc/$pid/cmdline")
        # Extract the script argument (naively assumes it's the first non-option)
        script_arg=$(echo "$cmdline" | awk '{for (i=2;i<=NF;i++) if ($i !~ /^-/) {print $i; exit}}')

        # Try resolving the script path relative to the process's cwd
        script_path=$(readlink -f "/proc/$pid/cwd/$script_arg" 2>/dev/null)

        if [[ "$script_path" == "$TARGET" ]]; then
            PID=$pid
            break
        fi
    fi
done
}

if [[ -z "$1" ]]; then
  for file in "src/server.py" "src/backend/main.py"; do
    echo "Checking ${file}"
    # Ensure input was provided
    TARGET=$(readlink -f "$file")
    if [[ ! -f "$TARGET" ]]; then
      echo "Target file '$TARGET' not found."
      exit 1
    fi
    get_pid
    if [[ "${PID}" != "" ]]; then
      break
    fi
  done
else
  TARGET=$(readlink -f "$1")
  if [[ ! -f "$TARGET" ]]; then
    echo "Target file '$TARGET' not found."
    exit 1
  fi
  get_pid
fi

if [[ -z "$PID" ]]; then
    echo "No Python process found running."
    exit 1
fi

echo "Found process $PID running $TARGET"

# Get times
file_time=$(stat -c %Y "$TARGET")
proc_time=$(stat -c %Y "/proc/$PID")

# if (( file_time > proc_time )); then
#     echo "Script '$TARGET' is newer than process $PID. Killing $PID"
    kill -9 "$PID"
    if [[ $? -ne 0 ]]; then
        echo "Failed to kill process $PID."
        exit 1
    fi
    echo "Process $PID killed."
# else
#     echo "Script '$TARGET' is older than or same age as process $PID."
# fi
