#!/bin/bash
set -e

# Define paths
CLI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${CLI_DIR}/.." && pwd)"
DIST_DIR="${ROOT_DIR}/dist"

# Ensure dist directory exists
mkdir -p "${DIST_DIR}"

echo "Building GoodMem CLI using Docker for reproducible builds..."

# Determine Git commit and version
GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
echo "Git commit: $GIT_COMMIT"

# Determine version based on Git state
if ! git diff-index --quiet HEAD -- 2>/dev/null || [ -n "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then
    # Workspace has uncommitted changes or untracked files
    CLI_VERSION="dev-dirty-${GIT_COMMIT}"
    echo "Dirty workspace detected"
elif GIT_TAG=$(git describe --exact-match --tags HEAD 2>/dev/null); then
    # Current commit has a tag - use the tag as version
    CLI_VERSION="$GIT_TAG"
    echo "Found git tag: $GIT_TAG"
else
    # Clean workspace but no tag - use commit SHA
    CLI_VERSION="dev-${GIT_COMMIT}"
    echo "Clean workspace, no tag"
fi

echo "Determined version: $CLI_VERSION"

# Build the Docker image with version and commit info (tests run inside Docker)
docker build \
    --build-arg GIT_COMMIT="$GIT_COMMIT" \
    --build-arg CLI_VERSION="$CLI_VERSION" \
    -t goodmem-cli-builder \
    "${CLI_DIR}"

# Extract the binary from the Docker image
CONTAINER_ID=$(docker create goodmem-cli-builder)
docker cp "${CONTAINER_ID}:/goodmem" "${DIST_DIR}/goodmem"
docker rm "${CONTAINER_ID}"

# Set executable permissions
chmod +x "${DIST_DIR}/goodmem"

echo "Build complete! Binary available at: ${DIST_DIR}/goodmem"
echo "Try running: ${DIST_DIR}/goodmem version"