#!/bin/bash




SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"


CONFIG_FILE=${1:-"${SCRIPT_DIR}/configs/base_config.sh"}
if [ ! -f "$CONFIG_FILE" ]; then
    echo "エラー: 設定ファイルが見つかりません: ${CONFIG_FILE}"
    exit 1
fi

echo "CONFIG_FILE: ${CONFIG_FILE}"

source ${REPO_ROOT}/.venv/bin/activate

source $CONFIG_FILE



if [ -f "$LATEST_ITERATION_FILE" ]; then
  MAX_ITERATION=$(cat "$LATEST_ITERATION_FILE")
else

  MAX_ITERATION=7500
fi
echo "最大イテレーションを検出しました: ${MAX_ITERATION}"




run_conversion() {
  local iter_to_run=$1

  echo "=================================================="
  echo "イテレーション ${iter_to_run} のモデル変換を実行します"
  echo "=================================================="


  local training_checkpoint_dir_base="${CHECK_POINT_ROOT_PATH}/${BASE_MODEL}/${TRAIN_DATASET}_lr_2e-5-minlr_4e-6_GB_64_${EPOCH}epoch"
  local formatted_iter=$(printf "iter_%07d" "$iter_to_run")
  local source_checkpoint_dir="${training_checkpoint_dir_base}/${formatted_iter}"


  if [ ! -d "$source_checkpoint_dir" ]; then
      echo "警告: 変換元のチェックポイントが見つかりません。スキップします: ${source_checkpoint_dir}"
      return
  fi


  ${SCRIPT_DIR}/convert_model.sh \
    "$EPOCH" \
    "$TRAIN_DATASET" \
    "$iter_to_run" \
    "$CHECK_POINT_ROOT_PATH" \
    "$CONVERTED_CHECK_POINT_ROOT_PATH" \
    "$BASE_MODEL" \
    "$MODEL_ORG"

  python3 ${SCRIPT_DIR}/utils/send_to_slack.py "Model conversion for iteration ${iter_to_run} Finished!"
}



ITERATION_STEP=250


for (( iter=${ITERATION_STEP}; iter<=${MAX_ITERATION}; iter+=${ITERATION_STEP} )); do
  run_conversion $iter
done


if (( MAX_ITERATION % ITERATION_STEP != 0 )); then
  echo "最終チェックポイント (${MAX_ITERATION}) のモデル変換を追加で実行します。"
  run_conversion $MAX_ITERATION
fi


python3 ${SCRIPT_DIR}/utils/send_to_slack.py "<!channel> 全てのチェックポイントのモデル変換が完了しました！"
echo "=================================================="
echo "全ての処理が完了しました。"
echo "=================================================="
