#!/bin/bash
# summary: Open Files at a folder or selected file.
# starchaser files: opens the file manager. Super+E, the menu's Files row and folder rows, and the taskbar's Files
# all open it through here.
#
#   starchaser files            bring up the Files window on this desktop, or open one when it has none
#   starchaser files FOLDER     open FOLDER in a tab on this desktop
#   starchaser files --which    print which one opens: "flea PRESET" (the key preset Files uses: default, vim, mac
#                               or windows) or "thunar"; the Super+K sheet and Settings show that one's keys
#
# Files is the flea program, the folder handler Starchaser sets for every account (decided 2026-11-08 #45). Thunar
# opens instead for an account that ran `flea --default off` (and `flea --default` takes it back), or without flea.
# A second Super+E reuses the Files window already open on the current desktop (decided 2026-11-09 #48); a new
# one is the menu's New window or Ctrl+N. Folder requests use the window's addressed tab IPC.
case "${1:-}" in -h|--help)
    sed -n '3,12p' "$0" | sed 's/^# \{0,1\}//'
    exit 0 ;;
esac

# The address of the Files window on the current desktop, the most recently used first; nothing when there is
# none, or no compositor to ask.
open_files_window() {
    [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] || return 0
    python3 -I - "$(timeout 2 hyprctl -j activeworkspace 2>/dev/null)" "$(timeout 2 hyprctl -j clients 2>/dev/null)" <<'PY' 2>/dev/null
import json, re, sys
try:
    here = json.loads(sys.argv[1])["id"]
    clients = json.loads(sys.argv[2])
except Exception:
    sys.exit(0)
files = [c for c in clients if isinstance(c, dict) and c.get("class") == "com.thisisgm.flea"
         and c.get("mapped", True) and not c.get("hidden") and (c.get("workspace") or {}).get("id") == here]
files.sort(key=lambda c: c.get("focusHistoryID", 1 << 30) if c.get("focusHistoryID", -1) >= 0 else 1 << 30)
if files and re.fullmatch(r"0x[0-9a-fA-F]+", str(files[0].get("address"))):
    print(files[0]["address"])
PY
}

# Focus the window at address $1 only where, asked inside the compositor in the same evaluation, it is still a Files
# window that is shown on the current desktop: one moved to another desktop since it was chosen is left alone, since
# focusing it would switch desktops. Focusing moves the keyboard, never the pointer (no_warps stays on in hyprland.lua).
focus_here() {
    hyprctl eval "local want = (string.lower('$1'):gsub('^0x', ''))
local m = hl.get_active_monitor()
local here = m and m.active_workspace and m.active_workspace.id
for _, w in ipairs(hl.get_windows()) do
    if here and (tostring(w.address):lower():gsub('^0x', '')) == want and w.class == 'com.thisisgm.flea'
        and w.mapped and not w.hidden and w.workspace and w.workspace.id == here then
        -- The shared helper moves covering Starchaser windows aside before focusing a tiled app.
        if StarchaserWin and StarchaserWin.show then StarchaserWin.show(w.address) end
        -- A stale lookup in the shared helper can leave another app focused. Recheck the desktop before
        -- dispatching directly so this fallback cannot follow a window that moved away.
        local now = hl.get_active_monitor()
        local active = hl.get_active_window()
        if now and now.active_workspace and now.active_workspace.id == here
            and w.mapped and not w.hidden and w.workspace and w.workspace.id == here
            and (not active or (tostring(active.address):lower():gsub('^0x', '')) ~= want) then
            hl.dispatch(hl.dsp.focus({ window = 'address:' .. w.address }))
        end
        break
    end
end" >/dev/null 2>&1
}

# Whether the window at address $1 has the keyboard now, on the current desktop.
focused_here() {
    python3 -I - "$1" "$(timeout 2 hyprctl -j activewindow 2>/dev/null)" "$(timeout 2 hyprctl -j activeworkspace 2>/dev/null)" <<'PY' 2>/dev/null
import json, sys
try:
    active = json.loads(sys.argv[2])
    here = json.loads(sys.argv[3])["id"]
except Exception:
    sys.exit(1)
ok = isinstance(active, dict) and active.get("address") == sys.argv[1] and (active.get("workspace") or {}).get("id") == here
sys.exit(0 if ok else 1)
PY
}

# Flea's own rule for its key preset: "keys" in its state file, and Default when the file or the name is missing,
# unreadable or unknown.
flea_preset() {
    python3 -I - "${XDG_STATE_HOME:-$HOME/.local/state}/flea/ui.json" 2>/dev/null <<'PY' || echo default
import json, sys
try:
    with open(sys.argv[1], encoding="utf-8") as f:
        keys = json.load(f).get("keys")
except Exception:
    keys = None
print(keys if keys in ("default", "vim", "mac", "windows") else "default")
PY
}

if [ "$(xdg-mime query default inode/directory 2>/dev/null)" = com.thisisgm.flea.desktop ] && command -v flea >/dev/null 2>&1; then
    [ "${1:-}" = --which ] && { echo "flea $(flea_preset)"; exit 0; }
    # The window list can change while this runs (a window moved to another desktop, or closed): a window counts as
    # reused only once it has the keyboard on this desktop; the list is read again once, then a new window opens.
    if [ $# -le 1 ] && [[ ${1:-} != --* ]]; then
        for _ in 1 2; do
            address=$(open_files_window)
            [ -n "$address" ] || break
            focus_here "$address"
            if focused_here "$address"; then
                if [ $# -eq 0 ]; then exit 0; fi
                case "$1" in
                    smb://*|sftp://*|ftp://*|dav://*|davs://*|afp://*|nfs://*) folder=$1 ;;
                    *) folder=$(realpath -e -- "$1" 2>/dev/null) || break; [ -d "$folder" ] || break ;;
                esac
                pid=$(hyprctl -j clients | python3 -I -c 'import json,sys; print(next((c["pid"] for c in json.load(sys.stdin) if c.get("address")==sys.argv[1] and isinstance(c.get("pid"),int)), ""))' "$address")
                if [[ $pid =~ ^[1-9][0-9]*$ ]] && [ "$(flea ipc --pid "$pid" call flea openFolderTab "$folder" 2>/dev/null)" = true ]; then exit 0; fi
            fi
        done
    fi
    if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/starchaser/permissions.json" ]; then
        exec starchaser app permissions command com.thisisgm.flea -- flea --gui "$@"
    fi
    exec flea --gui "$@"
fi
[ "${1:-}" = --which ] && { echo thunar; exit 0; }
if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/starchaser/permissions.json" ]; then
    exec starchaser app permissions command thunar -- thunar "$@"
fi
exec thunar "$@"
