#!/usr/bin/env bash
# Regression: _human-session must not name a tmux session with a char tmux parses as a
# target separator ('.' or ':'). A dotted project dir (zync.is) otherwise creates a session
# that can never be attached ("can't find window: zync"), piling up detached orphans.
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="$HERE/../bin/_human-session"
PASS=0; FAIL=0
ok()  { PASS=$((PASS+1)); printf 'PASS %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

# 1. the source builds the name with a char class that excludes '.' and ':'
if grep -Eq 'NAME="\$\{NAME//\[\^A-Za-z0-9_-\]/_\}"' "$SCRIPT"; then
  ok "session-name sanitizer excludes tmux target metachars"
else
  bad "session-name sanitizer excludes tmux target metachars" "line not found or still allows . / :"
fi

# 2. behavioral proof against real tmux: dotted name is unattachable, sanitized name attaches
sanitize() { local n="$1"; printf '%s' "${n//[^A-Za-z0-9_-]/_}"; }
RAW_SOCK="probe-raw-$$"
SAN_SOCK="probe-san-$$"
raw="zync.is-081117"
san="$(sanitize "$raw")"
if [[ "$san" != *.* && "$san" != *:* ]]; then
  ok "sanitized dotted dir has no tmux metachar ($raw -> $san)"
else
  bad "sanitized dotted dir has no tmux metachar" "got $san"
fi

if command -v tmux >/dev/null 2>&1; then
  tmux -L "$RAW_SOCK" new-session -d -s "$raw" 'sleep 30' 2>/dev/null
  if tmux -L "$RAW_SOCK" has-session -t "$raw" 2>/dev/null; then
    bad "raw dotted name is unattachable (demonstrates the bug)" "tmux resolved the dotted target"
  else
    ok "raw dotted name is unattachable (demonstrates the bug)"
  fi
  tmux -L "$RAW_SOCK" kill-server 2>/dev/null

  tmux -L "$SAN_SOCK" new-session -d -s "$san" 'sleep 30' 2>/dev/null
  if tmux -L "$SAN_SOCK" has-session -t "$san" 2>/dev/null; then
    ok "sanitized name is attachable"
  else
    bad "sanitized name is attachable" "has-session failed for $san"
  fi
  tmux -L "$SAN_SOCK" kill-server 2>/dev/null
else
  ok "tmux not installed — skipped behavioral check"
fi

echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
