#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════
# gen-env.sh — 生成生产/staging 环境文件(pac-service/.env + pac-web/.env)
#
# 做的事:
#   1. 从 .env.example 复制出 .env(已存在则拒绝,防清掉已配好的密钥;FORCE=1 强制)
#   2. 就地强随机生成 JWT_SECRET / JWT_REFRESH_SECRET(不外传,不复用其他环境)
#   3. 一把设好生产硬开关(NODE_ENV / mock 关 / 滞后阈值 / 监控 cron 等)
#   4. 业务值从环境变量注入(见下);未提供的留占位 __FILL_ME__ 并在末尾报告
#   5. chmod 600,并列出仍需手填的项
#
# 用法(在目标服务器仓库根或 deploy/ 下跑):
#   PAC_DOMAIN=pac.example.com \
#   POSTGRES_PASSWORD='...' REDIS_URL='redis://...:6379' \
#   DW_CLICKHOUSE_URL='http://...:8123' DW_CLICKHOUSE_USERNAME='jvs_pac' DW_CLICKHOUSE_PASSWORD='...' \
#   DEEPSEEK_API_KEY='sk-...' ALERT_WEBHOOK_URL='https://qyapi.weixin.qq.com/...' \
#   ENV_KIND=production \
#   bash deploy/gen-env.sh
#
# 只想先生成密钥+开关、业务值随后手填:直接 `bash deploy/gen-env.sh`,末尾按 __FILL_ME__ 补。
# ═══════════════════════════════════════════════════════════════════════
set -euo pipefail

ROOT="${PAC_REPO_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
SVC="$ROOT/apps/pac-service/.env"
SVC_EXAMPLE="$ROOT/apps/pac-service/.env.example"
WEB="$ROOT/apps/pac-web/.env"
ENV_KIND="${ENV_KIND:-production}"    # production | staging
PH="__FILL_ME__"

command -v openssl >/dev/null || { echo "✗ 需要 openssl(生成密钥)" >&2; exit 1; }
command -v perl    >/dev/null || { echo "✗ 需要 perl(安全写值)" >&2; exit 1; }
[[ -f "$SVC_EXAMPLE" ]] || { echo "✗ 找不到 $SVC_EXAMPLE" >&2; exit 1; }

if [[ -f "$SVC" && "${FORCE:-0}" != "1" ]]; then
  echo "✋ $SVC 已存在。要重建请先备份(cp .env .env.bak)并加 FORCE=1 重跑。" >&2
  exit 1
fi

cp "$SVC_EXAMPLE" "$SVC"

# set_kv KEY VALUE FILE —— 值经 %ENV 传入,perl 不解释特殊字符(URL/密码里的 /&@:? 都安全)
set_kv() {
  local key="$1" val="$2" file="$3"
  if grep -qE "^${key}=" "$file"; then
    _K="$key" _V="$val" perl -i -pe 's/^\Q$ENV{_K}\E=.*/"$ENV{_K}=$ENV{_V}"/e' "$file"
  else
    printf '%s=%s\n' "$key" "$val" >> "$file"
  fi
}

# ── ① 就地强随机密钥 ──
set_kv JWT_SECRET         "$(openssl rand -hex 32)" "$SVC"
set_kv JWT_REFRESH_SECRET "$(openssl rand -hex 32)" "$SVC"

# ── ② 生产硬开关 ──
set_kv NODE_ENV  "$ENV_KIND" "$SVC"
set_kv LOG_LEVEL info         "$SVC"
if [[ "$ENV_KIND" == "production" ]]; then
  set_kv PAC_ENABLE_MOCK_LOGIN false "$SVC"   # ⭐ 生产必关:开着=任何人可假冒任意客服
else
  set_kv PAC_ENABLE_MOCK_LOGIN true  "$SVC"   # staging 演示要开
fi
set_kv PAC_LAG_WARN_HOURS   24          "$SVC"
set_kv PAC_LAG_ERROR_HOURS  48          "$SVC"
set_kv PAC_LAG_MONITOR_CRON "0 * * * *" "$SVC"
set_kv PAC_STALE_SCAN_CRON  "0 2 * * *" "$SVC"
set_kv PAC_INCREMENTAL_CRON ""          "$SVC"   # 留空=自动发现各 manifest 的 incremental_cron
set_kv PAC_WX_AIBOT_DEMO_PUSH ""        "$SVC"   # 生产必空:不暴露裸推送端点

# ── ③ 业务值:环境变量有则注入,无则占位 ──
inject() { # inject KEY ENVVAR_VALUE —— 必填:没值则留 __FILL_ME__ 占位并在末尾报告
  local key="$1" v="${2:-}"
  set_kv "$key" "${v:-$PH}" "$SVC"
}
inject_opt() { # inject_opt KEY ENVVAR_VALUE —— 可选:有值就写,没值留空(不报占位)
  set_kv "$1" "${2:-}" "$SVC"
}
inject POSTGRES_PASSWORD      "${POSTGRES_PASSWORD:-}"
# compose 内置 redis 走内网 redis:6379(compose 会覆盖 pac-service 的 REDIS_URL);走托管则传环境变量覆盖
inject REDIS_URL              "${REDIS_URL:-redis://redis:6379}"
inject DW_CLICKHOUSE_URL      "${DW_CLICKHOUSE_URL:-}"
inject DW_CLICKHOUSE_DATABASE "${DW_CLICKHOUSE_DATABASE:-dw_group}"
inject DW_CLICKHOUSE_USERNAME "${DW_CLICKHOUSE_USERNAME:-}"
inject DW_CLICKHOUSE_PASSWORD "${DW_CLICKHOUSE_PASSWORD:-}"
inject     DEEPSEEK_API_KEY   "${DEEPSEEK_API_KEY:-}"
inject     QWEN_API_KEY       "${QWEN_API_KEY:-}"        # 话术生成可选 provider,生产在用 → 建议填
inject_opt DASHSCOPE_API_KEY  "${DASHSCOPE_API_KEY:-}"   # 实时坐席教练(可选,不用留空)
inject_opt GEMINI_API_KEY     "${GEMINI_API_KEY:-}"      # 实时坐席教练(可选,不用留空)
inject     ALERT_WEBHOOK_URL  "${ALERT_WEBHOOK_URL:-}"

# DATABASE_URL:显式给了就用;否则若给了库密码,按 compose 内部网络(host=postgres)拼一个
if [[ -n "${DATABASE_URL:-}" ]]; then
  set_kv DATABASE_URL "$DATABASE_URL" "$SVC"
elif [[ -n "${POSTGRES_PASSWORD:-}" ]]; then
  set_kv DATABASE_URL "postgresql://pac:${POSTGRES_PASSWORD}@postgres:5432/pac?schema=public" "$SVC"
else
  set_kv DATABASE_URL "$PH" "$SVC"
fi

# 域名:一处给,三处用(后端 CORS/深链前缀 + 前端 API base)
if [[ -n "${PAC_DOMAIN:-}" ]]; then
  set_kv CORS_ORIGINS   "https://${PAC_DOMAIN}" "$SVC"
  set_kv PAC_WEB_BASE_URL "https://${PAC_DOMAIN}" "$SVC"
  printf 'NEXT_PUBLIC_API_BASE_URL=https://%s\n' "$PAC_DOMAIN" > "$WEB"
else
  set_kv CORS_ORIGINS     "$PH" "$SVC"
  set_kv PAC_WEB_BASE_URL "$PH" "$SVC"
  printf 'NEXT_PUBLIC_API_BASE_URL=%s\n' "$PH" > "$WEB"
fi

chmod 600 "$SVC" "$WEB"

echo "✓ 已生成:"
echo "    $SVC"
echo "    $WEB"
echo "✓ JWT 密钥已就地强随机;生产开关已设(NODE_ENV=$ENV_KIND, mock=$([[ $ENV_KIND == production ]] && echo false || echo true))"
echo
MISSING=$(grep -nE "$PH" "$SVC" "$WEB" || true)
if [[ -n "$MISSING" ]]; then
  echo "⚠ 仍需手填(占位 $PH),补完才能上线:"
  echo "$MISSING" | sed 's/^/    /'
  echo
  echo "  可重跑本脚本并用环境变量注入(需 FORCE=1),或直接编辑上面文件。"
else
  echo "✓ 无占位残留,业务值已全部注入。"
fi
echo
echo "下一步:bash deploy/deploy-prod.sh  →  bash deploy/first-import.sh(见 README「新环境上线」)"
