#!/usr/bin/env bash
# Build Python backend as standalone binary using PyInstaller
# Usage: ./scripts/build-backend.sh [target-triple]
# Example: ./scripts/build-backend.sh aarch64-apple-darwin

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TARGET_TRIPLE="${1:-}"

# Detect platform triple if not provided
if [ -z "$TARGET_TRIPLE" ]; then
    OS="$(uname -s)"
    ARCH="$(uname -m)"
    case "$OS" in
        Darwin)
            if [ "$ARCH" = "arm64" ]; then
                TARGET_TRIPLE="aarch64-apple-darwin"
            else
                TARGET_TRIPLE="x86_64-apple-darwin"
            fi
            ;;
        Linux)
            TARGET_TRIPLE="x86_64-unknown-linux-gnu"
            ;;
        MINGW*|MSYS*|CYGWIN*)
            TARGET_TRIPLE="x86_64-pc-windows-msvc"
            ;;
        *)
            echo "Unsupported OS: $OS"
            exit 1
            ;;
    esac
fi

echo "Building agentkit-server for $TARGET_TRIPLE..."

cd "$PROJECT_ROOT"

# Install PyInstaller if not present
pip install pyinstaller 2>/dev/null || pip3 install pyinstaller 2>/dev/null

# Build the binary
BINARY_NAME="agentkit-server"
if [[ "$TARGET_TRIPLE" == *"-windows-"* ]]; then
    BINARY_NAME="agentkit-server.exe"
fi

pyinstaller --onefile \
    --name "$BINARY_NAME" \
    --hidden-import agentkit.server \
    --hidden-import agentkit.server.app \
    --hidden-import agentkit.server.routes \
    --hidden-import agentkit.server.config \
    --hidden-import agentkit.cli.main \
    --hidden-import uvicorn.logging \
    --hidden-import uvicorn.lifespan.on \
    --hidden-import uvicorn.lifespan.off \
    --hidden-import uvicorn.protocols.websockets.auto \
    --hidden-import uvicorn.protocols.http.auto \
    --hidden-import uvicorn.protocols.websockets.wsproto_impl \
    --hidden-import uvicorn.protocols.websockets.websockets_impl \
    --hidden-import uvicorn.protocols.websockets.impl_11 \
    --hidden-import uvicorn.lifespan \
    --hidden-import sse_starlette \
    --distpath "$PROJECT_ROOT/src-tauri/binaries" \
    --workpath "$PROJECT_ROOT/build/pyinstaller-work" \
    --specpath "$PROJECT_ROOT/build" \
    src/agentkit/__main__.py

# Rename with target triple suffix (Tauri sidecar convention)
if [[ "$TARGET_TRIPLE" != *"-windows-"* ]]; then
    mv "$PROJECT_ROOT/src-tauri/binaries/$BINARY_NAME" \
       "$PROJECT_ROOT/src-tauri/binaries/agentkit-server-$TARGET_TRIPLE"
else
    mv "$PROJECT_ROOT/src-tauri/binaries/$BINARY_NAME" \
       "$PROJECT_ROOT/src-tauri/binaries/agentkit-server-$TARGET_TRIPLE.exe"
fi

echo "Built: src-tauri/binaries/agentkit-server-$TARGET_TRIPLE"
