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

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

BUILD_APP=false
BUILD_DMG=false
SKIP_TESTS=false
INSTALL=false

for arg in "$@"; do
  case "$arg" in
    --app) BUILD_APP=true ;;
    --dmg) BUILD_APP=true; BUILD_DMG=true ;;
    --skip-tests) SKIP_TESTS=true ;;
    --install) BUILD_APP=true; INSTALL=true ;;
    -h|--help)
      echo "Usage: $0 [--app] [--dmg] [--skip-tests] [--install]"
      echo "Builds target/release/posprint (and optionally Posprint.app / .dmg on macOS)."
      echo "  --app         also bundle target/macos/Posprint.app (registers posprint:// handler)"
      echo "  --dmg         also build target/macos/Posprint-<ver>-macos-<arch>.dmg (implies --app)"
      echo "  --install     install Posprint.app to /Applications and posprint CLI on PATH (implies --app)"
      echo "  --skip-tests  skip cargo test before building"
      echo "On a TTY, missing Rust toolchain is offered for automatic install."
      exit 0
      ;;
    *) echo "Unknown option: $arg"; exit 1 ;;
  esac
done

is_interactive() {
  [[ -t 0 ]]
}

ask_yes_no() {
  local prompt="$1"
  if ! is_interactive; then
    return 1
  fi
  local answer
  read -r -p "$prompt [y/N] " answer
  [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]]
}

want_install() {
  if [[ "$INSTALL" == "true" ]]; then
    return 0
  fi
  if ! is_interactive; then
    return 1
  fi
  ask_yes_no "Install Posprint.app to /Applications and posprint CLI now?"
}

# Make rustup / Homebrew toolchains visible when installed.
if [[ -f "$HOME/.cargo/env" ]]; then
  # shellcheck source=/dev/null
  source "$HOME/.cargo/env"
fi
if [[ -d "/opt/homebrew/bin" && ":$PATH:" != *":/opt/homebrew/bin:"* ]]; then
  export PATH="/opt/homebrew/bin:$PATH"
fi

ensure_rust() {
  if command -v cargo &>/dev/null && command -v rustc &>/dev/null; then
    return 0
  fi

  echo "cargo/rustc not found."
  if ask_yes_no "Install Rust via rustup now?"; then
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    # shellcheck source=/dev/null
    source "$HOME/.cargo/env"
  else
    echo "Install Rust from https://rustup.rs (or 'brew install rust'), then re-run."
    exit 1
  fi

  if ! command -v cargo &>/dev/null || ! command -v rustc &>/dev/null; then
    echo "Rust install finished but cargo/rustc still not on PATH. Open a new shell or: source \"\$HOME/.cargo/env\""
    exit 1
  fi
}

ensure_rust

ARCH="$(uname -m)"
echo "Building posprint for macOS ($ARCH)..."

if [[ "$SKIP_TESTS" != "true" ]]; then
  cargo test
fi

cargo build --release
BIN="$ROOT/target/release/posprint"
echo "OK: $BIN"
ls -lh "$BIN"

VERSION="$(grep '^version = ' "$ROOT/Cargo.toml" | head -n1 | tr -d '\r' | sed -E 's/.*"([^"]+)"/\1/')"

if [[ "$BUILD_APP" == "true" ]]; then
  APP_DIR="$ROOT/target/macos/Posprint.app"
  rm -rf "$APP_DIR"
  mkdir -p "$APP_DIR/Contents/MacOS" "$APP_DIR/Contents/Resources"

  # Compile native Cocoa launcher that handles posprint:// URLs, .pos files,
  # and direct app launches by spawning Contents/MacOS/posprint-bin.
  cc -O2 -framework Cocoa \
    -o "$APP_DIR/Contents/MacOS/posprint-launcher" \
    "$ROOT/packaging/macos/launcher.m"
  chmod +x "$APP_DIR/Contents/MacOS/posprint-launcher"

  cp "$BIN" "$APP_DIR/Contents/MacOS/posprint-bin"
  chmod +x "$APP_DIR/Contents/MacOS/posprint-bin"

  sed "s/@VERSION@/${VERSION}/g" "$ROOT/packaging/macos/Info.plist" > "$APP_DIR/Contents/Info.plist"

  # Build AppIcon.icns from pos-logo.png if sips and iconutil are available.
  if command -v sips &>/dev/null && command -v iconutil &>/dev/null && [[ -f "$ROOT/pos-logo.png" ]]; then
    ICONSET_DIR="$(mktemp -d /tmp/posprint-icon.XXXXXX.iconset)"
    for size in 16 32 128 256 512; do
      sips -z "$size" "$size" "$ROOT/pos-logo.png" --out "$ICONSET_DIR/icon_${size}x${size}.png" >/dev/null 2>&1 || true
      size2=$((size * 2))
      sips -z "$size2" "$size2" "$ROOT/pos-logo.png" --out "$ICONSET_DIR/icon_${size}x${size}@2x.png" >/dev/null 2>&1 || true
    done
    iconutil -c icns "$ICONSET_DIR" -o "$APP_DIR/Contents/Resources/AppIcon.icns" >/dev/null 2>&1 || true
    rm -rf "$ICONSET_DIR"
  fi

  codesign --force --deep --sign - "$APP_DIR"
  echo "macOS app bundle: $APP_DIR"

  if [[ "$BUILD_DMG" == "true" ]]; then
    DMG_PATH="$ROOT/target/macos/Posprint-${VERSION}-macos-${ARCH}.dmg"
    rm -f "$DMG_PATH"
    hdiutil create -volname "Posprint" -srcfolder "$APP_DIR" -ov -format UDZO "$DMG_PATH" >/dev/null
    echo "macOS disk image: $DMG_PATH"
    ls -lh "$DMG_PATH"
  fi

  if want_install; then
    echo "Installing Posprint.app to /Applications/Posprint.app..."
    rm -rf /Applications/Posprint.app
    cp -R "$APP_DIR" /Applications/Posprint.app
    codesign --force --deep --sign - /Applications/Posprint.app

    if [[ -d "/opt/homebrew/bin" && -w "/opt/homebrew/bin" ]]; then
      cp "$BIN" /opt/homebrew/bin/posprint
      echo "Installed CLI binary: /opt/homebrew/bin/posprint"
    elif [[ -d "/usr/local/bin" && -w "/usr/local/bin" ]]; then
      cp "$BIN" /opt/homebrew/bin/posprint
      echo "Installed CLI binary: /opt/homebrew/bin/posprint"
    fi

    LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
    if [[ -x "$LSREGISTER" ]]; then
      "$LSREGISTER" -f /Applications/Posprint.app || true
    fi
    echo "Installed and registered posprint:// URL handler."
  fi
fi
