#!/usr/bin/env bash
# Apply the Home layout (Base/Yazi/Aerc tabs in /home/liph) and the Dotfiles
# workspace (yazi in ~/dotfiles + lazygit split to the right).
set -euo pipefail

SPREADER="$HOME/.config/herdr/plugins/github/herdr-spreader-f248c87aa2e2/target/release/herdr-spreader"
CONFIG_DIR="$HOME/.config/herdr/plugins/config/herdr-spreader"
TARGET_DIR="$(realpath ~/dotfiles)"

# Close any existing versions of these workspaces so this is idempotent.
herdr workspace close Home 2>/dev/null || true
herdr workspace close Dotfiles 2>/dev/null || true

# Apply the layout file, which creates both workspaces.
"$SPREADER" apply --file "$CONFIG_DIR/home.yml"

# Focus the Dotfiles workspace.
herdr workspace focus Dotfiles 2>/dev/null || true

# Wait briefly for the focus to settle on the new yazi pane in ~/dotfiles.
for _ in {1..30}; do
  current_json=$(herdr pane current 2>/dev/null || true)
  pane_cwd=$(echo "$current_json" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(d['result']['pane'].get('cwd', ''))
except Exception:
    print('')
" 2>/dev/null || true)
  if [ "$pane_cwd" = "$TARGET_DIR" ]; then
    break
  fi
  sleep 0.1
done

# Open lazygit via the plugin action. Because the yazi pane in ~/dotfiles is focused,
# lazygit will split to the right and target the dotfiles repository.
herdr plugin action invoke herdr-lazygit.open
