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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUT_DIR="$ROOT_DIR/resources/converter/mac"
WORK_DIR="$ROOT_DIR/scripts/.converter-venv"

PYTHON_BIN=""
for candidate in python3.11 python3.10 python3; do
  if command -v "$candidate" >/dev/null 2>&1; then
    PYTHON_BIN="$candidate"
    break
  fi
done

if [ -z "$PYTHON_BIN" ]; then
  echo "Python 3.10+ is required. Install python3.11 and retry."
  exit 1
fi

PYTHON_VERSION=$("$PYTHON_BIN" -c "import sys; print(f\"{sys.version_info.major}.{sys.version_info.minor}\")")
if [ "$PYTHON_VERSION" = "3.13" ]; then
  echo "Python 3.13 is not supported by opentele/TGConvertor. Install python3.11 and retry."
  exit 1
fi

"$PYTHON_BIN" -m venv "$WORK_DIR"
source "$WORK_DIR/bin/activate"

pip install --upgrade pip
pip install "TGConvertor[tdata]==0.1.4" telethon pyinstaller

pyinstaller --onefile "$ROOT_DIR/scripts/tdata_converter.py" \
  --name tgconvertor \
  --distpath "$ROOT_DIR/dist/tdata_converter" \
  --collect-all TGConvertor \
  --collect-all opentele \
  --collect-all telethon

mkdir -p "$OUT_DIR"
cp -f "$ROOT_DIR/dist/tdata_converter/tgconvertor" "$OUT_DIR/tgconvertor"

rm -rf "$ROOT_DIR/dist/tdata_converter" "$ROOT_DIR/build" "$ROOT_DIR/tdata_converter.spec"

echo "Converter built: $OUT_DIR/tgconvertor"
