#!/usr/bin/env bash

# Variable to store the last focused window address
last_focused_window=""
current_window=""

function handle {
  if [[ ${1:0:14} == "activewindowv2" ]]; then
    new_window="${1:16}"

    # Update window tracking
    last_focused_window="${current_window}"
    current_window="${new_window}"

    # Get all window information once
    window_info=$(hyprctl clients)

    # Process current focused window
    current_pid=""
    if [[ -n "$current_window" ]]; then
      # Extract tags
      current_tags=$(echo "$window_info" | awk -v addr="$current_window" '
        $0 ~ "Window " addr {found=1}
        found && /tags:/ {print $0; found=0; exit}
      ' | sed 's/.*tags: //;s/)//')

      # Extract PID
      current_pid=$(echo "$window_info" | awk -v addr="$current_window" '
        $0 ~ "Window " addr {found=1}
        found && /pid:/ {print $2; found=0; exit}
      ')

      # Process if window has zawarudo tag
      if [[ -n "$current_tags" && -n "$current_pid" ]]; then
        if [[ "$current_tags" == *"zawarudo"* ]]; then
          echo unfreeze $current_pid
          kill -CONT $current_pid 2>/dev/null
        fi
      fi
    fi

    # Process last focused window (unfocused)
    if [[ -n "$last_focused_window" ]]; then
      # Extract tags
      tags=$(echo "$window_info" | awk -v addr="$last_focused_window" '
        $0 ~ "Window " addr {found=1}
        found && /tags:/ {print $0; found=0; exit}
      ' | sed 's/.*tags: //;s/)//')

      # Extract PID
      pid=$(echo "$window_info" | awk -v addr="$last_focused_window" '
        $0 ~ "Window " addr {found=1}
        found && /pid:/ {print $2; found=0; exit}
      ')

      # Process if window has zawarudo tag
      if [[ -n "$tags" && -n "$pid" && "$pid" != "$current_pid" ]]; then
        if [[ "$tags" == *"zawarudo"* ]]; then
          echo freeze $current_pid
          kill -STOP $pid 2>/dev/null
        fi
      fi
    fi
  fi
}

# Listen for events
socat - "UNIX-CONNECT:$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" | while read -r line; do handle "$line"; done
