#!/bin/bash
# =============================================================================
# Multi-Slot Worktree Setup Script
# Generated by Traqr CLI for {{PROJECT_DISPLAY_NAME}}
# =============================================================================
#
# Creates a multi-slot worktree structure for parallel development.
#
# Usage: ./setup-worktrees.sh
#
# =============================================================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

PROJECT_PATH="{{REPO_PATH}}"
PROJECT_NAME="{{PROJECT_NAME}}"
WORKTREES_DIR="{{WORKTREES_PATH}}"

echo -e "${GREEN}Multi-Slot Worktree Setup for: $PROJECT_NAME${NC}"
echo "   Main repo: $PROJECT_PATH"
echo "   Worktrees: $WORKTREES_DIR"
echo ""

# Ensure we have a git repo with at least one commit
if [ ! -d "$PROJECT_PATH/.git" ] && [ ! -f "$PROJECT_PATH/.git" ]; then
    echo -e "${YELLOW}No git repo found. Initializing...${NC}"
    git init "$PROJECT_PATH"
    cd "$PROJECT_PATH"
    git commit --allow-empty -m "chore: initial commit (created by Traqr setup)"
elif ! git -C "$PROJECT_PATH" rev-parse HEAD >/dev/null 2>&1; then
    echo -e "${YELLOW}Git repo has no commits. Creating initial commit...${NC}"
    cd "$PROJECT_PATH"
    git commit --allow-empty -m "chore: initial commit (created by Traqr setup)"
fi

cd "$PROJECT_PATH"

# Create worktrees directory
mkdir -p "$WORKTREES_DIR"

# Define all slots: slot_name:branch_name
SLOTS=({{SLOT_BASH_ARRAY}})

echo -e "${BLUE}Creating ${#SLOTS[@]} worktree slots...${NC}"
echo ""

for slot_info in "${SLOTS[@]}"; do
    SLOT_NAME="${slot_info%%:*}"
    BRANCH="${slot_info##*:}"
    WT_PATH="$WORKTREES_DIR/$SLOT_NAME"

    if [ -d "$WT_PATH" ]; then
        echo -e "${YELLOW}Skipping $SLOT_NAME (already exists)${NC}"
    else
        echo -e "${GREEN}Creating $SLOT_NAME ($BRANCH)...${NC}"

        # Check if branch exists locally or remotely
        if git show-ref --verify --quiet "refs/heads/$BRANCH" || git show-ref --verify --quiet "refs/remotes/origin/$BRANCH"; then
            git worktree add "$WT_PATH" "$BRANCH" 2>/dev/null || git worktree add "$WT_PATH" -b "$BRANCH"
        else
            git worktree add "$WT_PATH" -b "$BRANCH"
        fi
    fi
done

echo ""

# Install pre-push guardrail hook
PRE_PUSH_SCRIPT="$PROJECT_PATH/scripts/pre-push-guardrail.sh"
MAIN_HOOKS_DIR="$PROJECT_PATH/.git/hooks"
if [ -f "$PRE_PUSH_SCRIPT" ]; then
    echo -e "${GREEN}Installing pre-push guardrail hook...${NC}"
    mkdir -p "$MAIN_HOOKS_DIR"
    cp "$PRE_PUSH_SCRIPT" "$MAIN_HOOKS_DIR/pre-push"
    chmod +x "$MAIN_HOOKS_DIR/pre-push"
    echo "   Installed in $MAIN_HOOKS_DIR/pre-push"
    echo "   Applies to all worktrees (shared hooks)"
    echo ""
else
    echo -e "${YELLOW}Warning: pre-push-guardrail.sh not found, skipping hook installation${NC}"
    echo ""
fi

# Symlink .env files
ENV_FILES=(".env.local" ".env" ".env.development.local")

for env_file in "${ENV_FILES[@]}"; do
    if [ -f "$PROJECT_PATH/$env_file" ]; then
        echo -e "${GREEN}Symlinking $env_file to all slots...${NC}"
        for slot_info in "${SLOTS[@]}"; do
            SLOT_NAME="${slot_info%%:*}"
            WT_PATH="$WORKTREES_DIR/$SLOT_NAME"
            if [ -d "$WT_PATH" ]; then
                ln -sf "$PROJECT_PATH/$env_file" "$WT_PATH/$env_file"
                echo "   $SLOT_NAME/$env_file"
            fi
        done
    fi
done

echo ""
echo -e "${GREEN}Setup complete!${NC}"
echo ""
echo "Slot Layout:"
echo ""
printf "  %-12s %-20s %-6s\n" "Slot" "Branch" "Port"
printf "  %-12s %-20s %-6s\n" "----------" "------------------" "----"

# Print slot table from config
{{SLOT_TABLE_PRINTF}}

echo ""
echo "Next steps:"
echo ""
echo "  If 'traqr init' already ran, your shell is configured."
echo "  Otherwise, add this to your ~/.zshrc or ~/.bashrc:"
echo ""
echo "     source ~/.traqr/shell-init.sh"
echo ""
echo "  Then reload your shell:"
echo "     source ~/.zshrc"
echo ""
echo "  Key commands:"
echo "     z1, z2, z3      Jump to feature slots"
echo "     zb1, zb2        Jump to bugfix slots"
echo "     zd1, zd2        Jump to devops slots"
echo "     c1, cb1, cd1    Open Claude in slot"
echo "     {{PREFIX}}-slots      Show all slot status"
echo "     {{PREFIX}}-sync       Sync all slots with main"
echo ""
echo "Pre-push guardrail installed:"
echo "  - Direct 'git push' is blocked in all slots"
echo "  - Use /ship in Claude Code to push changes"
echo ""
