#!/usr/bin/env bash
# Build and push Docker image from project source.
#
# Usage:
#   ./scripts/docker-deploy.sh
#
# Custom build directory / registry / tag:
#   BUILD_DIR=/your/build/path \
#   IMAGE_REGISTRY=registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/external_demand \
#   BUILD_TIMESTAMP=20260717143000 \
#   ./scripts/docker-deploy.sh
#
# Environment variables:
#   BUILD_DIR        Source directory containing Dockerfile (default: repo root)
#   IMAGE_REGISTRY   Docker image repository
#   BUILD_TIMESTAMP  Image tag (default: YYYYMMDDHHMMSS)
#   PUSH             Push after build (default: true)
set -euo pipefail

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

BUILD_DIR="${BUILD_DIR:-$PROJECT_ROOT}"
IMAGE_REGISTRY="${IMAGE_REGISTRY:-registry-vpc.cn-hangzhou.aliyuncs.com/stuuudy/external_demand}"
BUILD_TIMESTAMP="${BUILD_TIMESTAMP:-$(date +%Y%m%d%H%M%S)}"
PUSH="${PUSH:-true}"

IMAGE_TAG="${IMAGE_REGISTRY}:${BUILD_TIMESTAMP}"
LATEST_TAG="${IMAGE_REGISTRY}:latest"

usage() {
  cat <<EOF
Usage: $(basename "$0") [options]

Options:
  --no-push    Build only, do not push to registry
  -h, --help   Show this help

Environment:
  BUILD_DIR        ${BUILD_DIR}
  IMAGE_REGISTRY   ${IMAGE_REGISTRY}
  BUILD_TIMESTAMP  ${BUILD_TIMESTAMP}
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-push)
      PUSH=false
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage
      exit 1
      ;;
  esac
done

echo "==> Building from: ${BUILD_DIR}"
echo "==> Image tag: ${IMAGE_TAG}"

cd "$BUILD_DIR"
docker build -t "$IMAGE_TAG" -t "$LATEST_TAG" .

echo "==> Verifying video truncate runtime in image"
docker run --rm --entrypoint python "$IMAGE_TAG" scripts/verify_video_truncate_runtime.py

echo "==> Verifying pipeline imports and migration head"
docker run --rm --entrypoint python "$IMAGE_TAG" -m compileall -q supply_infra api alembic
docker run --rm --entrypoint alembic "$IMAGE_TAG" heads

if [[ "$PUSH" == "true" ]]; then
  echo "==> Pushing: ${IMAGE_TAG}"
  docker push "$IMAGE_TAG"
  docker push "$LATEST_TAG"
else
  echo "==> Skipping push"
fi

echo "==> Done"
echo "    ${IMAGE_TAG}"
echo "    ${LATEST_TAG}"
