#!/bin/bash
# === 參數檢查 ===
if [[ $# -ne 4 ]]; then
  echo "用法: $0 <TAG_NAME> <YYYYMMDDHHMMSS> <hour|minute> <TIME_INTERVAL>"
  exit 1
fi

TAG_NAME=$1
INPUT_TIME=$2
TIME_TYPE=$3
TIME_INTERVAL=$4

# === 檢查時間格式 ===
if ! [[ $INPUT_TIME =~ ^[0-9]{14}$ ]]; then
  echo "錯誤：第一個參數需為 14 碼時間格式：YYYYMMDDHHMMSS"
  exit 1
fi

# === 拆解時間 ===
YEAR=${INPUT_TIME:0:4}
MONTH=${INPUT_TIME:4:2}
DAY=${INPUT_TIME:6:2}
HOUR=${INPUT_TIME:8:2}
MINUTE=${INPUT_TIME:10:2}
SECOND=${INPUT_TIME:12:2}

# === 計算 thread 對齊時間 ===
if [[ "$TIME_TYPE" == "hour" ]]; then
  MOD_HOUR=$((10#$HOUR % TIME_INTERVAL))
  BASE_HOUR=$((10#$HOUR - MOD_HOUR))
  BASE_MIN=0
elif [[ "$TIME_TYPE" == "minute" ]]; then
  TOTAL_MIN=$((10#$HOUR * 60 + 10#$MINUTE))
  MOD_MIN=$((TOTAL_MIN % TIME_INTERVAL))
  BASE_TOTAL_MIN=$((TOTAL_MIN - MOD_MIN))
  BASE_HOUR=$((BASE_TOTAL_MIN / 60))
  BASE_MIN=$((BASE_TOTAL_MIN % 60))
else
  echo "錯誤：TIME_TYPE 必須是 hour 或 minute"
  exit 1
fi

# === 補零格式化 ===
BASE_HOUR_PAD=$(printf "%02d" $BASE_HOUR)
BASE_MIN_PAD=$(printf "%02d" $BASE_MIN)

# === 產生 thread 名稱 ===
THREAD_NAME="thread-${TAG_NAME}-${YEAR}_${MONTH}${DAY}_${BASE_HOUR_PAD}${BASE_MIN_PAD}"

echo "$THREAD_NAME"
