#!/usr/bin/env bash
# Attach this terminal to the Herdr workspace for the current directory.
# Resumes a terminal that no other herdr-here client is holding, or creates one.
set -euo pipefail

# The first run after a new version writes the Windows Terminal profiles.
# The version lives in pyproject.toml. verkit release bumps that file, and
# this script reads it back so the pane command does not start Python.
_herdr_here_version() {
  local script dir py meta
  script=$(readlink -f "${BASH_SOURCE[0]}")
  dir=$(dirname "$script")
  py="$dir/../../../pyproject.toml"
  if [[ -f "$py" && -f "$dir/../install.py" ]]; then
    sed -n 's/^version = "\([^"]*\)".*/\1/p' "$py" | head -n 1
    return 0
  fi
  meta=$(find "$dir/../lib" -path '*/herdr_here-*.dist-info/METADATA' -print -quit 2>/dev/null || true)
  if [[ -n "$meta" && -f "$meta" ]]; then
    awk -F': ' '/^Version: / { print $2; exit }' "$meta"
    return 0
  fi
  if command -v herdr-here-install >/dev/null 2>&1; then
    herdr-here-install --version
  fi
}
_herdr_here_setup_version=$(_herdr_here_version || true)
_herdr_here_stamp=${XDG_CONFIG_HOME:-$HOME/.config}/herdr/herdr-here-setup
if [[ -n "$_herdr_here_setup_version" ]]; then
  if [[ ! -f "$_herdr_here_stamp" ]] || [[ "$(< "$_herdr_here_stamp")" != "$_herdr_here_setup_version" ]]; then
    if command -v herdr-here-install >/dev/null 2>&1; then
      herdr-here-install
    fi
  fi
fi
unset -f _herdr_here_version
unset _herdr_here_setup_version _herdr_here_stamp

if [[ -x "$HOME/.local/share/mise/installs/herdr/latest/herdr" ]]; then
  HERDR="$HOME/.local/share/mise/installs/herdr/latest/herdr"
elif command -v herdr >/dev/null 2>&1; then
  HERDR=$(command -v herdr)
elif [[ -x "$HOME/.local/bin/herdr" ]]; then
  HERDR="$HOME/.local/bin/herdr"
else
  printf 'herdr-here: herdr is not installed.\n' >&2
  exit 1
fi
export HERDR

start=${1:-$PWD}
# C:\foo and C:/foo are Windows paths. Herdr runs in Debian, so convert them first.
if [[ "$start" =~ ^[A-Za-z]:[\\/] ]]; then
  if ! start=$(wslpath -u "$start"); then
    printf 'herdr-here: cannot convert Windows path: %s\n' "$1" >&2
    exit 1
  fi
fi
if [[ ! -d "$start" ]]; then
  printf 'herdr-here: not a directory: %s\n' "$start" >&2
  exit 1
fi
start=$(cd -- "$start" && pwd -P)
root=$start
if git -C "$start" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  root=$(cd -- "$(git -C "$start" rev-parse --show-toplevel)" && pwd -P)
fi
label=$(basename -- "$root")
export HERDR_ROOT=$root
export HERDR_LABEL=$label

# A reboot stops the server. herdr-here is the explicit request for a pane,
# so bring the default server up instead of making that a second command.
# This does not run from bashrc, and it does not open the dashboard.
ensure_server() {
  if "$HERDR" status server --json 2>/dev/null | grep -q '"running":true'; then
    return 0
  fi
  local log=${XDG_CONFIG_HOME:-$HOME/.config}/herdr/herdr-server.log
  printf 'herdr-here: starting Herdr\n' >&2
  # setsid keeps the server alive after this terminal attaches or closes.
  # Drop NO_COLOR and the other color-off switches. Panes inherit the server
  # environment, and a parent that disables color turns agent highlighting off.
  setsid env \
    -u NO_COLOR \
    CLICOLOR=1 \
    COLORTERM=truecolor \
    FORCE_COLOR=1 \
    TERM=xterm-256color \
    "$HERDR" server >>"$log" 2>&1 </dev/null &
  local pid=$!
  local _
  for _ in $(seq 1 75); do
    if "$HERDR" status server --json 2>/dev/null | grep -q '"running":true'; then
      return 0
    fi
    if ! kill -0 "$pid" 2>/dev/null; then
      printf 'herdr-here: Herdr exited while starting. See %s\n' "$log" >&2
      exit 1
    fi
    sleep 0.2
  done
  printf 'herdr-here: Herdr did not come up. See %s\n' "$log" >&2
  exit 1
}
ensure_server

lock_root=${XDG_CONFIG_HOME:-$HOME/.config}/herdr/wt-attach
mkdir -p -- "$lock_root"
chmod 700 "$lock_root"

# Remember which directory a workspace was opened for. The live pane cwd changes
# when the user cds, and that must not make the home workspace look like the new repo.
roots_dir=$lock_root/roots

record_root() {
  local workspace_id=$1
  [[ -n "$workspace_id" ]] || return 0
  mkdir -p -- "$roots_dir"
  local path=$roots_dir/$workspace_id
  if [[ ! -f "$path" ]]; then
    printf '%s\n' "$root" >"$path"
  fi
}

# Print "resume" or "created", then one "terminal_id workspace_id" line per hit.
pick_or_create() {
  python3 - "$HERDR_ROOT" "$HERDR_LABEL" "$roots_dir" <<'PY'
import json, os, subprocess, sys

root, label, roots_dir = sys.argv[1], sys.argv[2], sys.argv[3]
herdr = os.environ["HERDR"]

def run(args):
    proc = subprocess.run([herdr, *args], capture_output=True, text=True)
    text = (proc.stdout or "") + (proc.stderr or "")
    start = text.find("{")
    if proc.returncode != 0 or start < 0:
        sys.stderr.write(text or f"herdr {' '.join(args)} failed\n")
        sys.exit(proc.returncode or 1)
    return json.loads(text[start:])

def real(path):
    try:
        return os.path.realpath(path)
    except OSError:
        return path

def recorded(workspace_id):
    path = os.path.join(roots_dir, workspace_id)
    try:
        with open(path, encoding="utf-8") as handle:
            return handle.read().strip()
    except OSError:
        return ""

workspaces = run(["workspace", "list"]).get("result", {}).get("workspaces", [])
labels = {item.get("workspace_id"): item.get("label") or "" for item in workspaces}
panes = run(["pane", "list"]).get("result", {}).get("panes", [])
matched = []
seen = set()
for pane in panes:
    terminal_id = pane.get("terminal_id")
    workspace_id = pane.get("workspace_id")
    if not terminal_id or not workspace_id or terminal_id in seen:
        continue
    known = recorded(workspace_id)
    cwd = real(pane.get("cwd") or "")
    under = cwd == root or cwd.startswith(root + os.sep)
    if known:
        ok = known == root
    else:
        # Workspaces opened before the root file existed are matched by label.
        ok = labels.get(workspace_id) == label and under
    if not ok:
        continue
    seen.add(terminal_id)
    matched.append((terminal_id, workspace_id))

if matched:
    sys.stdout.write("resume\n")
    for terminal_id, workspace_id in matched:
        sys.stdout.write(f"{terminal_id} {workspace_id}\n")
    sys.exit(0)

args = [
    "workspace", "create",
    "--cwd", root,
    "--label", label,
    "--no-focus",
]
wt = os.environ.get("HERDR_WT")
if wt:
    args.extend(["--env", f"HERDR_WT={wt}"])
created = run(args)
result = created["result"]
terminal_id = result["root_pane"]["terminal_id"]
workspace_id = result["workspace"]["workspace_id"]
sys.stdout.write("created\n")
sys.stdout.write(f"{terminal_id} {workspace_id}\n")
PY
}

# Create another terminal in the workspace that already has this root.
create_in_workspace() {
  local workspace_id=$1
  python3 - "$workspace_id" "$HERDR_ROOT" "$HERDR_LABEL" <<'PY'
import json, os, subprocess, sys

workspace_id, root, label = sys.argv[1], sys.argv[2], sys.argv[3]
herdr = os.environ["HERDR"]
args = [herdr, "tab", "create", "--workspace", workspace_id, "--cwd", root, "--label", label, "--no-focus"]
wt = os.environ.get("HERDR_WT")
if wt:
    args.extend(["--env", f"HERDR_WT={wt}"])
proc = subprocess.run(args, capture_output=True, text=True)
text = (proc.stdout or "") + (proc.stderr or "")
start = text.find("{")
if proc.returncode != 0 or start < 0:
    sys.stderr.write(text or "herdr tab create failed\n")
    sys.exit(proc.returncode or 1)
data = json.loads(text[start:])
sys.stdout.write(data["result"]["root_pane"]["terminal_id"] + "\n")
PY
}

hold_lock() {
  local terminal_id=$1
  local path=$lock_root/${terminal_id}.lock
  exec 9>"$path"
  if flock -n 9; then
    return 0
  fi
  exec 9>&-
  return 1
}

release_lock() {
  flock -u 9 2>/dev/null || true
  exec 9>&- 2>/dev/null || true
}

# Sets terminal_id and workspace_id. Holds the terminal lock on success.
choose_terminal() {
  local row fallback_ws=""
  mapfile -t choice < <(pick_or_create)
  mode=${choice[0]:-}
  terminal_id=""
  workspace_id=""
  if [[ "$mode" == "resume" ]]; then
    for row in "${choice[@]:1}"; do
      [[ -n "$row" ]] || continue
      terminal_id=${row%% *}
      workspace_id=${row#* }
      record_root "$workspace_id"
      fallback_ws=$workspace_id
      if hold_lock "$terminal_id"; then
        return 0
      fi
    done
    if [[ -n "$fallback_ws" ]]; then
      terminal_id=$(create_in_workspace "$fallback_ws")
      workspace_id=$fallback_ws
      record_root "$workspace_id"
      hold_lock "$terminal_id"
      return $?
    fi
  elif [[ "$mode" == "created" ]]; then
    row=${choice[1]:-}
    terminal_id=${row%% *}
    workspace_id=${row#* }
    record_root "$workspace_id"
    hold_lock "$terminal_id"
    return $?
  fi
  return 1
}

# The Windows Terminal pane is the outside client. This loop stays alive so a
# later herdr-here, typed in the pane, can point that client at another workspace.
serve() {
  local terminal_id=$1
  local have_lock=1
  flock -u 8 2>/dev/null || true
  exec 8>&- 2>/dev/null || true
  printf '%s\n' "$$" >"$lock_root/loop.$$"
  trap 'rm -f "$lock_root/loop.$$" "$lock_root/switch.$$" "$lock_root/switch-label.$$"; if [[ -t 1 ]]; then printf "\033]0;\007"; fi' EXIT
  while true; do
    if [[ "$have_lock" != 1 ]]; then
      if ! hold_lock "$terminal_id"; then
        printf 'herdr-here: terminal %s is already attached.\n' "$terminal_id" >&2
        exit 1
      fi
    fi
    have_lock=0
    if [[ -t 1 && -n "${HERDR_LABEL:-}" ]]; then
      printf '\033]0;%s\007' "$HERDR_LABEL"
    fi
    set +e
    "$HERDR" terminal attach "$terminal_id"
    local status=$?
    set -e
    release_lock
    if [[ -s "$lock_root/switch.$$" ]]; then
      terminal_id=$(<"$lock_root/switch.$$")
      rm -f "$lock_root/switch.$$"
      if [[ -s "$lock_root/switch-label.$$" ]]; then
        HERDR_LABEL=$(<"$lock_root/switch-label.$$")
        rm -f "$lock_root/switch-label.$$"
      fi
      continue
    fi
    exit "$status"
  done
}

find_client() {
  local term=$1 pid ppid args
  while read -r pid ppid args; do
    if [[ "$args" == *"terminal attach ${term}"* ]]; then
      printf '%s %s\n' "$pid" "$ppid"
      return 0
    fi
  done < <(ps -eo pid=,ppid=,args=)
  return 1
}

# Already inside a pane: move this tab to the workspace for $root.
switch_tab() {
  local current_term="" current_ws="" current_label="" client="" parent=""
  read -r current_term current_ws current_label < <("$HERDR" pane current --pane "${HERDR_PANE_ID:-}" | python3 -c '
import json, sys
text = sys.stdin.read()
start = text.find("{")
if start < 0:
    sys.exit(0)
pane = json.loads(text[start:]).get("result", {}).get("pane", {})
print(pane.get("terminal_id") or "", pane.get("workspace_id") or "", end=" ")
')
  if [[ -n "$current_ws" ]]; then
    current_label=$("$HERDR" workspace get "$current_ws" | python3 -c '
import json, sys
text = sys.stdin.read()
start = text.find("{")
if start < 0:
    sys.exit(0)
ws = json.loads(text[start:]).get("result", {}).get("workspace", {})
print(ws.get("label") or "")
')
  fi
  local recorded=""
  if [[ -n "$current_ws" && -f "$roots_dir/$current_ws" ]]; then
    recorded=$(<"$roots_dir/$current_ws")
  fi
  if [[ "$recorded" == "$root" || ( -z "$recorded" && "$current_label" == "$label" ) ]]; then
    printf 'herdr-here: this tab is on %s\n' "$label"
    exit 0
  fi
  if ! choose_terminal; then
    printf 'herdr-here: could not choose a Herdr terminal.\n' >&2
    exit 1
  fi
  release_lock
  flock -u 8 2>/dev/null || true
  exec 8>&- 2>/dev/null || true
  if [[ -n "$current_term" ]] && read -r client parent < <(find_client "$current_term"); then
    if [[ -n "$parent" && -f "$lock_root/loop.$parent" ]]; then
      printf '%s\n' "$terminal_id" >"$lock_root/switch.$parent"
      printf '%s\n' "$label" >"$lock_root/switch-label.$parent"
      kill -TERM "$client"
      exit 0
    fi
  fi
  printf 'herdr-here: this tab is attached to %s.\n' "${current_label:-this workspace}" >&2
  printf 'herdr-here: open a new Debian Herdr tab and run herdr-here from %s.\n' "$label" >&2
  exit 1
}

exec 8>"$lock_root/create.lock"
flock 8

if [[ "${HERDR_ENV:-}" == "1" ]]; then
  switch_tab
fi

if ! choose_terminal; then
  printf 'herdr-here: could not choose a Herdr terminal.\n' >&2
  exit 1
fi
serve "$terminal_id"
