#!/usr/bin/env bash

# focus_workspace_with_monitor_swap.sh – move workspace to the other monitor and focus it
# Usage: focus_workspace_with_monitor_swap.sh <workspace-number>

workspace="$1"
if [[ -z "$workspace" ]]; then
    echo "Usage: $0 <workspace-number>"
    exit 1
fi

# Get monitor information (plain text)
monitor_output=$(hyprctl monitors)

# Extract monitor IDs and find the focused one
declare -a monitor_ids=()
focused_id=""
while IFS= read -r line; do
    if [[ "$line" =~ Monitor[[:space:]]([^[:space:]]+)[[:space:]]\(ID[[:space:]]([0-9]+)\) ]]; then
        mon_name="${BASH_REMATCH[1]}"
        mon_id="${BASH_REMATCH[2]}"
        monitor_ids+=("$mon_id")
    fi
    if [[ "$line" =~ focused:[[:space:]]yes ]]; then
        # The focused monitor is the one we just parsed (the previous line had its ID)
        focused_id="$mon_id"
    fi
done <<< "$monitor_output"

if [[ ${#monitor_ids[@]} -ne 2 ]]; then
    echo "Warning: Expected exactly 2 monitors, found ${#monitor_ids[@]}. Using fallback (+1)."
    # Fallback: just move to next monitor (original behaviour)
    hyprctl dispatch moveworkspacetomonitor "$workspace" +1
    hyprctl dispatch workspace "$workspace"
    exit 0
fi

# Determine the "other" monitor ID
other_id=""
for id in "${monitor_ids[@]}"; do
    if [[ "$id" != "$focused_id" ]]; then
        other_id="$id"
        break
    fi
done

if [[ -z "$other_id" ]]; then
    echo "Error: Could not determine the other monitor."
    exit 1
fi

# Check if the workspace already exists and find its current monitor
current_monitor_id=""
workspace_output=$(hyprctl workspaces)
in_workspace_block=false
while IFS= read -r line; do
    if [[ "$line" =~ workspace[[:space:]]ID[[:space:]]([0-9]+)[[:space:]] ]]; then
        wid="${BASH_REMATCH[1]}"
        if [[ "$wid" == "$workspace" ]]; then
            in_workspace_block=true
        else
            in_workspace_block=false
        fi
    fi
    if $in_workspace_block && [[ "$line" =~ monitorID:[[:space:]]([0-9]+) ]]; then
        current_monitor_id="${BASH_REMATCH[1]}"
        break
    fi
done <<< "$workspace_output"

if [[ -n "$current_monitor_id" ]]; then
    # Workspace exists – move it to the monitor that is NOT its current one
    if [[ "$current_monitor_id" == "$focused_id" ]]; then
        target_id="$other_id"
    else
        target_id="$focused_id"
    fi
else
    # Workspace does not exist – create it on the monitor that is NOT focused
    target_id="$other_id"
fi

# Move the workspace (creates it if needed) and then focus it
hyprctl dispatch moveworkspacetomonitor "$workspace" "$target_id"
hyprctl dispatch workspace "$workspace"
