#!/bin/bash
# Screen rotation for niri using niri IPC.
# Usage: unified-rotate.sh [cw|ccw|0|90|180|270]

direction="$1"

if [[ "$direction" != "cw" && "$direction" != "ccw" && \
      "$direction" != "0" && "$direction" != "90" && \
      "$direction" != "180" && "$direction" != "270" ]]; then
    echo "Usage: $0 [cw|ccw|0|90|180|270]"
    exit 1
fi

# Get focused output name
outputs_json=$(niri msg -j outputs 2>/dev/null)
curmon=$(echo "$outputs_json" | jq -r 'to_entries[] | select(.value.is_active == true) | .key' 2>/dev/null | head -1)

if [ -z "$curmon" ]; then
    # Fallback: use first output
    curmon=$(echo "$outputs_json" | jq -r 'keys[0]' 2>/dev/null)
fi

if [ -z "$curmon" ]; then
    notify-send -u critical "Screen Rotation" "Could not detect current output"
    exit 1
fi

# Niri transform values: "normal" | "90" | "180" | "270" | "flipped" | "flipped-90" | "flipped-180" | "flipped-270"
currot=$(echo "$outputs_json" | jq -r ".\"$curmon\".transform // \"normal\"" 2>/dev/null)

declare -A rot_to_deg=([normal]="0" [90]="90" [180]="180" [270]="270")
declare -A deg_to_rot=([0]="normal" [90]="90" [180]="180" [270]="270")

curdeg="${rot_to_deg[$currot]:-0}"

if [[ "$direction" == "cw" ]]; then
    newdeg=$(( (curdeg + 90) % 360 ))
elif [[ "$direction" == "ccw" ]]; then
    newdeg=$(( (curdeg + 270) % 360 ))
else
    newdeg="$direction"
fi

newrot="${deg_to_rot[$newdeg]:-normal}"

echo "Rotating '$curmon' from ${curdeg}° to ${newdeg}° (${newrot})"
niri msg action set-output-transform "$curmon" "$newrot"

eww reload 2>/dev/null || true
