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

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

merge_filename="$1"
file="$HOME/bin/merge_n1/live/${merge_filename}"
hosts_file="$HOME/bin/hosts"

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

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

line_no=0

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]}"
  world_ids=("${ids[@]:1}")

  if [[ "${#world_ids[@]}" -eq 0 ]]; then
    echo "L$line_no: Error   target=$target_world_id world_ids=<none> (no world_ids)"
    ALL_OK=0
    ((++TOTAL_ERRORS))
    continue
  fi

  world_ids_output="${world_ids[*]}"

  ok_cnt=0
  bad_ids=()

  for wid in "${world_ids[@]}"; do
    # 嚴格匹配：只允許以下前綴開頭的 token
    #   WS<wid>
    #   WHS<wid><digits...>         (例如 WHS11011 / WHS11012)
    #   WWEBSPS<wid><digits...>     (例如 WWEBSPS11011)
    #   WORLDDB<wid>
    #
    # 並要求 token 邊界（前面是行首/空白，後面是行尾/空白），避免誤判
    #
    # 注意：WHS/WWEBSPS 後面允許接數字，符合你舉例的 11011/11012 型態
    re="(^|[[:space:]])(WS${wid}|WORLDDB${wid}|WHS${wid}[0-9]*|WWEBSPS${wid}[0-9]*)([[:space:]]|$)"

    if awk -v r="$re" '$0 ~ r {found=1; exit} END{exit(found?0:1)}' "$hosts_file"; then
      # 找到了 => 錯誤
      bad_ids+=("$wid")
    else
      # 找不到 => 正確
      ((++ok_cnt))
    fi
  done

  total_cnt="${#world_ids[@]}"

  if [[ "$ok_cnt" -eq "$total_cnt" ]]; then
    echo "L$line_no: Correct target=$target_world_id world_ids=${world_ids_output} (not_found_ok=$ok_cnt total=$total_cnt)"
    "$HOME/bin/send_chatbot_text_only_test" "[正式合併] ${merge_filename} HOSTS 移除 驗證成功 (無殘留)" "${world_ids_output}"
  else
    echo "L$line_no: Error   target=$target_world_id world_ids=${world_ids_output} (not_found_ok=$ok_cnt total=$total_cnt found_bad=${bad_ids[*]:-<none>})"
    "$HOME/bin/send_chatbot_text_only_test" "[正式合併] ${merge_filename} HOSTS 移除 驗證失敗 (有搜尋到)" "${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 行）"
  "$HOME/bin/send_chatbot_text_only" "[正式合併] ${merge_filename} HOSTS 移除 驗證結果" "成功!"
else
  echo "最終結論：部分出錯（共 $TOTAL_LINES 行，錯誤 $TOTAL_ERRORS 行）"
  "$HOME/bin/send_chatbot_text_only" "[正式合併] ${merge_filename} HOSTS 移除 驗證結果" "失敗!"
fi

