#!/usr/bin/env bash
# 在本地执行：读取 server/data.db 各表 PRAGMA table_info，生成供生产执行的 align-production-schema.sh
# 用法：在项目根目录执行 ./scripts/gen-align-schema-from-local.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DB_PATH="${DB_PATH:-$PROJECT_ROOT/server/data.db}"
OUT_PATH="$PROJECT_ROOT/scripts/align-production-schema.sh"

if [[ ! -f "$DB_PATH" ]]; then
  echo "本地库不存在: $DB_PATH"
  exit 1
fi

tables=$(sqlite3 "$DB_PATH" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('sqlite_sequence') ORDER BY name;")

cat > "$OUT_PATH" << 'HEAD'
#!/usr/bin/env bash
# 由 scripts/gen-align-schema-from-local.sh 根据本地 server/data.db 表结构生成，供生产执行。
# 用法：在生产目录执行 DB_PATH=server/data.db ./scripts/align-production-schema.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DB_PATH="${DB_PATH:-$PROJECT_ROOT/server/data.db}"

run() { sqlite3 "$DB_PATH" "$1" 2>/dev/null || true; }

echo "=== 对齐生产库表结构（与本地 data.db 一致）：$DB_PATH ==="
HEAD

while IFS= read -r table; do
  [[ -z "$table" ]] && continue
  # 跳过 cid=0（首列，通常建表时已有）
  first=1
  while IFS='|' read -r cid name type notnull dflt pk; do
    [[ -z "$cid" || "$cid" -eq 0 ]] && continue
    # 非常量默认值（如 datetime('now')）不写 DEFAULT，避免生产 SQLite 报错
    def="$type"
    [[ "$notnull" == "1" ]] && def="$def NOT NULL"
    if [[ -n "$dflt" && "$dflt" != *"("* ]]; then
      # SQL 字面量：已知字符串默认值写死，避免 shell 转义问题
      case "$dflt" in
        '"operational"') def="${def} DEFAULT 'operational'" ;;
        '"other"')       def="${def} DEFAULT 'other'" ;;
        '"medium"')      def="${def} DEFAULT 'medium'" ;;
        "''")            def="${def} DEFAULT ''" ;;
        *)               dflt_sql="${dflt//\"/\'}"; def="$def DEFAULT $dflt_sql" ;;
      esac
    fi
    if [[ "$def" == *\'* ]]; then
      # def 含单引号：用 run '...'\''...'\'' 形式写入
      safe_def=$(echo "$def" | sed "s/'/'\\\\''/g")
      printf "run 'ALTER TABLE %s ADD COLUMN %s %s;'\n" "$table" "$name" "$safe_def" >> "$OUT_PATH"
    else
      printf 'run "ALTER TABLE %s ADD COLUMN %s %s;"\n' "$table" "$name" "$def" >> "$OUT_PATH"
    fi
    if [[ "$first" -eq 1 ]]; then
      echo "# $table（本地列）" >> "$OUT_PATH"
      first=0
    fi
    if [[ "$table" == "combat_losses" && "$name" == "carriers" ]]; then
      echo 'run "UPDATE combat_losses SET carriers = COALESCE(tanks, 0) WHERE carriers = 0;"' >> "$OUT_PATH"
    fi
  done < <(sqlite3 -separator '|' "$DB_PATH" "PRAGMA table_info($table);")
  if [[ "$first" -eq 0 ]]; then
    echo "echo \"  $table done\"" >> "$OUT_PATH"
  fi
done <<< "$tables"

echo "" >> "$OUT_PATH"
echo "echo \"=== 完成。核对示例： ===\"" >> "$OUT_PATH"
echo "echo \"  sqlite3 \$DB_PATH \\\"PRAGMA table_info(key_location);\\\"\"" >> "$OUT_PATH"
echo "echo \"  sqlite3 \$DB_PATH \\\"PRAGMA table_info(combat_losses);\\\"\"" >> "$OUT_PATH"

chmod +x "$OUT_PATH"
echo "已生成: $OUT_PATH"
echo "请将该文件推到生产后执行：DB_PATH=server/data.db ./scripts/align-production-schema.sh"
