#!/bin/bash
# Private beta launcher (Tailscale-first)
# Usage: ./start_beta.sh [port]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PORT="${1:-${CRM_PORT:-8080}}"
ENV_FILE="${CRM_ENV_FILE:-$SCRIPT_DIR/.env.beta}"

if [ -f "$ENV_FILE" ]; then
  # shellcheck disable=SC1090
  set -a
  . "$ENV_FILE"
  set +a
else
  echo "ERROR: Missing $ENV_FILE"
  echo "Copy .env.beta.example to .env.beta and fill values first."
  exit 1
fi

if [ -z "${CRM_SECRET_KEY:-}" ]; then
  echo "ERROR: CRM_SECRET_KEY is required for beta/prod mode."
  exit 1
fi

if [ "${#CRM_SECRET_KEY}" -lt 24 ]; then
  echo "ERROR: CRM_SECRET_KEY is too short. Use at least 24+ chars."
  exit 1
fi

export CRM_ENV="production"
export CRM_PORT="$PORT"
export CRM_HOST="0.0.0.0"

TAILSCALE_IP=""
if command -v tailscale >/dev/null 2>&1; then
  TAILSCALE_IP="$(tailscale ip -4 2>/dev/null | head -n 1 || true)"
fi

if [ -z "${CRM_CORS_ORIGIN:-}" ]; then
  if [ -n "$TAILSCALE_IP" ]; then
    export CRM_CORS_ORIGIN="http://$TAILSCALE_IP:$PORT"
  else
    export CRM_CORS_ORIGIN="*"
  fi
fi

echo ""
echo "  Venture CRM - Private Beta"
echo "  Mode:     $CRM_ENV"
echo "  Port:     $PORT"
echo "  CORS:     ${CRM_CORS_ORIGIN}"
if [ -n "$TAILSCALE_IP" ]; then
  echo "  Tailscale URL: http://$TAILSCALE_IP:$PORT"
else
  echo "  Tailscale IP not detected. Run: tailscale ip -4"
fi
echo ""

cd "$SCRIPT_DIR"
python3 backend/server.py
