#!/bin/sh
# ANODE unified .xth theme applier (strict POSIX sh, fractional DPI aware)
set -eu

: "${XDG_CONFIG_HOME:=$HOME/.config}"
: "${ANODE_PREFIX:=/usr/local}"
CONF_DIR="$XDG_CONFIG_HOME/anode"
THEME_CONF="$CONF_DIR/theme.conf"
SCALE_CONF="$CONF_DIR/scale.conf"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  cat <<'EOF'
Usage: anode-apply-theme [THEME_NAME | /path/to/Theme.xth]
EOF
  exit 0
fi

REQ_THEME="${1:-}"
if [ -z "$REQ_THEME" ] && [ -f "$THEME_CONF" ]; then
  REQ_THEME="$(awk -F= '/^THEME=/{ print $2; exit }' "$THEME_CONF" 2>/dev/null || true)"
fi
: "${REQ_THEME:=AnodeDefault}"

find_xth() {
  _q="$1"
  if [ -f "$_q" ]; then
    printf '%s\n' "$_q"
    return 0
  fi
  if [ -f "$_q.xth" ]; then
    printf '%s\n' "$_q.xth"
    return 0
  fi
  _base="$(basename "$_q" .xth)"
  for _dir in \
    "$CONF_DIR/themes" \
    "$HOME/.xthemes" \
    "$ANODE_PREFIX/share/anode/themes" \
    "$SCRIPT_DIR/../share/anode/themes" \
    "$SCRIPT_DIR/../data/themes"
  do
    if [ -f "$_dir/$_base.xth" ]; then
      printf '%s\n' "$_dir/$_base.xth"
      return 0
    fi
  done
  return 1
}

XTH_FILE="$(find_xth "$REQ_THEME" || true)"
if [ -z "$XTH_FILE" ] || [ ! -r "$XTH_FILE" ]; then
  printf 'anode-apply-theme: theme not found: %s\n' "$REQ_THEME" >&2
  exit 1
fi

SCALE=""
TOUCH=""
if [ -f "$SCALE_CONF" ]; then
  . "$SCALE_CONF"
else
  if [ -n "${ANODE_SCALE:-}" ]; then SCALE="$ANODE_SCALE"; fi
  if [ -n "${ANODE_TOUCH:-}" ]; then TOUCH="$ANODE_TOUCH"; fi
fi
: "${SCALE:=1.00}"
: "${TOUCH:=0}"

resolve_ui_font() {
  _req="$1"
  [ -n "$_req" ] || _req="Roboto"
  if [ "$_req" = "Roboto" ] && command -v fc-list >/dev/null 2>&1; then
    _resolved="$(fc-list : family 2>/dev/null | awk '
      {
        n = split($0, a, ",")
        for (i = 1; i <= n; i++) {
          s = a[i]
          gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s)
          ls = tolower(s)
          if (ls == "roboto") has_rob = 1
          else if (ls == "noto sans") has_noto = 1
        }
      }
      END {
        if (has_rob) print "Roboto"
        else if (has_noto) print "Noto Sans"
        else print "Roboto"
      }
    ' || true)"
    if [ -n "$_resolved" ]; then
      printf '%s\n' "$_resolved"
      return 0
    fi
  fi
  printf '%s\n' "$_req"
}

THEME_NAME="$(awk -F: '/^theme\.name[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); print $2; exit }' "$XTH_FILE" || true)"
if [ -z "$THEME_NAME" ]; then
  THEME_NAME="$(basename "$XTH_FILE" .xth)"
fi
RAW_UI_FONT="$(awk -F: '/^theme\.uiFontFace[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); sub(/[ \t\r\n]+$/, "", $2); print $2; exit }' "$XTH_FILE" || true)"
UI_FONT="$(resolve_ui_font "${RAW_UI_FONT:-Roboto}")"

mkdir -p "$CONF_DIR"
LOCAL_XRES="$CONF_DIR/Xresources.local"
PRESERVED_ST=""
if [ -r "$HOME/.Xresources" ]; then
  _lfile_arg=""
  if [ -r "$LOCAL_XRES" ]; then
    _lfile_arg="$LOCAL_XRES"
  fi
  PRESERVED_ST="$(awk -v lfile="$_lfile_arg" '
    function trim(s) {
      gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s)
      return s
    }
    BEGIN {
      if (lfile != "") {
        while ((getline line < lfile) > 0) {
          sl = trim(line)
          if (sl == "" || substr(sl, 1, 1) == "!" || substr(sl, 1, 1) == "#") continue
          pl = index(sl, ":")
          if (pl > 0) {
            kl = trim(substr(sl, 1, pl - 1))
            local_keys[kl] = 1
          }
        }
        close(lfile)
      }
    }
    /^[ \t]*![ \t]*User overrides from Xresources\.local/ { exit }
    {
      s = trim($0)
      if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next
      p = index(s, ":")
      if (p > 0) {
        k = trim(substr(s, 1, p - 1))
        if (substr(k, 1, 3) == "St." && !(k in local_keys)) {
          if (!(k in seen)) {
            seen[k] = 1
            order[++n] = k
          }
          lines[k] = s
        }
      }
    }
    END {
      for (i = 1; i <= n; i++) print lines[order[i]]
    }
  ' "$HOME/.Xresources" 2>/dev/null || true)"
fi

TMP_XRES="$HOME/.Xresources.tmp.$$"

awk -v scale_str="$SCALE" -v touch_str="$TOUCH" -v tname="$THEME_NAME" -v ui_font="$UI_FONT" '
function trim(s) {
  gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s)
  return s
}
function rint(x) {
  return int(x + 0.5)
}
{
  raw[NR] = $0
  s = trim($0)
  if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next
  pos = index(s, ":")
  if (pos > 0) {
    k = trim(substr(s, 1, pos - 1))
    v = trim(substr(s, pos + 1))
    vals[k] = v
  }
}
END {
  s = scale_str + 0.0
  if (s < 0.50) s = 0.50
  if (s > 4.00) s = 4.00
  t = (touch_str == "1" || touch_str == 1) ? 1 : 0

  orig_dpi = ("Xft.dpi" in vals) ? (vals["Xft.dpi"] + 0.0) : 96.0
  base_sz = ("theme.baseFontSize" in vals) ? (vals["theme.baseFontSize"] + 0.0) : 15.0
  cur_sz = ("Xcursor.size" in vals) ? (vals["Xcursor.size"] + 0.0) : 24.0
  bw = ("dwm.borderpx" in vals) ? (vals["dwm.borderpx"] + 0.0) : 2.0

  # Normalize imported 192-DPI themes down to 96-DPI logical bases before scaling
  if (orig_dpi >= 160.0 && base_sz >= 24.0) {
    base_sz = base_sz / 2.0
    if (cur_sz >= 40.0) cur_sz = cur_sz / 2.0
    if (bw >= 4.0) bw = bw / 2.0
  }
  if (base_sz < 8.0 || base_sz > 28.0) base_sz = 15.0
  if (cur_sz < 12.0 || cur_sz > 48.0) cur_sz = 24.0
  if (bw < 1.0 || bw > 6.0) bw = 2.0

  xft_dpi = rint(96.0 * s)
  if (xft_dpi < 48) xft_dpi = 48
  if (xft_dpi > 384) xft_dpi = 384

  scaled_font_px = rint(base_sz * s)
  if (scaled_font_px < 8) scaled_font_px = 8
  if (scaled_font_px > 96) scaled_font_px = 96

  raw_cur = cur_sz * s
  if (raw_cur < 20.0) scaled_cur = 16
  else if (raw_cur < 32.0) scaled_cur = 24
  else if (raw_cur < 44.0) scaled_cur = 32
  else if (raw_cur < 64.0) scaled_cur = 48
  else scaled_cur = 64

  scaled_bw = rint(bw * s)
  if (scaled_bw < 1) scaled_bw = 1
  if (scaled_bw > 10) scaled_bw = 10

  scaled_dm_lh = rint(26.0 * s)
  if (scaled_dm_lh < 20) scaled_dm_lh = 20
  if (t == 1 && scaled_dm_lh < rint(36.0 * s)) scaled_dm_lh = rint(36.0 * s)

  font_face = ("theme.fontFace" in vals && vals["theme.fontFace"] != "") ? vals["theme.fontFace"] : "Fira Code"
  icon_face = ("theme.iconFontFace" in vals && vals["theme.iconFontFace"] != "") ? vals["theme.iconFontFace"] : "DejaVuSansM Nerd Font"

  over["theme.name"] = tname
  over["theme.fontFace"] = font_face
  over["theme.uiFontFace"] = ui_font
  over["theme.iconFontFace"] = icon_face
  over["theme.baseFontSize"] = sprintf("%d", scaled_font_px)
  over["theme.scale"] = sprintf("%.2f", s)
  over["theme.touchMode"] = sprintf("%d", t)
  over["theme.gtkTheme"] = "ANODE-" tname
  over["*TkTheme"] = "gtkTtk"
  over["Xft.dpi"] = sprintf("%d", xft_dpi)
  over["Xcursor.size"] = sprintf("%d", scaled_cur)
  over["dwm.borderpx"] = sprintf("%d", scaled_bw)
  over["dwm.font"] = sprintf("%s, %s %dpx", font_face, icon_face, scaled_font_px)
  over["dmenu.font"] = sprintf("%s, %s %dpx", font_face, icon_face, scaled_font_px)
  over["dmenu.lineheight"] = sprintf("%d", scaled_dm_lh)
  over["st.font"] = sprintf("%s:size=13:style=Regular:antialias=true:autohint=true", font_face)

  for (i = 1; i <= NR; i++) {
    sline = trim(raw[i])
    if (sline == "" || substr(sline, 1, 1) == "!" || substr(sline, 1, 1) == "#") {
      print raw[i]
      continue
    }
    p = index(sline, ":")
    if (p > 0) {
      key = trim(substr(sline, 1, p - 1))
      if (key in over) {
        if (!(key in emitted)) {
          printf "%s: %s\n", key, over[key]
          emitted[key] = 1
        }
      } else {
        print raw[i]
      }
    } else {
      print raw[i]
    }
  }
  order[1] = "theme.scale"; order[2] = "theme.touchMode"; order[3] = "theme.gtkTheme"
  order[4] = "*TkTheme"; order[5] = "Xft.dpi"; order[6] = "Xcursor.size"
  order[7] = "theme.fontFace"; order[8] = "theme.uiFontFace"; order[9] = "theme.iconFontFace"
  order[10] = "theme.baseFontSize"; order[11] = "dwm.borderpx"; order[12] = "dwm.font"
  order[13] = "dmenu.font"; order[14] = "dmenu.lineheight"; order[15] = "st.font"
  for (j = 1; j <= 15; j++) {
    ok = order[j]
    if (!(ok in emitted)) {
      printf "%s: %s\n", ok, over[ok]
      emitted[ok] = 1
    }
  }
}
' "$XTH_FILE" > "$TMP_XRES"

if [ -n "${PRESERVED_ST:-}" ]; then
  {
    printf '\n! Preserved user St.* overrides\n'
    printf '%s\n' "$PRESERVED_ST"
  } >> "$TMP_XRES"
fi

if [ -r "$LOCAL_XRES" ]; then
  {
    printf '\n! User overrides from Xresources.local\n'
    cat "$LOCAL_XRES"
    printf '\n'
  } >> "$TMP_XRES"
fi

mv -f "$TMP_XRES" "$HOME/.Xresources"

TMP_TC="$THEME_CONF.tmp.$$"
printf 'THEME=%s\nXTH_FILE=%s\n' "$THEME_NAME" "$XTH_FILE" > "$TMP_TC"
mv -f "$TMP_TC" "$THEME_CONF"

if [ -n "${DISPLAY:-}" ] && command -v xrdb >/dev/null 2>&1; then
  xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true
fi

if [ -x "$SCRIPT_DIR/anode-sync-gtk-theme" ]; then
  "$SCRIPT_DIR/anode-sync-gtk-theme"
elif command -v anode-sync-gtk-theme >/dev/null 2>&1; then
  anode-sync-gtk-theme
fi

if [ -x "$SCRIPT_DIR/anode-sync-dunst-theme" ]; then
  "$SCRIPT_DIR/anode-sync-dunst-theme"
elif command -v anode-sync-dunst-theme >/dev/null 2>&1; then
  anode-sync-dunst-theme
fi

if [ -n "${DISPLAY:-}" ] && [ "${ANODE_NO_SIGNAL:-0}" != "1" ]; then
  _pids="$( (ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null || true) | awk '
    {
      pid = $1; cmd = $2
      sub(/^.*\//, "", cmd)
      if (cmd == "dwm" || cmd == "st" || cmd == "anode-statusd" ||
          cmd == "anode-net" || cmd == "anode-audio" || cmd == "anode-display" ||
          cmd == "anode-datetime" || cmd == "anode-power" || cmd == "anode-themes") {
        print "USR1 " pid
      } else if (cmd == "anode-vkbd") {
        print "HUP " pid
      }
    }
  ' )"
  if [ -n "${_pids:-}" ]; then
    printf '%s\n' "$_pids" | while read -r _sig _p; do
      [ -n "${_p:-}" ] && kill -"$_sig" "$_p" 2>/dev/null || true
    done
  fi
fi

printf 'ANODE applied theme: %s (scale=%s)\n' "$THEME_NAME" "$SCALE"
