{#- Context variables: bundle_name, catalog, warehouse_id, databricks_profile, workspace_host -#}
#!/usr/bin/env bash
# {{ demo_title }} — Lakehouse Deployment
# Full lifecycle: validate → deploy → data gen → pipeline → ML → Genie
# Usage: ./scripts/deploy-lakehouse.sh [target] [--skip-to pipeline|ml|genie]
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Source environment
if [ -f "$SCRIPT_DIR/../.env" ]; then
  set -a; source "$SCRIPT_DIR/../.env"; set +a
fi

TARGET="${1:-dev}"
SKIP_TO="all"
PROFILE="${DATABRICKS_CONFIG_PROFILE:-{{ databricks_profile or 'DEFAULT' }}}"

# Parse --skip-to flag
for arg in "$@"; do
  case "$arg" in
    --skip-to=*) SKIP_TO="${arg#*=}" ;;
    --skip-to) shift; SKIP_TO="${2:-all}" ;;
  esac
done

JOB_PREFIX="{{ bundle_name | replace('-', '_') }}"

echo "========================================="
echo "Lakehouse Deploy: {{ bundle_name }} (${TARGET})"
echo "Profile: ${PROFILE}"
echo "Skip to: ${SKIP_TO}"
echo "========================================="

# Step 1: Validate & Deploy Bundle
echo ""
echo "=== Step 1: Validate & Deploy Bundle ==="
databricks bundle validate -t "$TARGET" --profile "$PROFILE"
databricks bundle deploy -t "$TARGET" --profile "$PROFILE"
echo "Bundle deployed."

# Step 2: Run Data Generation Job
if [ "$SKIP_TO" = "all" ]; then
  echo ""
  echo "=== Step 2: Run Data Generation Job ==="
  databricks bundle run -t "$TARGET" "${JOB_PREFIX}_data_generation" --profile "$PROFILE"
  echo "Data generation complete."
fi

# Step 3: Run DLT Pipeline
if [ "$SKIP_TO" = "all" ] || [ "$SKIP_TO" = "pipeline" ]; then
  echo ""
  echo "=== Step 3: Run DLT Pipeline ==="
  databricks bundle run -t "$TARGET" "${JOB_PREFIX}_dlt_pipeline" --profile "$PROFILE"
  echo "DLT pipeline complete."
fi

# Step 4: Run ML Training Job
if [ "$SKIP_TO" = "all" ] || [ "$SKIP_TO" = "pipeline" ] || [ "$SKIP_TO" = "ml" ]; then
  echo ""
  echo "=== Step 4: Run ML Training Job ==="
  databricks bundle run -t "$TARGET" "${JOB_PREFIX}_ml_training" --profile "$PROFILE"
  echo "ML training complete."
fi

# Step 5: Create Genie Space
if [ "$SKIP_TO" = "all" ] || [ "$SKIP_TO" = "genie" ]; then
  echo ""
  echo "=== Step 5: Create Genie Space ==="
  uv run python3 "$SCRIPT_DIR/setup-genie.py" --profile "$PROFILE" \
    || echo "Genie Space creation skipped (see above for details)"
fi

echo ""
echo "========================================="
echo "Lakehouse deployment complete!"
echo "========================================="
