#!/bin/bash

# <swiftbar.hideAbout>true</swiftbar.hideAbout>

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:$PATH"
Q=/opt/homebrew/bin/quattle
[ -x "$Q" ] || Q="python3 $HOME/quattle/quattle.py"
PORT=8787
PY=/usr/bin/python3

say() {
  osascript -e "display notification \"$2\" with title \"$1\"" >/dev/null 2>&1
}

link_of() {
  $PY -c 'import json,sys
try:
    print(json.load(sys.stdin).get("link",""))
except ValueError:
    print("")'
}

choose_folder() {
  list=$($Q folders --json 2>/dev/null | $PY -c 'import json,sys
try:
    rows=json.load(sys.stdin).get("folders",[])
except ValueError:
    rows=[]
def esc(t): return t.replace("\\", "\\\\").replace("\"", "\\\"")
print(", ".join("\"%s\"" % esc(r["path"]) for r in sorted(rows, key=lambda r: r["path"].lower())))')
  top="Vault (root directory)"
  items="\"$top\""
  [ -n "$list" ] && items="$items, $list"
  pick=$(osascript -e "tell application \"System Events\" to activate" -e "set chosen to choose from list {$items} with title \"quattle\" with prompt \"Where should it land?\" default items {\"$top\"}" -e 'if chosen is false then return "CANCEL"' -e 'return item 1 of chosen' 2>/dev/null)
  case "$pick" in
    CANCEL|"") echo "CANCEL";;
    "$top") echo "";;
    *) echo "$pick";;
  esac
}

send_paths() {
  where="$1"; shift
  links=""; names=""
  for f in "$@"; do
    [ -z "$f" ] && continue
    [ -d "$f" ] && continue
    if [ -n "$where" ]; then out=$($Q put --json --path "$where" "$f" 2>/dev/null); else out=$($Q put --json "$f" 2>/dev/null); fi
    link=$(printf '%s' "$out" | link_of)
    [ -n "$link" ] && links="$links${links:+
}$link"
    [ -n "$out" ] && names="$names${names:+, }$(basename "$f")"
  done
  into=""
  [ -n "$where" ] && into=" into $where"
  if [ -n "$links" ]; then printf '%s' "$links" | pbcopy; say "quattle" "Uploaded $names$into. Link copied."
  elif [ -n "$names" ]; then say "quattle" "Uploaded $names$into"
  else say "quattle" "Upload failed"; fi
}

bridge_up() {
  curl -s -m 1 -X OPTIONS "http://127.0.0.1:$PORT/" -o /dev/null && return 0
  return 1
}

case "$1" in
  link)
    out=$($Q share "$2" --json 2>/dev/null | link_of)
    if [ -n "$out" ]; then printf '%s' "$out" | pbcopy; say "quattle" "Sharing link copied"; else say "quattle" "Could not mint a link"; fi
    exit 0;;
  get)
    name=$($Q ls --json 2>/dev/null | $PY -c 'import json,sys
want=sys.argv[1]
for r in json.load(sys.stdin):
    if r["id"]==want:
        print(r["name"]); break' "$2")
    [ -z "$name" ] && name="quattle-$2"
    target="$HOME/Downloads/$name"
    if [ -e "$target" ]; then
      base="${name%.*}"; ext="${name##*.}"; [ "$base" = "$name" ] && ext=""
      n=2; while [ -e "$HOME/Downloads/$base ($n)${ext:+.$ext}" ]; do n=$((n+1)); done
      target="$HOME/Downloads/$base ($n)${ext:+.$ext}"
    fi
    if $Q get "$2" -o "$target" >/dev/null 2>&1; then open -R "$target"; else say "quattle" "Download failed"; fi
    exit 0;;
  clip)
    text="$(pbpaste)"
    if [ -z "$text" ]; then say "quattle" "The clipboard is empty"; exit 0; fi
    name="Clipboard $(date '+%Y-%m-%d %H.%M').txt"
    out=$(printf '%s' "$text" | $Q put - --name "$name" --json 2>/dev/null)
    link=$(printf '%s' "$out" | link_of)
    if [ -n "$link" ]; then printf '%s' "$link" | pbcopy; say "quattle" "Uploaded $name. Link copied."
    elif [ -n "$out" ]; then say "quattle" "Uploaded $name"
    else say "quattle" "Upload failed"; fi
    exit 0;;
  secret)
    text="$(pbpaste)"
    if [ -z "$text" ]; then say "quattle" "The clipboard is empty"; exit 0; fi
    link=$(printf '%s' "$text" | $Q secret - --json 2>/dev/null | link_of)
    if [ -n "$link" ]; then printf '%s' "$link" | pbcopy; say "quattle" "Secret sealed. Link replaced the clipboard."; else say "quattle" "Could not seal the secret"; fi
    exit 0;;
  upload)
    picked=$(osascript -e 'set out to ""
tell application "System Events" to activate
set chosen to choose file with multiple selections allowed with prompt "Upload to quattle"
repeat with f in chosen
  set out to out & POSIX path of f & linefeed
end repeat
return out' 2>/dev/null)
    [ -z "$picked" ] && exit 0
    where=$(choose_folder)
    [ "$where" = "CANCEL" ] && exit 0
    paths=()
    while IFS= read -r f; do [ -n "$f" ] && paths+=("$f"); done <<< "$picked"
    send_paths "$where" "${paths[@]}"
    exit 0;;
  finder)
    picked=$(osascript -e 'set out to ""
tell application "Finder"
  repeat with f in (selection as alias list)
    set out to out & POSIX path of f & linefeed
  end repeat
end tell
return out' 2>/dev/null)
    if [ -z "$picked" ]; then say "quattle" "Select a file in Finder first"; exit 0; fi
    where=$(choose_folder)
    [ "$where" = "CANCEL" ] && exit 0
    paths=()
    while IFS= read -r f; do [ -n "$f" ] && paths+=("$f"); done <<< "$picked"
    send_paths "$where" "${paths[@]}"
    exit 0;;
  receive)
    label=$(osascript -e 'tell application "System Events" to activate
set answer to display dialog "Name for the receiving link" default answer "" with title "quattle"
return text returned of answer' 2>/dev/null)
    [ -z "$label" ] && exit 0
    link=$($Q receive --label "$label" --json 2>/dev/null | link_of)
    if [ -n "$link" ]; then printf '%s' "$link" | pbcopy; say "quattle" "Receiving link $label copied"; else say "quattle" "Could not make the link"; fi
    exit 0;;
  clipto)
    text="$(pbpaste)"
    if [ -z "$text" ]; then say "quattle" "The clipboard is empty"; exit 0; fi
    name="Clipboard $(date '+%Y-%m-%d %H.%M').txt"
    out=$(printf '%s' "$text" | $Q put - --name "$name" --path "$2" --json 2>/dev/null)
    link=$(printf '%s' "$out" | link_of)
    if [ -n "$link" ]; then printf '%s' "$link" | pbcopy; say "quattle" "Uploaded $name into $2. Link copied."
    elif [ -n "$out" ]; then say "quattle" "Uploaded $name into $2"
    else say "quattle" "Upload failed"; fi
    exit 0;;
  start)
    if ! bridge_up; then nohup $Q serve --port "$PORT" >/dev/null 2>&1 & sleep 2; fi
    exit 0;;
  mount)
    if ! bridge_up; then nohup $Q serve --port "$PORT" >/dev/null 2>&1 & sleep 2; fi
    osascript -e "mount volume \"http://localhost:$PORT\"" >/dev/null 2>&1 || open "http://localhost:$PORT"
    exit 0;;
  stop)
    pkill -f "quattle serve" 2>/dev/null; pkill -f "quattle.py serve" 2>/dev/null
    exit 0;;
esac

listing=$($Q ls --json 2>/dev/null)
if [ -z "$listing" ]; then
  echo " | sfimage=lock.slash"
  echo "---"
  echo "quattle is not signed in | sfimage=exclamationmark.triangle"
  echo "Run quattle login in Terminal | bash=/usr/bin/open param1=-a param2=Terminal terminal=false"
  echo "---"
  echo "Refresh | refresh=true"
  exit 0
fi

held=$(mktemp)
printf '%s' "$listing" > "$held"
tree=$(mktemp)
$Q folders --json > "$tree" 2>/dev/null
$PY - "$0" "$held" "$tree" <<'PYEOF'
import json, os, sys, time

me = sys.argv[1]
with open(sys.argv[2]) as handle:
    rows = json.load(handle)
os.unlink(sys.argv[2])
folders = []
try:
    with open(sys.argv[3]) as handle:
        folders = json.load(handle).get("folders", [])
except (OSError, ValueError):
    folders = []
try:
    os.unlink(sys.argv[3])
except OSError:
    pass
count = len(rows)
total = sum(int(r.get("size") or 0) for r in rows)

def human(n):
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024 or unit == "TB":
            return ("%d %s" % (n, unit)) if unit == "B" else ("%.1f %s" % (n, unit))
        n /= 1024.0

def clean(text):
    return text.replace("|", "\u2502").replace("\n", " ")

print(" | sfimage=lock")
print("---")
print("%d file%s, %s | sfimage=internaldrive" % (count, "" if count == 1 else "s", human(total)))
print("---")
rows.sort(key=lambda r: r.get("updatedAt") or 0, reverse=True)
print("Recent | sfimage=clock")
for r in rows[:12]:
    when = time.strftime("%d %b", time.localtime((r.get("updatedAt") or 0) / 1000))
    where = r.get("path") or ""
    label = clean(r["name"])
    sub = (where + "  " if where else "") + human(int(r.get("size") or 0)) + "  " + when
    print("--%s | size=13" % label)
    print("----%s | size=11 color=gray" % clean(sub))
    print('----Copy Sharing Link | bash="%s" param1=link param2=%s terminal=false' % (me, r["id"]))
    print('----Download to Downloads | bash="%s" param1=get param2=%s terminal=false' % (me, r["id"]))
if folders:
    print("Folders | sfimage=folder")
    for f in sorted(folders, key=lambda f: f["path"].lower()):
        n = int(f.get("files") or 0)
        print("--%s | size=13" % clean(f["path"]))
        print("----%d file%s | size=11 color=gray" % (n, "" if n == 1 else "s"))
        print('----Upload Clipboard Here | bash="%s" param1=clipto param2="%s" terminal=false refresh=true' % (me, clean(f["path"])))
print("---")
print('Upload File\u2026 | bash="%s" param1=upload terminal=false refresh=true sfimage=arrow.up.doc' % me)
print('Upload Finder Selection | bash="%s" param1=finder terminal=false refresh=true sfimage=macwindow' % me)
print('Upload Clipboard | bash="%s" param1=clip terminal=false refresh=true sfimage=doc.on.clipboard' % me)
print('---')
print('New Receiving Link\u2026 | bash="%s" param1=receive terminal=false sfimage=tray.and.arrow.down' % me)
print('Seal Clipboard as Secret | bash="%s" param1=secret terminal=false sfimage=flame' % me)
PYEOF

echo "---"
if bridge_up; then
  echo "Finder bridge is running | sfimage=checkmark.circle"
  echo "Mount Vault in Finder | bash=\"$0\" param1=mount terminal=false sfimage=externaldrive"
  echo "Stop the Bridge | bash=\"$0\" param1=stop terminal=false refresh=true sfimage=stop.circle"
else
  echo "Finder bridge is not running | sfimage=circle"
  echo "Mount Vault in Finder | bash=\"$0\" param1=mount terminal=false refresh=true sfimage=externaldrive"
fi
echo "---"
echo "Open quattle | href=https://quattle.app sfimage=safari"
echo "Refresh | refresh=true sfimage=arrow.clockwise"
