#!/usr/bin/env bash
#
# Импортирует портативный артефакт стартовой истории в Kafka.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

COMPOSE_BIN="${COMPOSE_BIN:-docker compose}"
ARTIFACT="${ARTIFACT:-data/startup_history/reference-world.json.xz}"
PROFILE="${PROFILE:-${GEN_LAUNCH_PROFILE:-daily-wave}}"
duration_args=()
if [[ -n "${GEN_HISTORY_DURATION:-}" ]]; then
  duration_args=(--duration "${GEN_HISTORY_DURATION}")
fi

cd "${REPO_ROOT}"

launch_env="$(
  PYTHONPATH="${REPO_ROOT}/generator/src" \
  uv run python -m clickstream_generator.launch \
    continue \
    --profile "${PROFILE}" \
    "${duration_args[@]}"
)"
eval "${launch_env}"

if [[ ! -s "${ARTIFACT}" ]]; then
  echo "Ошибка: артефакт не найден или пуст: ${ARTIFACT}" >&2
  exit 1
fi

ARTIFACT_DIR="$(cd "$(dirname "${ARTIFACT}")" && pwd)"
ARTIFACT_FILE="$(basename "${ARTIFACT}")"

echo "=== Импорт стартовой истории ==="
echo "ARTIFACT=${ARTIFACT}"
echo "GEN_LAUNCH_PROFILE=${GEN_LAUNCH_PROFILE}"
echo "GEN_HISTORY_DURATION=${GEN_HISTORY_DURATION}"
echo "GEN_SEED=${GEN_SEED}"
echo "GEN_MODEL_T0=${GEN_MODEL_T0}"
echo "GEN_MODEL_T_END=${GEN_MODEL_T_END}"
echo ""

echo "Шаг 1: запуск Kafka и ClickHouse"
${COMPOSE_BIN} up -d kafka clickhouse

echo "Шаг 2: предпроверка чистого стенда"
bash "${SCRIPT_DIR}/assert_stand_clean.sh" clean

echo "Шаг 3: сборка образа генератора"
${COMPOSE_BIN} build generator

echo "Шаг 4: воспроизведение артефакта в Kafka"
${COMPOSE_BIN} run --rm --no-deps \
  -v "${ARTIFACT_DIR}:/startup-artifacts:ro" \
  -e GEN_LAUNCH_PROFILE="${GEN_LAUNCH_PROFILE}" \
  -e GEN_SEED="${GEN_SEED}" \
  -e GEN_MODEL_T0="${GEN_MODEL_T0}" \
  -e GEN_MODEL_T_END="${GEN_MODEL_T_END}" \
  -e GEN_MODEL_TIMEZONE="${GEN_MODEL_TIMEZONE}" \
  -e GEN_MODEL_TIME_SPEED="${GEN_MODEL_TIME_SPEED}" \
  -e GEN_TICK_SECONDS="${GEN_TICK_SECONDS}" \
  -e GEN_LAMBDA_BASE_PER_MIN="${GEN_LAMBDA_BASE_PER_MIN}" \
  -e GEN_JITTER_PCT="${GEN_JITTER_PCT}" \
  -e GEN_MIN_EVENTS_PER_TICK="${GEN_MIN_EVENTS_PER_TICK}" \
  -e GEN_MAX_EVENTS_PER_TICK="${GEN_MAX_EVENTS_PER_TICK}" \
  generator python -m clickstream_generator.startup_history_artifact import \
    --artifact "/startup-artifacts/${ARTIFACT_FILE}"

echo "Готово: артефакт воспроизведён в Kafka."
