#!/usr/bin/env bash
# Regenerate a Telegram session string for ONE account, save it to a fixed-name
# temp file under .secrets/, and upsert it into the project .env so the MCP
# server (via scripts/telegram-mcp.sh) and the direct Telethon scripts pick it up.
#
# Why per-account strings: one Telegram authorization (auth_key / session string)
# must be used from ONE source. Sharing a single string across two devices/IPs
# makes Telegram permanently revoke the key. Each device/account gets its own.
#
# Usage:
#   bash scripts/regen_telegram_session.sh usulsu    # main account   -> TELEGRAM_SESSION_STRING
#   bash scripts/regen_telegram_session.sh helper    # samuishechka   -> TELEGRAM_SESSION_STRING_HELPER
# or via npm:
#   pnpm tg:session:usulsu
#   pnpm tg:session:helper
#
# At the generator prompts:
#   - "Account label"            -> just press Enter
#   - "update your .env? (y/N)"  -> answer N  (this script writes .env itself)
set -euo pipefail

ACCOUNT="${1:-}"
case "$ACCOUNT" in
  usulsu) ENV_VAR="TELEGRAM_SESSION_STRING" ;;
  helper) ENV_VAR="TELEGRAM_SESSION_STRING_HELPER" ;;
  *) echo "usage: $0 <usulsu|helper>" >&2; exit 1 ;;
esac

PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"
SECRETS_DIR="$PROJECT_ROOT/.secrets"
OUT_FILE="$SECRETS_DIR/session_${ACCOUNT}.txt"

[ -f "$ENV_FILE" ] || { echo "missing $ENV_FILE (copy .env.example and fill it in)" >&2; exit 1; }
set -a; . "$ENV_FILE"; set +a
if [ -z "${TELEGRAM_API_ID:-}" ] || [ -z "${TELEGRAM_API_HASH:-}" ]; then
  echo "TELEGRAM_API_ID / TELEGRAM_API_HASH missing in $ENV_FILE" >&2
  exit 1
fi

TELEGRAM_DIR="${TELEGRAM_MCP_DIR:-}"
if [ -z "$TELEGRAM_DIR" ]; then
  echo "TELEGRAM_MCP_DIR not set in $ENV_FILE" >&2
  echo "point it at the telegram-mcp checkout on THIS machine, e.g.:" >&2
  echo "  TELEGRAM_MCP_DIR=/path/to/telegram" >&2
  exit 1
fi
[ -x "$TELEGRAM_DIR/.venv/bin/python" ] || {
  echo "generator not found at $TELEGRAM_DIR/.venv/bin/python" >&2
  echo "check TELEGRAM_MCP_DIR in $ENV_FILE and that its .venv is created" >&2; exit 1; }

mkdir -p "$SECRETS_DIR"
tmp="$(mktemp)"; trap 'rm -f "$tmp"' EXIT

echo ">> Regenerating Telegram session for: $ACCOUNT  (-> $ENV_VAR)"
echo ">> Sign in with the '$ACCOUNT' account when scanning the QR code."
echo ">> At 'Account label' press Enter; at 'update .env' answer N."
echo ""

# Run the generator unbuffered; show output live AND capture it to $tmp.
( cd "$TELEGRAM_DIR" \
    && TELEGRAM_API_ID="$TELEGRAM_API_ID" TELEGRAM_API_HASH="$TELEGRAM_API_HASH" \
       .venv/bin/python -u session_string_generator.py --qr ) 2>&1 | tee "$tmp"

# Extract the session string: first non-empty line after the header marker.
SESSION="$(awk '/----- Your Session String -----/{f=1; next} f && NF {print $1; exit}' "$tmp")"
if [ -z "$SESSION" ]; then
  echo "!! Could not capture a session string from the generator output." >&2
  echo "!! Nothing written. Re-run and complete the login." >&2
  exit 1
fi

# Save to the fixed temp file (owner-only).
umask 077
printf '%s\n' "$SESSION" > "$OUT_FILE"
echo ""
echo ">> Saved session string -> $OUT_FILE"

# Upsert ENV_VAR into .env (replace the existing line or append).
if grep -q "^${ENV_VAR}=" "$ENV_FILE"; then
  awk -v k="$ENV_VAR" -v v="$SESSION" \
      '$0 ~ "^" k "=" {print k "=" v; done=1; next} {print}
       END{if(!done) print k "=" v}' "$ENV_FILE" > "$tmp"
  cat "$tmp" > "$ENV_FILE"
else
  printf '%s=%s\n' "$ENV_VAR" "$SESSION" >> "$ENV_FILE"
fi
echo ">> Updated $ENV_VAR in $ENV_FILE"
echo ">> Done. Run /mcp (reconnect) to pick up the new session for telegram-$ACCOUNT."
