#!/bin/bash
set -e

echo "==================================="
echo "Initializing Codeflash Database"
echo "==================================="

# Wait for PostgreSQL to be ready
echo "Waiting for PostgreSQL to start..."
timeout=60
counter=0
until pg_isready -h localhost -p 5432 -U codeflash 2>/dev/null; do
  counter=$((counter + 1))
  if [ $counter -gt $timeout ]; then
    echo "ERROR: PostgreSQL did not start within ${timeout} seconds"
    exit 1
  fi
  sleep 1
done

echo "PostgreSQL is ready!"

# Run Prisma migrations
echo ""
echo "Running Prisma migrations..."
cd /common
export DATABASE_URL="${DATABASE_URL:-postgresql://codeflash:codeflash@localhost:5432/codeflash}"
npx prisma migrate deploy

echo ""
echo "Checking for existing users..."
USER_COUNT=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM users;" 2>/dev/null || echo "0")
USER_COUNT=$(echo $USER_COUNT | tr -d ' ')

if [ "$USER_COUNT" = "0" ]; then
  echo ""
  echo "No users found. Creating default user and API key..."

  # Hardcoded API key for on-premise deployment
  # Unhashed key (what users will use): cf-LDKLmsqjcZeX6SvjFPTz66NWgTV25njdWNUxinokmJcfegwRWytqFoJBoCkAKQad
  # This is the SHA-384 hash stored in the database:
  API_KEY_UNHASHED="LDKLmsqjcZeX6SvjFPTz66NWgTV25njdWNUxinokmJcfegwRWytqFoJBoCkAKQad"
  API_KEY_HASHED="uXkhQcmQVmZbOpMtPMUTfeLRZOD3-s6GzYV1IpLMtJeHX4I9P8Ej_Kx3RftkP9yw"
  SUFFIX="KQad"

  # Use environment variables or defaults for user information
  DEFAULT_USER_ID="${DEFAULT_USER_ID:-github|10488227}"
  DEFAULT_USERNAME="${DEFAULT_USERNAME:-Saga4}"
  DEFAULT_EMAIL="${DEFAULT_EMAIL:-sarthak.agarwal.cse12@iitbhu.ac.in}"
  DEFAULT_NAME="${DEFAULT_NAME:-$DEFAULT_USERNAME}"

  echo "Creating user: $DEFAULT_USERNAME (ID: $DEFAULT_USER_ID)"

  # Insert user
  psql "$DATABASE_URL" <<-EOSQL
    INSERT INTO users (user_id, github_username, email, name, onboarding_completed, created_at)
    VALUES ('$DEFAULT_USER_ID', '$DEFAULT_USERNAME', '$DEFAULT_EMAIL', '$DEFAULT_NAME', true, NOW())
    ON CONFLICT (user_id) DO NOTHING;
EOSQL

  # Insert API key (HASHED version in database)
  psql "$DATABASE_URL" <<-EOSQL
    INSERT INTO cf_api_keys (key, suffix, name, user_id, tier, created_at)
    VALUES ('$API_KEY_HASHED', '$SUFFIX', 'Default API Key', '$DEFAULT_USER_ID', 'free', NOW());
EOSQL

  # Insert subscription with unlimited usage for on-premise deployments
  echo "Creating unlimited subscription for on-premise deployment..."
  psql "$DATABASE_URL" <<-EOSQL
    INSERT INTO subscriptions (
      id,
      user_id,
      stripe_customer_id,
      stripe_subscription_id,
      plan_type,
      optimizations_used,
      optimizations_limit,
      subscription_status,
      created_at,
      updated_at
    )
    VALUES (
      gen_random_uuid(),
      '$DEFAULT_USER_ID',
      NULL,
      NULL,
      'enterprise',
      0,
      999999999,
      'active',
      NOW(),
      NOW()
    )
    ON CONFLICT (user_id) DO NOTHING;
EOSQL

  # Format API key with cf- prefix for display (UNHASHED version for users)
  DISPLAY_API_KEY="cf-${API_KEY_UNHASHED}"

  echo ""
  echo "======================================"
  echo "  CODEFLASH SETUP COMPLETE!"
  echo "======================================"
  echo ""
  echo "User: $DEFAULT_USERNAME"
  echo "Email: $DEFAULT_EMAIL"
  echo ""
  echo "Your API Key: $DISPLAY_API_KEY"
  echo ""
  echo "Save this API key! You'll need it to configure the Codeflash CLI."
  echo ""
  echo "To use the CLI, set these environment variables:"
  echo "  export CODEFLASH_API_KEY=$DISPLAY_API_KEY"
  echo "  export CODEFLASH_AIS_SERVER=local"
  echo "  export CODEFLASH_CFAPI_SERVER=local"
  echo ""
  echo "Or create a .env file in your project:"
  echo "  CODEFLASH_API_KEY=$DISPLAY_API_KEY"
  echo "  CODEFLASH_AIS_SERVER=local"
  echo "  CODEFLASH_CFAPI_SERVER=local"
  echo ""
  echo "======================================"
  echo ""

  # Save API key to file for easy retrieval
  echo "$DISPLAY_API_KEY" > /app/API_KEY.txt
  echo "API key also saved to: /app/API_KEY.txt"
  echo "(Retrieve anytime with: docker exec <container> cat /app/API_KEY.txt)"
  echo ""
else
  echo "Found $USER_COUNT existing user(s). Skipping user creation."
  echo ""
  echo "To retrieve an existing API key, run:"
  echo "  docker exec <container-name> psql \$DATABASE_URL -c \"SELECT key FROM cf_api_keys LIMIT 1;\""
  echo ""
fi

echo "Database initialization complete!"