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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BARON_DIR="${BARON_SSO_WORKTREE:-/home/ubuntu/workspace/baron-sso-tdc114plus-api}"
SOURCE_FILE="$BARON_DIR/.env.sample"
TARGET_FILE="$BARON_DIR/.env"

if [ ! -f "$SOURCE_FILE" ]; then
  echo "Baron SSO env sample not found: $SOURCE_FILE" >&2
  exit 1
fi

if [ -f "$TARGET_FILE" ]; then
  echo "Target env file already exists: $TARGET_FILE" >&2
  echo "Remove or rename it first if you want to regenerate from the sample." >&2
  exit 1
fi

cp "$SOURCE_FILE" "$TARGET_FILE"

cat >>"$TARGET_FILE" <<'EOF'

# --- tdc114plus local smoke overrides ---
# Added by scripts/bootstrap-baron-api-env.sh
APP_ENV=development
BACKEND_LOG_LEVEL=debug
CLIENT_LOG_DEBUG=true
CORS_ALLOWED_ORIGINS=http://localhost:5000
USERFRONT_URL=http://localhost:5000
BACKEND_PUBLIC_URL=http://localhost:5000
BACKEND_URL=http://localhost:5000
OATHKEEPER_PUBLIC_URL=http://localhost:5000
ADMINFRONT_URL=http://localhost:5173
DEVFRONT_URL=http://localhost:5174
ORGFRONT_URL=http://localhost:5175
KRATOS_UI_URL=http://localhost:5000
KRATOS_BROWSER_URL=http://localhost:5000/auth
WORKS_ADMIN_OAUTH_TOKEN_URL=https://auth.worksmobile.com/oauth2/v2.0/token
WORKSMOBILE_ENABLED=false
WORKSMOBILE_RELAY_ENABLED=false
LOGIN_LOGOUT_SMS_ENABLED=false
LOGIN_LOGOUT_NAVER_ENABLED=false
VITE_CLIENT_LOG_DEBUG=false
DEV_SERVER_WATCH_POLLING=true
EOF

echo "Created $TARGET_FILE from $SOURCE_FILE"
echo "A local smoke override block was appended to prefer localhost URLs and disable optional external notifications."
echo "Next steps:"
echo "  1. Review $TARGET_FILE and replace any placeholder secrets if your local backend requires real values."
echo "  2. Run ./scripts/check-baron-api-env.sh"
echo "  3. If runtime looks ready, run TDC114_API_BASE=http://127.0.0.1:5000 ./scripts/api-smoke.sh"
