#!/bin/bash
# build.sh - Cross-platform build script for DBML Language Server

set -e

echo "Building DBML Language Server..."

# Build for current platform
cargo build --release

# Create distribution directory
mkdir -p dist/server

# Copy binary for current platform
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    cp target/release/dbml-lsp dist/server/dbml-lsp-x86_64-unknown-linux-gnu
    echo "✓ Built for Linux x86_64"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    if [[ $(uname -m) == "arm64" ]]; then
        cp target/release/dbml-lsp dist/server/dbml-lsp-aarch64-apple-darwin
        echo "✓ Built for macOS ARM64"
    else
        cp target/release/dbml-lsp dist/server/dbml-lsp-x86_64-apple-darwin
        echo "✓ Built for macOS x86_64"
    fi
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
    cp target/release/dbml-lsp.exe dist/server/dbml-lsp.exe
    echo "✓ Built for Windows"
fi

echo "Build complete! Binaries are in dist/server/"

# Optional: Cross-compile for other platforms
# Requires cross to be installed: cargo install cross
read -p "Do you want to cross-compile for other platforms? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Installing cross if not present..."
    cargo install cross --quiet || true

    echo "Cross-compiling for Linux x86_64..."
    cross build --release --target x86_64-unknown-linux-gnu
    cp target/x86_64-unknown-linux-gnu/release/dbml-lsp dist/server/dbml-lsp-x86_64-unknown-linux-gnu

    echo "Cross-compiling for macOS x86_64..."
    cross build --release --target x86_64-apple-darwin || echo "⚠ macOS x86_64 cross-compile failed"

    echo "Cross-compiling for macOS ARM64..."
    cross build --release --target aarch64-apple-darwin || echo "⚠ macOS ARM64 cross-compile failed"

    echo "Cross-compiling for Windows..."
    cross build --release --target x86_64-pc-windows-msvc || echo "⚠ Windows cross-compile failed"

    echo "✓ Cross-compilation complete!"
fi

# Build VS Code extension if requested
read -p "Do you want to build the VS Code extension? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Building VS Code extension..."
    cd vscode-extension
    npm install
    npm run compile
    npm run package
    mv *.vsix ../dist/
    cd ..
    echo "✓ VS Code extension built!"
fi

echo ""
echo "==================================="
echo "Build Summary:"
echo "==================================="
echo "Server binaries: dist/server/"
if [ -f dist/*.vsix ]; then
    echo "VS Code extension: dist/*.vsix"
fi
echo ""
echo "To install the server manually:"
echo "  1. Copy the appropriate binary to your PATH"
echo "  2. Make it executable: chmod +x dbml-lsp"
echo ""
echo "To install the VS Code extension:"
echo "  code --install-extension dist/*.vsix"
