#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
harness="$repo_dir/config/dot/quickshell/display-layout-harness.qml"
state_home="$(mktemp -d /tmp/panama-display-layout-state.XXXXXX)"
shell_log="$state_home/quickshell.log"
harness_pid=""

fail() {
    printf 'display layout contract: %s\n' "$1" >&2
    [[ -s "$shell_log" ]] && sed -n '1,160p' "$shell_log" >&2
    exit 1
}

cleanup() {
    [[ "$harness_pid" =~ ^[0-9]+$ ]] && kill "$harness_pid" 2>/dev/null || true
    rm -rf "$state_home"
}
trap cleanup EXIT

qs_for_harness() {
    if [[ "$harness_pid" =~ ^[0-9]+$ && "${1:-}" == "ipc" ]]; then
        XDG_STATE_HOME="$state_home" qs -p "$harness" ipc --pid "$harness_pid" "${@:2}"
    else
        XDG_STATE_HOME="$state_home" qs -p "$harness" "$@"
    fi
}

qs_for_harness --daemonize >"$shell_log" 2>&1 || fail 'geometry harness did not launch'
for _ in $(seq 1 60); do
    harness_pid="$(qs list --all 2>/dev/null | awk -v expected="$harness" '
        /^Instance / {pid=""} /^[[:space:]]*Process ID:/ {pid=$3}
        /^[[:space:]]*Config path:/ {path=$0; sub(/^[[:space:]]*Config path: /,"",path); if(path==expected) print pid}' | head -1)"
    [[ "$harness_pid" =~ ^[0-9]+$ ]] \
        && qs_for_harness ipc show 2>/dev/null | rg -q '^target display-layout-test$' && break
    sleep 0.1
done
[[ "$harness_pid" =~ ^[0-9]+$ ]] || fail 'geometry harness process did not start'

status="$(qs_for_harness ipc call display-layout-test status)"
jq -e '.valid == true
    and .sizes == [{"width":3000,"height":2000},{"width":1440,"height":2560}]
    and .normalized == [
      {"name":"DP-2","x":0,"y":0,"primary":true},
      {"name":"HDMI-A-1","x":3000,"y":0,"primary":false}]
    and .bounds == {"x":0,"y":0,"width":4440,"height":2560}
    and .near == 3000 and .far == 3017
    and (.canvasRects | length) == 2
    and ((.bounds.width / .bounds.height) - (4440 / 2560) | fabs) < 0.000001' \
    <<<"$status" >/dev/null || fail "geometry output was wrong: $status"

invalid="$(qs_for_harness ipc call display-layout-test invalid)"
jq -e 'all(. == false)' <<<"$invalid" >/dev/null || fail "an invalid layout was accepted: $invalid"

# Mirroring is the one arrangement where the position on file is not the
# position on the desk. Hyprland stacks a mirrored output on its target and
# ignores whatever the rule asked for, so the geometry here has to agree:
# a mirrored display contributes nothing to the desktop's bounds, and the
# canvas draws it on top of what it mirrors rather than at stale coordinates.
mirror="$(qs_for_harness ipc call display-layout-test mirror)"
#
# The mirrored record is given its target's normalized position -- its stored
# coordinates stopped meaning anything the moment mirroring was turned on, and
# the compositor chooses the real ones. Keeping a stale pair would still draw
# it somewhere false on the canvas. It contributes nothing to the bounds, so
# the desktop measures 3000 x 2000: one display.
jq -e '.valid == true
    and .normalized == [
      {"name":"DP-2","x":0,"y":0,"primary":true,"mirrorOf":""},
      {"name":"HDMI-A-1","x":0,"y":0,"primary":false,"mirrorOf":"DP-2"}]
    and .bounds == {"x":0,"y":0,"width":3000,"height":2000}
    and (.rects | length) == 2
    and .rects[1].mirrorOf == "DP-2" and .rects[1].mirrored == true
    and .rects[0].mirrored == false
    and .rects[1].x == .rects[0].x and .rects[1].y == .rects[0].y
    and .rects[1].width == .rects[0].width' \
    <<<"$mirror" >/dev/null || fail "mirrored geometry was wrong: $mirror"

# A mirror that names itself, an absent output, or a display that is itself
# mirroring is not a layout with a cosmetic problem -- it is one the compositor
# will answer in a way nobody predicted.
invalid_mirrors="$(qs_for_harness ipc call display-layout-test invalidMirrors)"
jq -e 'all(. == false)' <<<"$invalid_mirrors" >/dev/null \
    || fail "an impossible mirror was accepted: $invalid_mirrors"

printf 'display layout contract: PASS\n'
