#!/bin/bash

# omarchy:summary=Screenshot a shell plugin's bar widget and report its QML errors
# omarchy:args=<plugin-dir> [--set property=value]... [--out file.png]
# omarchy:examples=omarchy agent look plugin ~/.config/omarchy/plugins/alice.counter | omarchy agent look plugin ~/.config/omarchy/plugins/alice.counter --set count=42

# Renders the plugin's bar widget in a bar-sized window with the current theme
# and saves it as an image, so an agent sees its widget without reloading the
# user's bar. The window floats without taking the focus and closes once
# captured; the running shell is untouched. (Offscreen rendering can't load
# widgets with a popup panel, which need layer shell.) Prints the QML errors
# and warnings the plugin produced while loading. --set gives a property of
# the widget a value first (a number, true or false, or else a string), so
# a state the widget only reaches later, a running timer or an alert, can be
# looked at without editing the plugin.

set -uo pipefail

usage="Usage: omarchy agent look plugin <plugin-dir> [--set property=value]... [--out file.png]"
if [[ -z ${1:-} || $1 == -* ]]; then
  echo "$usage" >&2
  exit 2
fi
plugin=$(realpath "$1")
shift
out=""
sets="{}"
# A value that reads as JSON (42, true, [1, 2]) is that; anything else is the string.
set_property() {
  sets=$(jq -c --arg key "${1%%=*}" --arg value "${1#*=}" '. + {($key): ($value | try fromjson catch $value)}' <<<"$sets")
}
while (( $# )); do
  case $1 in
    --out) out=${2:?--out needs a file}; shift 2 ;;
    --set)
      if [[ ${2:-} != [A-Za-z_]*=* ]]; then
        echo "--set takes property=value, like --set count=42" >&2
        exit 2
      fi
      set_property "$2"
      shift 2 ;;
    # --set a=1 b=2 sets both.
    [A-Za-z_]*=*) set_property "$1"; shift ;;
    *) echo "$usage" >&2; exit 2 ;;
  esac
done
[[ -n $out ]] || out=$(mktemp --suffix=.png -p "${TMPDIR:-/tmp}" look-XXXXXX)
entry=$(jq -r '.entryPoints.barWidget // empty' "$plugin/manifest.json" 2>/dev/null)
if [[ -z $entry ]]; then
  echo "$plugin/manifest.json has no entryPoints.barWidget" >&2
  exit 1
fi

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/config"
for item in "$OMARCHY_PATH"/shell/*; do
  [[ $(basename "$item") == "shell.qml" ]] || ln -s "$item" "$work/config/$(basename "$item")"
done

component_url=$(jq -Rn --arg path "$plugin/$entry" '"file://" + ($path | split("/") | map(@uri) | join("/"))')
shot_path=$(jq -Rn --arg path "$work/shot.png" '$path')

cat > "$work/config/shell.qml" <<EOF
import QtQuick
import Quickshell
import qs.Commons

ShellRoot {
  id: root
  property var widget
  property int step: 0

  FloatingWindow {
    id: win
    implicitWidth: 640
    implicitHeight: Style.bar.sizeHorizontal + 16
    color: Color.background
    // Only this strip of bar is captured, whatever size the compositor gives
    // the window: the widget and a little bar beside it, so the widget fills
    // the picture.
    Rectangle {
      id: frame
      anchors.centerIn: parent
      width: root.widget ? Math.min(600, Math.max(120, root.widget.width + 64)) : 600
      height: Style.bar.sizeHorizontal + 8
      color: (Color.bar && Color.bar.background) ? Color.bar.background : "#16161e"
      Item { id: host; anchors.centerIn: parent; width: frame.width - 16; height: Style.bar.sizeHorizontal }
    }
  }

  Timer {
    interval: 700
    repeat: true
    running: true
    onTriggered: {
      if (root.step === 0) {
        var component = Qt.createComponent($component_url)
        if (component.status !== Component.Ready) {
          console.log("PREVIEW_ERROR " + component.errorString())
          Qt.quit()
          return
        }
        root.widget = component.createObject(host, { moduleName: "preview", height: Style.bar.sizeHorizontal })
        if (!root.widget) {
          console.log("PREVIEW_ERROR could not create the widget: " + component.errorString())
          Qt.quit()
          return
        }
        root.widget.anchors.verticalCenter = host.verticalCenter
        root.widget.anchors.right = host.right
        var sets = $sets
        for (var key in sets) {
          if (!(key in root.widget)) {
            console.log("PREVIEW_ERROR --set " + key + ": the widget has no property " + key)
            Qt.quit()
            return
          }
          root.widget[key] = sets[key]
        }
      } else if (root.step === 2) {
        frame.grabToImage(function(result) {
          result.saveToFile($shot_path)
          console.log("PREVIEW_SAVED " + Math.round(root.widget.width) + "x" + Math.round(root.widget.height) + " " + Math.round(root.widget.implicitWidth) + "x" + Math.round(root.widget.implicitHeight))
          Qt.quit()
        })
      }
      root.step++
    }
  }
}
EOF

# Hyprland starts the window with the session's environment, so pass on the
# caller's home: an agent working in another home sees its own plugin and
# theme. While the display is off nothing on screen draws, so render
# offscreen instead, which works for any widget without a popup panel.
offscreen=false
hyprctl monitors -j | jq -e 'any(.[]; .dpmsStatus)' >/dev/null || offscreen=true
if [[ $offscreen == "true" ]]; then
  QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software QT_QPA_PLATFORMTHEME= QT_STYLE_OVERRIDE= \
    timeout 20 quickshell -p "$work/config" --no-color >"$work/log" 2>&1 </dev/null &
else
  command="export HOME=${HOME@Q} OMARCHY_PATH=${OMARCHY_PATH@Q} QT_QPA_PLATFORMTHEME= QT_STYLE_OVERRIDE=; exec timeout 20 quickshell -p ${work@Q}/config --no-color >${work@Q}/log 2>&1"
  hyprctl dispatch "hl.dsp.exec_cmd($(jq -Rn --arg c "bash -c ${command@Q}" '$c'), { float = true, no_initial_focus = true })" >/dev/null
fi
for _ in {1..50}; do
  grep -qE "PREVIEW_SAVED|PREVIEW_ERROR" "$work/log" 2>/dev/null && break
  sleep 0.5
done
sleep 0.5
# The preview's own quickshell, found by its unique scratch path.
pgrep -f -- "quickshell -p $work/config" | xargs -r kill 2>/dev/null

problems=$( (grep -E "WARN|ERROR" "$work/log" | grep -F "$plugin"; grep "PREVIEW_ERROR" "$work/log" | sed 's/^.*PREVIEW_ERROR //') \
  | sed -E 's/^ *(WARN|ERROR)[^:]*: //' | sort -u | head -20)
if [[ ! -s $work/shot.png ]]; then
  echo "The widget didn't render." >&2
  if [[ $offscreen == "true" ]] && grep -q "No PanelWindow backend" "$work/log"; then
    echo "The display is off, and a widget with a popup panel can only be drawn on screen; the errors below other than the panel's are real." >&2
    echo "Don't turn the display on or start a shell of your own to get around this: the user is away or the screen is locked. Fix the other errors, and tell the user the panel is still to be looked at." >&2
  fi
  [[ -n $problems ]] && echo "$problems" >&2
  exit 1
fi
magick "$work/shot.png" -resize '200%' "$out"
read -r size implicit < <(grep -oE 'PREVIEW_SAVED [0-9]+x[0-9]+ [0-9]+x[0-9]+' "$work/log" | cut -d' ' -f2-)
echo "screenshot: $out"
echo "widget: $size, shown at 2x on a strip of bar"
# The bar lays widgets out by their size, so one with none draws over its
# neighbours, though its own label may still show in the picture.
# The preview gives the widget the bar's height, so it's the implicit size,
# the one the bar lays out by, that tells.
if [[ $implicit == 0x* || $implicit == *x0 ]]; then
  problems=$(printf '%s\n' "${problems:+$problems}" "the widget's implicit size is $implicit, so the bar gives it no room and it draws over its neighbours: size the BarWidget to its content, as implicitWidth: button.implicitWidth and implicitHeight: button.implicitHeight do" | sed '/^$/d')
fi
if [[ -n $problems ]]; then
  echo "problems:"
  echo "$problems"
  exit 1
fi
