#!/usr/bin/env bash
set -euo pipefail

APP_NAME="chatgpt-image"
SOURCE_URL="${CHATGPT_IMAGE_SOURCE_URL:-https://wezen.tech/downloads/chatgpt-image-cli-source.tar.gz}"
INSTALL_DIR="${CHATGPT_IMAGE_INSTALL_DIR:-$HOME/.local/bin}"

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "This installer currently supports macOS only."
  exit 1
fi

for command_name in curl tar swift; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    echo "Missing required command: $command_name"
    exit 1
  fi
done

temp_dir="$(mktemp -d)"
cleanup() {
  rm -rf "$temp_dir"
}
trap cleanup EXIT

echo "Downloading $APP_NAME source bundle..."
curl -fsSL "$SOURCE_URL" -o "$temp_dir/chatgpt-image-cli-source.tar.gz"

echo "Extracting source bundle..."
tar -xzf "$temp_dir/chatgpt-image-cli-source.tar.gz" -C "$temp_dir"

package_path="$temp_dir/tools/chatgpt-image-cli"
if [[ ! -f "$package_path/Package.swift" ]]; then
  echo "Unexpected archive layout. Expected Swift package at $package_path"
  exit 1
fi

echo "Building $APP_NAME..."
swift build -c release --package-path "$package_path"

mkdir -p "$INSTALL_DIR"
cp "$package_path/.build/release/$APP_NAME" "$INSTALL_DIR/$APP_NAME"
chmod 755 "$INSTALL_DIR/$APP_NAME"

cat <<EOF

Installed $APP_NAME to:
  $INSTALL_DIR/$APP_NAME

If $INSTALL_DIR is not already in your PATH, add:
  export PATH="$INSTALL_DIR:\$PATH"

Before first use, Safari must allow JavaScript automation:
1. Open Safari.
2. Go to Safari > Settings > Advanced.
3. Turn on "Show features for web developers".
4. Go to Safari > Settings > Developer.
5. Turn on "Allow JavaScript from Apple Events".

Then run:
  $APP_NAME --help
EOF
