{#- Context variables: app_name, catalog, warehouse_id, databricks_profile, workspace_host -#}
#!/usr/bin/env bash
# {{ demo_title }} — App Deployment
# Full app lifecycle: build → bundle deploy → bundle run → permissions
# Usage: ./scripts/deploy-app.sh [target]
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}"
PROFILE="${DATABRICKS_CONFIG_PROFILE:-{{ databricks_profile or 'DEFAULT' }}}"
APP_NAME="${APP_NAME:-{{ app_name }}}"
WAREHOUSE_ID="${DATABRICKS_SQL_WAREHOUSE_ID:-{{ warehouse_id }}}"
CATALOG="${CATALOG:-{{ catalog }}}"

# Schemas to grant access to — Claude updates this list after planning
SCHEMAS=("default")

TMP_SQL=$(mktemp)
trap "rm -f $TMP_SQL" EXIT

# Helper: run a SQL statement via the warehouse
run_sql() {
  local stmt="$1"
  python3 -c "
import json, sys
payload = json.dumps({
    'statement': sys.argv[1],
    'warehouse_id': sys.argv[2],
    'wait_timeout': '30s',
})
sys.stdout.write(payload)
" "$stmt" "$WAREHOUSE_ID" > "$TMP_SQL"
  databricks api post /api/2.0/sql/statements/ \
    --json @"$TMP_SQL" \
    --profile "$PROFILE" 2>&1 | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    status = d.get('status', {})
    if status.get('state') == 'FAILED':
        err = status.get('error', {}).get('message', 'unknown error')
        print(f'  SQL error: {err}', file=sys.stderr)
        sys.exit(1)
except (json.JSONDecodeError, KeyError):
    pass
"
}

echo "========================================="
echo "App Deploy: ${APP_NAME} (${TARGET})"
echo "========================================="

# The app has its own databricks.yml — separate from the root lakehouse bundle.
APP_DIR="$SCRIPT_DIR/../apps/${APP_NAME}"
if [ ! -d "$APP_DIR" ]; then
  APP_DIR="$SCRIPT_DIR/../apps/main-app"
fi

# Step 1: Build frontend + Python wheel
echo ""
echo "=== Step 1: Build frontend + Python wheel ==="
cd "$APP_DIR"
apx build
cd "$SCRIPT_DIR/.."
echo "Build complete."

# Step 2: Deploy app bundle (upload to workspace)
echo ""
echo "=== Step 2: Deploy app bundle ==="
cd "$APP_DIR"
databricks bundle deploy -t "$TARGET" --profile "$PROFILE"
cd "$SCRIPT_DIR/.."
echo "App bundle deployed."

# Step 3: Deploy app via bundle run
# 'bundle run' handles the full app deployment lifecycle — it uploads the
# source code and triggers the deployment, avoiding the "active deployment
# in progress" issue that 'apps deploy' has after fresh app creation.
echo ""
echo "=== Step 3: Deploy app ==="
APP_RESOURCE_KEY=$(cd "$APP_DIR" && databricks bundle validate -t "$TARGET" --output json --profile "$PROFILE" \
  | python3 -c "
import sys, json
apps = json.load(sys.stdin).get('resources', {}).get('apps', {})
for key in apps:
    print(key); break
" 2>/dev/null || echo "")

if [ -n "$APP_RESOURCE_KEY" ]; then
  cd "$APP_DIR"
  databricks bundle run -t "$TARGET" "$APP_RESOURCE_KEY" --profile "$PROFILE"
  cd "$SCRIPT_DIR/.."
  echo "App deployed."
else
  echo "WARNING: Could not determine app resource key from bundle."
  echo "You can deploy manually: cd $APP_DIR && databricks bundle run -t $TARGET <app-resource-key>"
fi

# Step 4: Get app service principal
echo ""
echo "=== Step 4: Get app service principal ==="
SP_CLIENT_ID=$(databricks apps get "$APP_NAME" --profile "$PROFILE" \
  --output json 2>/dev/null \
  | python3 -c "import sys,json; print(json.load(sys.stdin).get('service_principal_client_id',''))" 2>/dev/null || true)

if [ -z "$SP_CLIENT_ID" ]; then
  echo "WARNING: Could not retrieve service principal client ID."
  echo "You may need to grant permissions manually."
  exit 0
fi
echo "App SP Client ID: $SP_CLIENT_ID"

# Step 5: Grant SQL Warehouse access
echo ""
echo "=== Step 5: Grant SQL Warehouse access ==="
databricks api patch "/api/2.0/permissions/sql/warehouses/$WAREHOUSE_ID" \
  --json "{\"access_control_list\": [{\"service_principal_name\": \"$SP_CLIENT_ID\", \"permission_level\": \"CAN_USE\"}]}" \
  --profile "$PROFILE" > /dev/null 2>&1 \
  && echo "  Granted CAN_USE on warehouse $WAREHOUSE_ID" \
  || echo "  WARNING: Failed to grant warehouse permission"

# Step 6: Grant Unity Catalog access
echo ""
echo "=== Step 6: Grant Unity Catalog access ==="
run_sql "GRANT USE CATALOG ON CATALOG $CATALOG TO \`$SP_CLIENT_ID\`" \
  && echo "  GRANT USE CATALOG on $CATALOG" \
  || echo "  WARNING: Failed to grant USE CATALOG"

for schema in "${SCHEMAS[@]}"; do
  run_sql "GRANT USE SCHEMA ON SCHEMA $CATALOG.$schema TO \`$SP_CLIENT_ID\`"
  run_sql "GRANT SELECT ON SCHEMA $CATALOG.$schema TO \`$SP_CLIENT_ID\`"
  echo "  GRANT USE SCHEMA + SELECT on $CATALOG.$schema"
done

echo ""
echo "========================================="
echo "App deployment complete!"
echo "========================================="
