#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_FILE="${ROOT_DIR}/docker-compose.webapp-test.yml"
ENV_FILE="${ROOT_DIR}/.env"
PROJECT_NAME="fenya-webapp-test"

if [[ ! -f "${COMPOSE_FILE}" ]]; then
  echo "Не найден ${COMPOSE_FILE}" >&2
  exit 1
fi

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "Не найден ${ENV_FILE}" >&2
  exit 1
fi

if ! grep -qE '^NGROK_AUTHTOKEN=' "${ENV_FILE}"; then
  fallback_token="$(python - <<'PY'
import re
from pathlib import Path

p = Path("webapp/ngrok_tunnel.py")
if not p.exists():
    print("")
    raise SystemExit
txt = p.read_text(encoding="utf-8", errors="ignore")
m = re.search(r'auth_token\s*=\s*"([^"]+)"', txt)
print(m.group(1) if m else "")
PY
)"
  if [[ -n "${fallback_token}" ]]; then
    printf '\nNGROK_AUTHTOKEN=%s\n' "${fallback_token}" >> "${ENV_FILE}"
    echo "Добавил NGROK_AUTHTOKEN в .env из webapp/ngrok_tunnel.py"
  else
    echo "NGROK_AUTHTOKEN не найден. Добавь в .env строку NGROK_AUTHTOKEN=..." >&2
    exit 1
  fi
fi

cd "${ROOT_DIR}"
docker compose -p "${PROJECT_NAME}" -f "${COMPOSE_FILE}" up -d --build

echo "Жду инициализацию ngrok..."
public_url=""
for _ in $(seq 1 45); do
  public_url="$(python - <<'PY'
import json
import urllib.request

try:
    with urllib.request.urlopen("http://127.0.0.1:4041/api/tunnels", timeout=2) as resp:
        data = json.load(resp)
    tunnels = data.get("tunnels", [])
    for t in tunnels:
        url = str(t.get("public_url", ""))
        if url.startswith("https://"):
            print(url)
            break
except Exception:
    pass
PY
)"
  if [[ -n "${public_url}" ]]; then
    break
  fi
  sleep 1
done

if [[ -z "${public_url}" ]]; then
  echo "Не удалось получить ngrok URL. Проверь логи: docker logs fenyabot-ngrok-test" >&2
  exit 1
fi

python - <<'PY' "${ENV_FILE}" "${public_url}"
import re
import sys
from pathlib import Path

env_path = Path(sys.argv[1])
url = sys.argv[2]
text = env_path.read_text(encoding="utf-8")
if re.search(r"^WEBAPP_URL=.*$", text, flags=re.MULTILINE):
    text = re.sub(r"^WEBAPP_URL=.*$", f"WEBAPP_URL={url}", text, flags=re.MULTILINE)
else:
    text = text.rstrip() + f"\nWEBAPP_URL={url}\n"
env_path.write_text(text, encoding="utf-8")
PY

echo
echo "Готово."
echo "NGROK URL: ${public_url}"
echo "WEBAPP_URL обновлён в .env"
echo
echo "Для остановки тест-контура:"
echo "  docker compose -p ${PROJECT_NAME} -f ${COMPOSE_FILE} down"
