#!/bin/bash
# =============================================================================
# 步骤 4：更新迁移目标机代码中的硬编码 IP/端口
# 在【迁移目标机】上执行本脚本
# 配置项请修改 migration_config.sh
# =============================================================================

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "${SCRIPT_DIR}/migration_config.sh"

set -e

echo "=========================================="
echo "  kgrag 配置更新脚本 - 步骤 4"
echo "  代码目录: ${DST_CODE_DIR}"
echo "  替换: ${SRC_HOST} → ${DST_HOST}"
echo "=========================================="

cd "${DST_CODE_DIR}"

TARGET_FILES=(
    "config.py"
    "batch_kg_build.py"
    "batch_kg_build_timeout.py"
    "app.py"
)

echo ""
echo "开始替换配置..."

for FILE in "${TARGET_FILES[@]}"; do
    if [ ! -f "${FILE}" ]; then
        echo "  [SKIP] 文件不存在: ${FILE}"
        continue
    fi

    cp "${FILE}" "${FILE}.bak_migration"

    sed -i "s|${OLD_NEO4J_URI}|${NEO4J_URI}|g"       "${FILE}"
    sed -i "s|${OLD_BASE_URL}|${NEW_BASE_URL}|g"      "${FILE}"
    sed -i "s|${OLD_MINERU_URL}|${NEW_MINERU_URL}|g"  "${FILE}"
    sed -i "s|${OLD_EMBED_URL}|${NEW_EMBED_URL}|g"    "${FILE}"
    sed -i "s|${OLD_LLM_URL}|${NEW_LLM_URL}|g"        "${FILE}"

    echo "  [OK] 已更新: ${FILE}  （备份：${FILE}.bak_migration）"
done

echo ""
echo "=========================================="
echo "  配置更新完成！"
echo "  下一步：执行 python 05_verify_migration.py"
echo "=========================================="

echo ""
echo "以下是各文件中仍包含旧 IP（${SRC_HOST}）的位置（供人工核查）："
grep -rn "${SRC_HOST}" "${TARGET_FILES[@]}" 2>/dev/null || echo "  （未发现残留旧 IP，配置替换完整）"
