#!/bin/bash

# omarchy:summary=Set up Japanese, Korean, or Chinese typing
# omarchy:args=[mozc|hangul|pinyin|chewing]
# omarchy:examples=omarchy setup input | omarchy setup input mozc
# omarchy:requires-sudo=true

set -euo pipefail

if (( $# > 1 )); then
  echo "Usage: omarchy setup input [mozc|hangul|pinyin|chewing]" >&2
  exit 1
fi

method=${1:-}
if [[ -z $method ]]; then
  choice=$(jq -r 'to_entries[] | select(.key != "none") | .value.label' "$OMARCHY_PATH/default/input-methods/presets.json" |
    gum choose --header "Select input language")
  method=$(jq -r --arg label "$choice" 'to_entries[] | select(.value.label == $label) | .key' "$OMARCHY_PATH/default/input-methods/presets.json")
fi

case "$method" in
  mozc | hangul | pinyin | chewing) ;;
  *) echo "Unknown input method: $method" >&2; exit 1 ;;
esac

mapfile -t packages < <(jq -r --arg method "$method" '.[$method].packages[]' "$OMARCHY_PATH/default/input-methods/presets.json")
omarchy-pkg-add "${packages[@]}"
omarchy-input-method configure "$method"
echo "Input method added. The default switch is Ctrl+Shift+Space or the Japanese/Korean input key; existing custom keys are preserved."
