#!/usr/bin/env bash
# Capture the currently focused window

set -euo pipefail

# Check required commands
for cmd in niri jq logger; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "Error: Required command not found: $cmd" >&2
        exit 1
    fi
done

LOG_TAG="niri-capture"
SCREENSHOT_DIR="$HOME/Pictures/Screenshots"

# Ensure screenshot directory exists
if [[ ! -d "$SCREENSHOT_DIR" ]]; then
    mkdir -p "$SCREENSHOT_DIR"
    logger -t "$LOG_TAG" "Created screenshot directory: $SCREENSHOT_DIR"
fi

# Get focused window metadata
if ! WINDOW_META=$(niri msg --json focused-window 2>&1); then
    logger -t "$LOG_TAG" "ERROR: Failed to query niri: $WINDOW_META"
    echo "Error: Failed to query niri. Is niri running?" >&2
    exit 1
fi
WINDOW_ID=$(echo "$WINDOW_META" | jq -r '.id')
WINDOW_TITLE=$(echo "$WINDOW_META" | jq -r '.title')
WORKSPACE_ID=$(echo "$WINDOW_META" | jq -r '.workspace_id')

if [[ -z "$WINDOW_ID" || "$WINDOW_ID" == "null" ]]; then
    logger -t "$LOG_TAG" "ERROR: No focused window"
    echo "Error: No focused window" >&2
    exit 1
fi

# Log the capture
logger -t "$LOG_TAG" "Capturing focused window $WINDOW_ID: '$WINDOW_TITLE' (workspace: $WORKSPACE_ID)"

# Capture to screenshots directory
if ! niri msg action screenshot-window --id "$WINDOW_ID" --write-to-disk true >/dev/null 2>&1; then
    logger -t "$LOG_TAG" "ERROR: Failed to capture window $WINDOW_ID"
    echo "Error: Failed to capture window" >&2
    exit 1
fi

# Return path to the screenshot
sleep 0.1
if ! SCREENSHOT_PATH=$(ls -t "$SCREENSHOT_DIR"/*.png 2>/dev/null | head -1) || [[ -z "$SCREENSHOT_PATH" ]]; then
    logger -t "$LOG_TAG" "ERROR: No screenshot found in $SCREENSHOT_DIR"
    echo "Error: Screenshot not found" >&2
    exit 1
fi

logger -t "$LOG_TAG" "Screenshot saved: $SCREENSHOT_PATH"
echo "$SCREENSHOT_PATH"
