#!/usr/bin/env bash
#
# Экспортирует стартовую историю в портативный JSON-артефакт.

set -euo pipefail

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

COMPOSE_BIN="${COMPOSE_BIN:-docker compose}"
CLEAN_START="${CLEAN_START:-1}"
ARTIFACT="${ARTIFACT:-/tmp/clickstream-startup-history.json}"
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 \
    backfill \
    --profile "${PROFILE}" \
    "${duration_args[@]}"
)"
eval "${launch_env}"

ARTIFACT_DIR="$(dirname "${ARTIFACT}")"
ARTIFACT_FILE="$(basename "${ARTIFACT}")"
mkdir -p "${ARTIFACT_DIR}"

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 ""

if [[ "${CLEAN_START}" == "1" ]]; then
  echo "Шаг 0: очистка Kafka/state перед повторяемым экспортом"
  ${COMPOSE_BIN} down -v --remove-orphans
else
  echo "Шаг 0: CLEAN_START=0, очистка пропущена"
fi

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

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

echo "Шаг 3: backfill и запись артефакта"
${COMPOSE_BIN} run --rm --no-deps \
  -v "${ARTIFACT_DIR}:/startup-artifacts" \
  -e GEN_RUN_MODE=backfill \
  -e GEN_STATE_RESET=true \
  -e GEN_LAUNCH_PROFILE="${GEN_LAUNCH_PROFILE}" \
  -e GEN_STARTUP_HISTORY_ARTIFACT="/startup-artifacts/${ARTIFACT_FILE}" \
  -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

test -s "${ARTIFACT}"
echo "Готово: ${ARTIFACT}"
