#!/usr/bin/env bash
# Norwegian Handy instance (whisper-large-v3, language pinned to "no").
# Runs on a private D-Bus session bus so the tauri single-instance lock
# (D-Bus name com.pais.handy) doesn't collide with the main English
# instance, and with its own XDG_DATA_HOME for a separate settings store.
# Models are shared via ~/.cache/huggingface — no duplicate downloads.
#
# Usage: handy-no start | toggle | gui | cancel
set -euo pipefail

export XDG_DATA_HOME="$HOME/.local/share/handy-no"
export BUSFILE="$XDG_RUNTIME_DIR/handy-no.bus"

case "${1:-start}" in
start)
    # First run on a new machine: seed this instance's settings from the
    # main (English) store and apply the Norwegian overrides. The live
    # store stays out of git — Handy rewrites it at runtime and it can
    # hold API keys.
    NO_STORE="$XDG_DATA_HOME/com.pais.handy/settings_store.json"
    EN_STORE="$HOME/.local/share/com.pais.handy/settings_store.json"
    if [ ! -f "$NO_STORE" ] && [ -f "$EN_STORE" ]; then
        mkdir -p "${NO_STORE%/*}"
        python3 - "$EN_STORE" "$NO_STORE" <<'PY'
import json, sys
en, out = sys.argv[1:3]
d = json.load(open(en))
s = d["settings"]
s["selected_model"] = "handy-computer/whisper-large-v3-gguf/whisper-large-v3-Q5_K_M.gguf"
s["selected_language"] = "no"  # pinned: auto-detect mistakes Norwegian for Swedish
s["show_tray_icon"] = False
s["autostart_enabled"] = False  # hyprland autostarts this instance
s["onboarding_completed"] = True
s["post_process_api_keys"] = {k: "" for k in s.get("post_process_api_keys", {})}
json.dump(d, open(out, "w"), indent=2)
PY
    fi
    # Publish the private bus address so toggle/gui/cancel can reach
    # this instance through the single-instance forwarder.
    exec dbus-run-session -- sh -c \
        'echo "$DBUS_SESSION_BUS_ADDRESS" > "$BUSFILE"; exec handy --start-hidden --no-tray'
    ;;
toggle | gui | cancel)
    DBUS_SESSION_BUS_ADDRESS="$(cat "$BUSFILE")"
    export DBUS_SESSION_BUS_ADDRESS
    case "$1" in
    toggle) exec handy --toggle-transcription ;;
    cancel) exec handy --cancel ;;
    gui) exec handy ;;
    esac
    ;;
*)
    echo "usage: handy-no {start|toggle|gui|cancel}" >&2
    exit 2
    ;;
esac
