#!/bin/bash

# omarchy:summary=Choose a legible transparent bar text color
# omarchy:hidden=true

set -e

position=${1:-top}
bar_size=${2:-}
text_color=${3:-}
background_color=${4:-}
background_path=""
screen_size=""
widget_spans=""

shift 4 2>/dev/null || true
while (($# > 0)); do
  case "$1" in
  --background)
    background_path=${2:-}
    shift 2
    ;;
  --screen)
    screen_size=${2:-}
    shift 2
    ;;
  --spans)
    widget_spans=${2:-}
    shift 2
    ;;
  *)
    shift
    ;;
  esac
done

valid_hex() {
  [[ $1 =~ ^#[0-9A-Fa-f]{6}$ ]]
}

fallback() {
  printf '%s\n' "$text_color"
  exit 0
}

valid_hex "$text_color" || fallback
valid_hex "$background_color" || fallback
[[ $position =~ ^(top|bottom|left|right)$ ]] || fallback
[[ $bar_size =~ ^[0-9]+$ ]] || fallback
omarchy-cmd-present magick || fallback

if [[ -z $background_path ]]; then
  background_path=$(readlink -f "$HOME/.local/state/omarchy/current/background" 2>/dev/null || true)
fi
[[ -f $background_path ]] || fallback

if [[ -z $screen_size ]]; then
  if omarchy-cmd-present hyprctl && omarchy-cmd-present jq; then
    screen_size=$(hyprctl monitors -j 2>/dev/null | jq -r '
      .[0]
      | (if ((.transform // 0) % 2) == 1 then [.height, .width] else [.width, .height] end) as $dims
      | (.scale // 1) as $scale
      | "\(($dims[0] / $scale) | round)x\(($dims[1] / $scale) | round)"
    ' 2>/dev/null || true)
  fi
fi
[[ $screen_size =~ ^([0-9]+)x([0-9]+)$ ]] || fallback

screen_width=${BASH_REMATCH[1]}
screen_height=${BASH_REMATCH[2]}
((screen_width > 0 && screen_height > 0 && bar_size > 0)) || fallback

# Sample on a canvas no wider than 1920 px; a 6K or 8K screen would otherwise
# add a full-size intermediate image.
if ((screen_width > 1920)); then
  screen_height=$(((screen_height * 1920 + screen_width - 1) / screen_width))
  bar_size=$(((bar_size * 1920 + screen_width - 1) / screen_width))
  screen_width=1920
fi

# Choose prime sample counts coprime to the strip dimensions so periodic fine
# stripes (such as 1px or 2px alternating columns/rows on 1920x1080) cannot
# alias onto a single stripe phase.
coprime_major() {
  local length=$1
  if ((length <= 239)); then
    echo "$length"
  elif ((length % 239 != 0)); then
    echo 239
  else
    echo 241
  fi
}

coprime_minor() {
  local length=$1
  if ((length <= 7)); then
    echo "$length"
  elif ((length % 7 != 0)); then
    echo 7
  elif ((length % 11 != 0)); then
    echo 11
  else
    echo 5
  fi
}

case "$position" in
top)
  crop="${screen_width}x${bar_size}+0+0"
  sample_geometry="$(coprime_major "$screen_width")x$(coprime_minor "$bar_size")!"
  ;;
bottom)
  crop_y=$((screen_height - bar_size))
  ((crop_y >= 0)) || fallback
  crop="${screen_width}x${bar_size}+0+${crop_y}"
  sample_geometry="$(coprime_major "$screen_width")x$(coprime_minor "$bar_size")!"
  ;;
left)
  crop="${bar_size}x${screen_height}+0+0"
  sample_geometry="$(coprime_minor "$bar_size")x$(coprime_major "$screen_height")!"
  ;;
right)
  crop_x=$((screen_width - bar_size))
  ((crop_x >= 0)) || fallback
  crop="${bar_size}x${screen_height}+${crop_x}+0"
  sample_geometry="$(coprime_minor "$bar_size")x$(coprime_major "$screen_height")!"
  ;;
esac

# Sample the first frame only. Without the selector a video background makes
# ImageMagick decode the whole file and emit one value per frame, and the match
# below then fails into the fallback colour. Let JPEG decode at about canvas size
# and box-scale to the canvas, so a 6K or 8K photo fits the limit without a
# second full-size resize buffer. Do not let an oversized image spill its pixel
# cache into a memory map or /tmp (a tmpfs on Omarchy); fall back to the
# configured text color when the bounded sample cannot finish cheaply.
#
# Point-sample a prime grid coprime to the strip dimensions rather than averaging
# it into coarse tiles: averaging smears high-frequency stippling and crosshatching
# (dark ink beside bright paper) into a false mid-tone that looks readable on
# paper but buries glyphs in the live bar, while coprime dimensions keep fine
# stripes from aliasing onto one phase. Lay a soft mist behind the strip if
# neither theme colour can hold 2.2:1 across 90% of the strip (severe glare or
# stipple), or if the strip is broadly low-contrast (under 3.2:1 on the worst
# 10% and under WCAG AA 4.5:1 across half the bar).
#
# The strip as a whole can pass while a small busy patch sits right behind a
# widget (stars under the clock). With --spans (start-end fractions along the
# bar, comma separated) each stretch that holds widgets is checked on its own
# too, in windows about a clock wide, for speckle: samples where the chosen
# colour falls under 2.3:1 that have readable wallpaper both beside and above or
# below them. Stars and bright photo detail are ragged that way and break up
# glyphs; a flat block of colour or a smooth gradient is not, and text over
# one stays legible at a low contrast, so those stay clear. Mist once speckle
# makes up 3% of a window. A patch between the widgets counts for nothing.
samples=$(MAGICK_MEMORY_LIMIT=512MiB \
  MAGICK_MAP_LIMIT=0 \
  MAGICK_DISK_LIMIT=0 \
  MAGICK_TIME_LIMIT=5 \
  MAGICK_THREAD_LIMIT=2 \
  timeout --kill-after=1s 5s magick -define jpeg:size="${screen_width}x${screen_height}" "$background_path[0]" -auto-orient \
  -scale "${screen_width}x${screen_height}^" \
  -gravity center -extent "${screen_width}x${screen_height}" \
  -gravity NorthWest -crop "$crop" +repage \
  -alpha off -colorspace sRGB -sample "$sample_geometry" -depth 8 -compress none ppm:- 2>/dev/null || true)
[[ -n $samples ]] || fallback

[[ $widget_spans =~ ^[0-9.,-]*$ ]] || widget_spans=""
major_axis=x
[[ $position == left || $position == right ]] && major_axis=y

result=$(awk -v fg="$text_color" -v bg="$background_color" -v spans="$widget_spans" -v major="$major_axis" '
  function channel(hex, start) {
    return strtonum("0x" substr(hex, start, 2)) / 255
  }
  function linear(c) {
    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ^ 2.4
  }
  function hex_luminance(hex, r, g, b) {
    r = linear(channel(hex, 2))
    g = linear(channel(hex, 4))
    b = linear(channel(hex, 6))
    return 0.2126 * r + 0.7152 * g + 0.0722 * b
  }
  function rgb_luminance(r, g, b) {
    return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
  }
  # Contrast of the chosen colour at a sample, by its place along and across the bar.
  function text_cr(along, across, i) {
    i = major == "y" ? along * w + across + 1 : across * w + along + 1
    return best_color == bg ? bg_cr[i] : fg_cr[i]
  }
  function ratio(l1, l2, t) {
    if (l1 < l2) {
      t = l1
      l1 = l2
      l2 = t
    }
    return (l1 + 0.05) / (l2 + 0.05)
  }
  {
    sub(/#.*/, "")
    for (i = 1; i <= NF; i++) {
      tokens[++tok_count] = $i
    }
  }
  END {
    if (tok_count < 7 || tokens[1] != "P3") exit 1
    w = tokens[2] + 0
    h = tokens[3] + 0
    maxval = tokens[4] + 0
    n = w * h
    if (n <= 0 || maxval <= 0 || tok_count < 4 + n * 3) exit 1

    fg_lum = hex_luminance(fg)
    bg_lum = hex_luminance(bg)
    fg_sum = 0
    bg_sum = 0

    for (i = 1; i <= n; i++) {
      idx = 4 + (i - 1) * 3
      l = rgb_luminance(tokens[idx + 1] / maxval, tokens[idx + 2] / maxval, tokens[idx + 3] / maxval)
      fg_cr[i] = ratio(fg_lum, l)
      bg_cr[i] = ratio(bg_lum, l)
      fg_sum += fg_cr[i]
      bg_sum += bg_cr[i]
    }

    asort(fg_cr, fg_sorted)
    asort(bg_cr, bg_sorted)

    p10 = int(n * 0.10) + 1
    p50 = int(n * 0.50) + 1
    fg_p10 = fg_sorted[p10]
    bg_p10 = bg_sorted[p10]

    if (bg_p10 > fg_p10 || (bg_p10 == fg_p10 && bg_sum > fg_sum)) {
      best_p10 = bg_p10
      best_p50 = bg_sorted[p50]
      best_color = bg
    } else {
      best_p10 = fg_p10
      best_p50 = fg_sorted[p50]
      best_color = fg
    }

    # Samples run in rows, so along a horizontal bar the major axis is x.
    len = major == "y" ? h : w
    cross = major == "y" ? w : h
    speck_share = 0.03
    speck_floor = 2.3
    window = int(len * 0.10 + 0.5)
    if (window < 1) window = 1
    local_mist = 0
    span_count = split(spans, span_list, ",")
    for (s = 1; s <= span_count && !local_mist; s++) {
      if (split(span_list[s], edge, "-") != 2 || edge[1] == "" || edge[2] + 0 <= edge[1] + 0) continue
      first = int(edge[1] * len)
      last = int(edge[2] * len + 0.999) - 1
      if (first < 0) first = 0
      if (last > len - 1) last = len - 1
      if (last < first) continue
      # A widget narrower than the window is judged with its surroundings.
      if (last - first + 1 < window) {
        first = int((first + last + 1 - window) / 2)
        if (first < 0) first = 0
        if (first + window > len) first = len - window
        last = first + window - 1
      }
      step = int(window / 4)
      if (step < 1) step = 1
      for (start = first; !local_mist; start += step) {
        if (start + window - 1 > last) start = last - window + 1
        count = 0
        specks = 0
        for (m = start; m < start + window; m++) {
          for (o = 0; o < cross; o++) {
            count++
            if (text_cr(m, o) >= speck_floor) continue
            beside = (m > 0 && text_cr(m - 1, o) >= speck_floor) || (m < len - 1 && text_cr(m + 1, o) >= speck_floor)
            above = (o > 0 && text_cr(m, o - 1) >= speck_floor) || (o < cross - 1 && text_cr(m, o + 1) >= speck_floor)
            if (beside && above) specks++
          }
        }
        if (specks / count >= speck_share) local_mist = 1
        if (start + window - 1 >= last) break
      }
    }

    if (local_mist || best_p10 < 2.2 || (best_p10 < 3.2 && best_p50 < 4.5)) {
      print "mist"
    } else {
      print best_color
    }
  }
' <<<"$samples" 2>/dev/null || true)

if [[ $result == "mist" ]] || valid_hex "$result"; then
  printf '%s\n' "$result"
else
  fallback
fi
