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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DERIVED_BASE="$ROOT_DIR/.deriveddata"

log() {
  printf '[setup] %s\n' "$1"
}

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required command: $1" >&2
    exit 1
  fi
}

require_cmd xcodebuild
require_cmd xcrun

log "Using developer dir: $(xcode-select -p)"
log "Xcode version: $(xcodebuild -version | tr '\n' ' ' | sed 's/  */ /g')"

if xcrun --find metal >/dev/null 2>&1; then
  METAL_BIN="$(xcrun --find metal)"
  if "$METAL_BIN" -v >/dev/null 2>&1; then
    log "Metal toolchain is ready: $METAL_BIN"
  else
    log "Metal toolchain is not ready, downloading component..."
    xcodebuild -downloadComponent MetalToolchain
    if ! "$METAL_BIN" -v >/dev/null 2>&1; then
      echo "Metal toolchain is still unavailable. Run Xcode once and retry." >&2
      exit 1
    fi
    log "Metal toolchain installed successfully."
  fi
else
  log "metal command is missing, downloading component..."
  xcodebuild -downloadComponent MetalToolchain
fi

mkdir -p "$DERIVED_BASE/objc" "$DERIVED_BASE/swift"
log "DerivedData folders prepared under $DERIVED_BASE"

xcodebuild -project "$ROOT_DIR/QGVAPlayer/QGVAPlayer.xcodeproj" -list >/dev/null
xcodebuild -project "$ROOT_DIR/QGVAPlayerDemo/QGVAPlayerDemo.xcodeproj" -list >/dev/null
xcodebuild -project "$ROOT_DIR/QGVAPlayerDemoSwift/QGVAPlayerDemoSwift.xcodeproj" -list >/dev/null

log "SDK dev environment check complete."
log "Next: run scripts/dev/build_demo.sh all"
