#!/bin/bash
# Opens a new terminal, using the current terminal's working directory if focused window is a terminal

# Get focused window info from Sway
focused_info=$(swaymsg -t get_tree | jq -r '.. | select(.focused? == true) | {app_id: .app_id, name: .name}')
app_id=$(echo "$focused_info" | jq -r '.app_id')
window_name=$(echo "$focused_info" | jq -r '.name')

if [ "$app_id" = "org.wezfurlong.wezterm" ]; then
    # Match the Sway window title with wezterm's window_title to get the correct pane's cwd
    cwd=$(wezterm cli list --format json 2>/dev/null | jq -r --arg title "$window_name" '.[] | select(.window_title == $title) | .cwd' | head -n 1)

    if [ -n "$cwd" ] && [ "$cwd" != "null" ]; then
        # Remove file:// prefix and hostname (format: file://hostname/path)
        cwd=$(echo "$cwd" | sed 's|^file://[^/]*/|/|')

        if [ -d "$cwd" ]; then
            wezterm start --cwd "$cwd" &
            exit 0
        fi
    fi
fi

# Fallback: open terminal in home directory
wezterm &
