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

# 用法: ./script.sh <environment:test|live> <merge_filename>
if [[ "$#" -ne 2 ]]; then
  echo "用法: $0 <environment:test|live> <merge_filename>" >&2
  exit 1
fi

environment="$1"
merge_filename="$2"

if [[ "$environment" != "test" && "$environment" != "live" ]]; then
  echo "Error: environment must be 'test' or 'live'." >&2
  exit 1
fi

file="$HOME/bin/merge_n1/${environment}/${merge_filename}"
hosts_file="$HOME/bin/hosts.old"

if [[ ! -f "$file" ]]; then
  echo "找不到檔案: $file" >&2
  exit 1
fi

if [[ ! -f "$hosts_file" ]]; then
  echo "找不到 hosts 檔案: $hosts_file" >&2
  exit 1
fi

if [[ "$environment" == "live" ]]; then
  OUTPUT_ENV="[正式合併]"
  SCRIPT="$HOME/bin/send_chatbot_text_only"
else
  OUTPUT_ENV="[測試合併]"
  SCRIPT="$HOME/bin/send_chatbot_text_only_test"
fi

# test: >=3；live: >=4
if [[ "$environment" == "test" ]]; then
  CNT_THRESHOLD=3
else
  CNT_THRESHOLD=4
fi

# SSH 強制非互動，避免卡住；也避免 known_hosts 污染與 warning
SSH_OPTS=(
  -n
  -o BatchMode=yes
  -o StrictHostKeyChecking=no
  -o UserKnownHostsFile=/dev/null
  -o LogLevel=ERROR
)

line_no=0

# 全面判斷：只要有任一行 Error，就視為「部分出錯」
ALL_OK=1
TOTAL_LINES=0
TOTAL_ERRORS=0

exec 3< "$file"
while IFS= read -r line <&3 || [[ -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"
  target_world_id="${ids[0]}"
  source_world_ids=("${ids[@]:1}")
  source_world_ids_cnt="${#source_world_ids[@]}"

  # 僅供輸出用（空白分隔、保留原順序、不換行）
  source_world_ids_output="${source_world_ids[*]}"

  if [[ "$source_world_ids_cnt" -eq 0 ]]; then
    echo "L$line_no: Error   env=$environment target=$target_world_id source_ids=<none> (no source ids)"
    ALL_OK=0
    ((++TOTAL_ERRORS))
    continue
  fi

  # test/live SET_ID 規則一致：都以 target_world_id 計算
  SET_ID=$((target_world_id / 100))
  source_ids_str="$(printf '%s\n' "${source_world_ids[@]}" | paste -sd, -)"

  # test 環境下的 MACHINE_KEYWORD 只跟 SET_ID 有關，可以先算好
  if [[ "$environment" == "test" ]]; then
    if [[ "$SET_ID" -ge 10 && "$SET_ID" -lt 20 ]]; then
      TEST_MACHINE_KEYWORD="MERGE_ASIA"
    elif [[ "$SET_ID" -ge 20 && "$SET_ID" -lt 30 ]]; then
      TEST_MACHINE_KEYWORD="MERGE_US"
    elif [[ "$SET_ID" -ge 30 && "$SET_ID" -lt 40 ]]; then
      TEST_MACHINE_KEYWORD="MERGE_EU"
    else
      echo "L$line_no: Error   env=$environment target=$target_world_id set_id=$SET_ID (SET_ID out of range for test)"
      "$HOME/bin/send_chatbot_text_only_test" "${OUTPUT_ENV} ${merge_filename} Server 目錄移除 驗證失敗 QQ" "$target_world_id <- ${source_world_ids_output}"
      ALL_OK=0
      ((++TOTAL_ERRORS))
      continue
    fi
  fi

  WID_CORRECT=0
  WID_ERROR=()

  for wid in "${source_world_ids[@]}"; do
    # environment 決定 MACHINE_KEYWORD（依你指定）
    if [[ "$environment" == "live" ]]; then
      MACHINE_KEYWORD="WS${wid} "
    else
      MACHINE_KEYWORD="$TEST_MACHINE_KEYWORD"
    fi

    MACHINE_IP="$(
      awk -v key="${MACHINE_KEYWORD}" 'index($0, key) {print $1; exit}' "$hosts_file"
    )"

    if [[ -z "$MACHINE_IP" ]]; then
      WID_ERROR+=("$wid")
      continue
    fi

    remote_cmd="ls -hld $HOME/prepare/merge_*_${merge_filename}_${environment}/servers${SET_ID}/*Server* 2>/dev/null \
| grep -E 'WHTTPAServer|WorldServer|WWebSocketProxyServer' \
| grep -E '${wid}' \
| wc -l"

    set +e
    DIRECTORY_RELATED_CNT="$(ssh "${SSH_OPTS[@]}" "$MACHINE_IP" "$remote_cmd" </dev/null)"
    ssh_rc=$?
    set -e

    if [[ "$ssh_rc" -ne 0 ]]; then
      WID_ERROR+=("$wid")
      continue
    fi

    DIRECTORY_RELATED_CNT="$(printf '%s' "$DIRECTORY_RELATED_CNT" | tr -d '[:space:]')"
    if ! [[ "$DIRECTORY_RELATED_CNT" =~ ^[0-9]+$ ]]; then
      WID_ERROR+=("$wid")
      continue
    fi

    if [[ "$DIRECTORY_RELATED_CNT" -ge "$CNT_THRESHOLD" ]]; then
      ((++WID_CORRECT))
    else
      WID_ERROR+=("$wid")
    fi
  done

  if [[ "$source_world_ids_cnt" -eq "$WID_CORRECT" ]]; then
    echo "L$line_no: Correct env=$environment target=$target_world_id set_id=$SET_ID source_ids=${source_ids_str:-<none>} (ok=$WID_CORRECT total=$source_world_ids_cnt)"
    "$HOME/bin/send_chatbot_text_only_test" "${OUTPUT_ENV} ${merge_filename} Server 目錄移除 驗證成功 ^^" "${source_world_ids_output}"
  else
    echo "L$line_no: Error   env=$environment target=$target_world_id set_id=$SET_ID source_ids=${source_ids_str:-<none>} (ok=$WID_CORRECT total=$source_world_ids_cnt bad=${WID_ERROR[*]:-<none>})"
    "$HOME/bin/send_chatbot_text_only_test" "${OUTPUT_ENV} ${merge_filename} Server 目錄移除 驗證失敗 QQ" "${source_world_ids_output}"
    ALL_OK=0
    ((++TOTAL_ERRORS))
  fi

done
exec 3<&-

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

