#!/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"

printf 'display layout contract: PASS\n'
