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

# 檢查參數數量
if [[ "$#" -ne 1 ]]; then
  echo "用法: $0 <merge_filename>" >&2
  exit 1
fi

merge_filename="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
file="${SCRIPT_DIR}/merge_n1/live/${merge_filename}"

# 檢查檔案是否存在
if [[ ! -f "$file" ]]; then
  echo "找不到檔案: $file" >&2
  exit 1
fi

line_no=0

# 全面判斷統計
ALL_OK=1
TOTAL_LINES=0
TOTAL_ERRORS=0

# 讀檔
while IFS= read -r line || [[ -n "$line" ]]; do
  ((++line_no))

  # 跳過空行/註解行
  [[ -z "$line" ]] && continue
  [[ "$line" =~ ^[[:space:]]*# ]] && continue

  # 僅允許數字與空白（避免注入或非預期字元）
  if ! [[ "$line" =~ ^[[:space:]]*[0-9]+([[:space:]]+[0-9]+)*[[:space:]]*$ ]]; then
    echo "L$line_no: invalid content, skipped: $line" >&2
    continue
  fi

  ((++TOTAL_LINES))

  # 拆成陣列
  read -r -a ids <<<"$line"

  # 1) target_world_id 取第一個
  target_world_id="${ids[0]}"

  # 2) source：後面參數排除重複後，保留原順序
  declare -A seen=()
  seen["$target_world_id"]=1

  declare -a source_world_ids=()
  for wid in "${ids[@]:1}"; do
    if [[ -z "${seen[$wid]+x}" ]]; then
      source_world_ids+=("$wid")
      seen["$wid"]=1
    fi
  done

  # 你要的 2)（空白分隔、保序去重）
  sorted_source_world_ids="${source_world_ids[*]}"

  # 補上：sorted_world_ids_arr（array 版本）
  sorted_world_ids_arr=("$target_world_id" "${source_world_ids[@]}")

  # 補上：sorted_world_ids（多行字串版本，若你後面還想用 head/tail/paste）
  sorted_world_ids="$(printf '%s\n' "${sorted_world_ids_arr[@]}")"

  # 你要的 3)（逗號分隔）
  sorted_world_ids_str="$(IFS=,; printf '%s' "${sorted_world_ids_arr[*]}")"

  if [[ -z "$sorted_world_ids" ]]; then
    echo "L$line_no: no ids, skipped" >&2
    continue
  fi

  # 你指定的 SQL（不含結尾分號；由 psql -c "$sql;" 補）
  sql="WITH base AS (
    SELECT to_jsonb(dbs) - 'world_id' AS payload
    FROM db_setup dbs
    WHERE is_commercial = 1 AND dbs.world_id = ${target_world_id}
  )
  SELECT dbs.*
  FROM db_setup dbs
  CROSS JOIN base b
  WHERE is_commercial = 1
    AND dbs.world_id IN (${sorted_world_ids_str})
    AND (to_jsonb(dbs) - 'world_id') IS DISTINCT FROM b.payload"

  # 固定透過 ssh CTRL 執行：psql -U postgres WebTool -c "$sql;"
  psql_out="$(
    ssh CTRL 'bash -lc '"'"'sql="$(cat)"; psql -U postgres WebTool -c "$sql;"'"'"'' <<<"$sql" 2>&1
  )" || {
    echo "L$line_no: Error target_world_id=$target_world_id ids=$sorted_world_ids_str (psql failed)" >&2
    echo "$psql_out" >&2
    ALL_OK=0
    ((++TOTAL_ERRORS))
    continue
  }

  # 從 psql 輸出抓 (N rows) 或 (N row)
  row_count="$(
    printf '%s\n' "$psql_out" \
      | sed -n 's/^[[:space:]]*(\([0-9]\+\)[[:space:]]\+row[s]*).*/\1/p' \
      | tail -n 1
  )"

  if ! [[ "$row_count" =~ ^[0-9]+$ ]]; then
    echo "L$line_no: Error target_world_id=$target_world_id ids=$sorted_world_ids_str (cannot parse row count)" >&2
    echo "$psql_out" >&2
    ALL_OK=0
    ((++TOTAL_ERRORS))
    continue
  fi

  if [[ "$row_count" -eq 0 ]]; then
    echo "L$line_no: Correct target_world_id=$target_world_id ids=$sorted_world_ids_str"
    "$HOME/bin/send_chatbot_text_only_test" "[DB_SETUP]驗證 更新成功 ^^" "$target_world_id <- ${sorted_source_world_ids}"
  else
    echo "L$line_no: Error   target_world_id=$target_world_id ids=$sorted_world_ids_str rows=$row_count"
    "$HOME/bin/send_chatbot_text_only_test" "[DB_SETUP]驗證 更新失敗 QQ" "$target_world_id <- ${sorted_source_world_ids}"
    ALL_OK=0
    ((++TOTAL_ERRORS))
  fi

done < "$file"

# 最終單一結論
if [[ "$TOTAL_LINES" -eq 0 ]]; then
  echo "最終結論：未處理任何資料行（檔案可能為空或全為註解/空行）"
elif [[ "$ALL_OK" -eq 1 ]]; then
  echo "最終結論：完全正確（共 $TOTAL_LINES 行）"
  "$HOME/bin/send_chatbot_text_only" "[正式合併] ${merge_filename} DB_SETUP 驗證結果" "成功!"
else
  echo "最終結論：部分出錯（共 $TOTAL_LINES 行，錯誤 $TOTAL_ERRORS 行）"
  "$HOME/bin/send_chatbot_text_only" "[正式合併] ${merge_filename} DB_SETUP 驗證結果" "失敗!"
fi

