#!/bin/bash
# omarchy:summary=Check Fcitx5 Rime installation and configuration
# omarchy:examples=omarchycn ime status

set -euo pipefail

failures=0

for pkg in fcitx5 fcitx5-gtk fcitx5-qt fcitx5-rime fcitx5-chinese-addons; do
  if pacman -Q "$pkg" > /dev/null 2>&1; then
    echo "PASS ime: $pkg installed"
  else
    echo "FAIL ime: $pkg missing"
    failures=$((failures + 1))
  fi
done

if grep -sq '^Name=rime$' "$HOME/.config/fcitx5/profile"; then
  echo "PASS ime: rime in fcitx5 profile"
else
  echo "FAIL ime: rime not in fcitx5 profile (run: omarchycn ime apply)"
  failures=$((failures + 1))
fi

if grep -sq '^DefaultIM=rime$' "$HOME/.config/fcitx5/profile"; then
  echo "PASS ime: rime is the default input method"
else
  echo "FAIL ime: DefaultIM is not rime"
  failures=$((failures + 1))
fi

env_file="/usr/share/omarchy/default/environment.d/10-omarchy-fcitx.conf"
if [[ -f $env_file ]] || [[ -f $OMARCHY_PATH/default/environment.d/10-omarchy-fcitx.conf ]]; then
  echo "PASS ime: fcitx environment file present"
else
  echo "FAIL ime: fcitx environment file missing"
  failures=$((failures + 1))
fi

trigger=$(grep -sA2 '^\[Hotkey/TriggerKeys\]' "$HOME/.config/fcitx5/config" | grep -sE '^0=' | cut -d= -f2- || true)
if [[ $trigger == "Super+space" ]] && ! grep -sq 'OmarchyCN ime hotkey begin' "$HOME/.config/hypr/bindings.lua"; then
  echo "FAIL ime: Super+space 与 Omarchy 菜单冲突 (run: omarchycn ime hotkey super-space)"
  failures=$((failures + 1))
else
  echo "PASS ime: trigger key ${trigger:-Control+space (fcitx5 default)}"
fi

if pgrep -x fcitx5 > /dev/null 2>&1; then
  echo "PASS ime: fcitx5 running"
else
  echo "INFO ime: fcitx5 not running (headless session?)"
fi

exit $((failures > 0 ? 1 : 0))
