#!/usr/bin/env bash
# One-time local setup for macOS: Postgres 18 + DB restore + backend venv + frontend deps.
#
# Usage (from the repo root):
#   ./scripts/setup_mac.sh /path/to/Audi_db.sql
#
# Safe to re-run. Pass --reset-db to drop and re-restore erp_db.
set -euo pipefail

# Override any of these by exporting them before running the script.
DB_NAME="${DB_NAME:-erp_db}"
DB_USER="${DB_USER:-erp_user}"
DB_PASS="${DB_PASS:-erp_2026}"
PG_VER=18

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DUMP=""
RESET_DB=0
for arg in "$@"; do
  case "$arg" in
    --reset-db) RESET_DB=1 ;;
    *) DUMP="$arg" ;;
  esac
done

step() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
die()  { printf '\033[1;31mError: %s\033[0m\n' "$*" >&2; exit 1; }

# ---------------------------------------------------------------- Homebrew
step "Checking Homebrew"
if ! command -v brew >/dev/null; then
  die "Homebrew not found. Install it first: https://brew.sh  then re-run this script."
fi

step "Installing PostgreSQL $PG_VER, Python 3.12, Node (skips what is already installed)"
brew list postgresql@$PG_VER >/dev/null 2>&1 || brew install postgresql@$PG_VER
brew list python@3.12       >/dev/null 2>&1 || brew install python@3.12
command -v node >/dev/null || brew install node

PG_BIN="$(brew --prefix postgresql@$PG_VER)/bin"
export PATH="$PG_BIN:$PATH"
PY="$(brew --prefix python@3.12)/bin/python3.12"

# ---------------------------------------------------------------- Postgres
step "Starting PostgreSQL $PG_VER"
brew services start postgresql@$PG_VER >/dev/null || true
for _ in $(seq 1 20); do pg_isready -q -h localhost && break; sleep 1; done
pg_isready -q -h localhost || die "Postgres did not start. Check: brew services list  (another Postgres on port 5432?)"

# Homebrew creates a superuser named after your macOS account; connect to the default 'postgres' db.
SUPER="psql -h localhost -d postgres -v ON_ERROR_STOP=1 -qtA"

step "Creating role '$DB_USER'"
if [ "$($SUPER -c "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'")" != "1" ]; then
  $SUPER -c "CREATE ROLE $DB_USER LOGIN PASSWORD '$DB_PASS' CREATEDB"
else
  $SUPER -c "ALTER ROLE $DB_USER WITH LOGIN PASSWORD '$DB_PASS'"
fi

count_tables() {
  PGPASSWORD="$DB_PASS" psql -h localhost -U "$DB_USER" -d "$DB_NAME" -qtA \
    -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public'"
}

DB_EXISTS="$($SUPER -c "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'")"
if [ "$DB_EXISTS" = "1" ] && [ "$RESET_DB" = "1" ]; then
  step "Dropping existing '$DB_NAME' (--reset-db)"
  $SUPER -c "DROP DATABASE $DB_NAME WITH (FORCE)"
  DB_EXISTS=""
fi

# An existing but empty database (e.g. from an earlier failed restore) is restored into, not skipped.
if [ "$DB_EXISTS" = "1" ] && [ "$(count_tables)" != "0" ]; then
  step "Database '$DB_NAME' already has $(count_tables) tables, so the restore is skipped (use --reset-db to re-restore)"
else
  [ -n "$DUMP" ] || die "Pass the dump file path: ./scripts/setup_mac.sh ~/Downloads/Audi_db.sql"
  [ -f "$DUMP" ] || die "Dump file not found: $DUMP"

  if [ "$DB_EXISTS" != "1" ]; then
    step "Creating database '$DB_NAME'"
    # The dump was taken on Windows (locale English_United States.1252), so we create the DB
    # ourselves with a macOS-friendly UTF8 locale instead of letting pg_restore --create do it.
    $SUPER -c "CREATE DATABASE $DB_NAME OWNER $DB_USER ENCODING 'UTF8' TEMPLATE template0"
  fi

  step "Restoring $DUMP into '$DB_NAME' with $(pg_restore --version)"
  # --no-owner/--no-privileges: everything ends up owned by erp_user, no Windows-specific grants.
  # Not --exit-on-error: one harmless error shouldn't abort the whole restore; errors are listed instead.
  LOG="$ROOT/restore.log"
  if ! PGPASSWORD="$DB_PASS" pg_restore -h localhost -U "$DB_USER" -d "$DB_NAME" \
      --no-owner --no-privileges "$DUMP" 2>"$LOG"; then
    printf '\033[1;33mpg_restore reported errors (full log: %s):\033[0m\n' "$LOG"
    grep -i "error" "$LOG" | head -n 20
  fi

  TABLES="$(count_tables)"
  [ "$TABLES" != "0" ] || die "Restore produced 0 tables. See $LOG"
  echo "Restored $TABLES tables."
fi

# ---------------------------------------------------------------- Backend
step "Setting up backend virtualenv"
cd "$ROOT/backend"
# Recreate a venv that isn't a working macOS one (e.g. copied from Windows, or half-created).
if [ ! -x venv/bin/python ] || ! venv/bin/python -c "import sys" >/dev/null 2>&1; then
  rm -rf venv
  "$PY" -m venv venv
fi
./venv/bin/python -m pip install -q --upgrade pip
./venv/bin/pip install -q -r requirements.txt

if [ ! -f .env ]; then
  step "Writing backend/.env"
  cat > .env <<EOF
DATABASE_URL=postgresql+asyncpg://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME
DATABASE_URL_SYNC=postgresql://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME
ALLOWED_ORIGINS=["http://localhost:5173", "http://127.0.0.1:5173", "http://localhost:3000"]
ALLOWED_ORIGIN_REGEX=http://(192\\.168\\.[0-9]{1,3}\\.[0-9]{1,3}|10\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|172\\.(1[6-9]|2[0-9]|3[01])\\.[0-9]{1,3}\\.[0-9]{1,3}):5173
SECRET_KEY=$(openssl rand -hex 32)
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=43200
REFRESH_TOKEN_EXPIRE_DAYS=30
DEBUG=True
EOF
else
  step "backend/.env already exists, so it is left unchanged"
fi

step "Applying database migrations (adds anything newer than your dump)"
./venv/bin/alembic upgrade head

# ---------------------------------------------------------------- Frontend
step "Installing frontend dependencies"
cd "$ROOT/frontend"
npm install --no-audit --no-fund

step "Done. Start the app with:  ./scripts/run_mac.sh"
