#!/bin/bash
set -e

echo "🔨 Building Storybook LSP Extension..."

# Get the directory where this script lives
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
REPO_ROOT="$SCRIPT_DIR/.."

echo "📍 Working in: $SCRIPT_DIR"

# Build the LSP server
echo ""
echo "1️⃣  Building LSP server..."
cd "$REPO_ROOT"
cargo build --release --bin storybook-lsp

# Create bin directory in extension
echo ""
echo "2️⃣  Copying binary to extension..."
mkdir -p "$SCRIPT_DIR/bin"

# Detect platform and copy the appropriate binary
if [[ "$OSTYPE" == "darwin"* ]]; then
    cp "$REPO_ROOT/target/release/storybook-lsp" "$SCRIPT_DIR/bin/storybook-lsp"
    echo "   ✓ Copied macOS binary"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    cp "$REPO_ROOT/target/release/storybook-lsp" "$SCRIPT_DIR/bin/storybook-lsp"
    echo "   ✓ Copied Linux binary"
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
    cp "$REPO_ROOT/target/release/storybook-lsp.exe" "$SCRIPT_DIR/bin/storybook-lsp.exe"
    echo "   ✓ Copied Windows binary"
else
    echo "   ⚠️  Unknown platform: $OSTYPE"
    exit 1
fi

# Make it executable
chmod +x "$SCRIPT_DIR/bin/storybook-lsp"* 2>/dev/null || true

echo ""
echo "✅ Build complete!"
echo ""
echo "📦 Extension is ready at: $SCRIPT_DIR"
echo "🚀 To install in Zed:"
echo "   1. Open Zed"
echo "   2. Run: zed: install dev extension"
echo "   3. Select: $SCRIPT_DIR"
echo ""
echo "🧪 To test:"
echo "   1. Open a .sb file in Zed"
echo "   2. The LSP should activate automatically"
echo "   3. Try hovering over symbols to see rich information!"
echo ""
