#!/bin/bash

# shellcheck shell=bash

# Create worktree
bridge_create_worktree() {
  if [[ -z "${1:-}" ]]; then
    json_error "Branch name required"
    return 1
  fi
  branch_name="$1"
  
  if git_require_repo_root >/dev/null 2>&1; then
    worktree_path="$(git_create_branch_and_worktree "$branch_name")"
    
    source_path="$(git_repo_root)"
    target_path="$worktree_path"
    shared_root="$(cd "$source_path" 2>/dev/null && git rev-parse --git-common-dir 2>/dev/null || echo "")"
    if [[ -n "$shared_root" ]]; then
      if [[ "$shared_root" != /* ]]; then
        shared_root="$(cd "$source_path" 2>/dev/null && pwd -P)/$shared_root"
      fi
      shared_root="$(dirname "$shared_root")"
    else
      shared_root="$(cd "$source_path" 2>/dev/null && git rev-parse --show-toplevel 2>/dev/null || printf '%s' "$source_path")"
    fi

    local env_copy_bin
    if ! env_copy_bin="$(gw_env_copy_bin)"; then
      json_error "gw-env-copy binary not found"
      return 1
    fi

    "$env_copy_bin" --source "$source_path" --target "$target_path" --repo "$shared_root" --format boolean --quiet >/dev/null
    
    echo "\"$worktree_path\""
  else
    json_error "Not a git repository"
  fi
}
