#!/usr/bin/env bash
#
# launch.sh — start the MuveOne Pricer app locally.
#
# What it does, in order:
#   1. Makes sure a local MySQL server is running (starts it via Homebrew if not).
#   2. Ensures the `onemovee_pricer_dev2` database + app user exist and are
#      populated from the SQL dump (imports on first run; skips if already there).
#   3. Clears Laravel's config/cache so .env changes take effect.
#   4. Starts the Laravel dev server (Ctrl+C to stop).
#
# Usage:
#   ./scripts/launch.sh                 # start on http://127.0.0.1:8000
#   ./scripts/launch.sh --port 9000     # use a different port
#   ./scripts/launch.sh --reset-db      # DROP and re-import the database, then start
#   ./scripts/launch.sh --help
#
set -euo pipefail

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
HOST="127.0.0.1"
PORT="8000"
RESET_DB="false"

# Resolve paths relative to this script, so it works from any directory.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="$(dirname "$SCRIPT_DIR")"            # the Laravel app (contains artisan)
ENV_FILE="$APP_DIR/.env"

# Candidate locations for the SQL dump (first match wins).
DUMP_CANDIDATES=(
  "$APP_DIR/../onemovee_pricer_dev2.sql"
  "$APP_DIR/onemovee_pricer_dev2.sql"
  "$APP_DIR/database/onemovee_pricer_dev2.sql"
)

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
c_blue()  { printf "\033[1;34m%s\033[0m\n" "$*"; }
c_green() { printf "\033[1;32m%s\033[0m\n" "$*"; }
c_yellow(){ printf "\033[1;33m%s\033[0m\n" "$*"; }
c_red()   { printf "\033[1;31m%s\033[0m\n" "$*" >&2; }
die()     { c_red "ERROR: $*"; exit 1; }

usage() {
  sed -n '2,16p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
  exit 0
}

# Read a key from .env, stripping trailing CR (CRLF files) and surrounding quotes.
env_get() {
  grep -E "^$1=" "$ENV_FILE" | head -1 | cut -d= -f2- | tr -d '\r' \
    | sed -E 's/^"(.*)"$/\1/; s/^'\''(.*)'\''$/\1/'
}

# ---------------------------------------------------------------------------
# Parse arguments
# ---------------------------------------------------------------------------
while [[ $# -gt 0 ]]; do
  case "$1" in
    --port)     PORT="${2:?--port needs a value}"; shift 2 ;;
    --host)     HOST="${2:?--host needs a value}"; shift 2 ;;
    --reset-db) RESET_DB="true"; shift ;;
    -h|--help)  usage ;;
    *)          die "Unknown option: $1 (use --help)" ;;
  esac
done

# ---------------------------------------------------------------------------
# Locate tools (Herd's PHP + Homebrew MySQL)
# ---------------------------------------------------------------------------
[[ -f "$APP_DIR/artisan" ]] || die "artisan not found in $APP_DIR — is this the app directory?"
[[ -f "$ENV_FILE" ]]        || die ".env not found at $ENV_FILE"
command -v php >/dev/null   || die "php not found on PATH (install Laravel Herd or PHP 8.2+)"

# Prefer mysql on PATH; otherwise fall back to the Homebrew install location.
if command -v mysql >/dev/null; then
  MYSQL_BIN="$(command -v mysql)"
  MYSQLADMIN_BIN="$(command -v mysqladmin)"
elif [[ -x /opt/homebrew/opt/mysql/bin/mysql ]]; then
  MYSQL_BIN="/opt/homebrew/opt/mysql/bin/mysql"
  MYSQLADMIN_BIN="/opt/homebrew/opt/mysql/bin/mysqladmin"
else
  die "mysql client not found. Install it with: brew install mysql"
fi

DB_NAME="$(env_get DB_DATABASE)"
DB_USER="$(env_get DB_USERNAME)"
DB_PASS="$(env_get DB_PASSWORD)"
DB_HOST="$(env_get DB_HOST)"
: "${DB_NAME:?DB_DATABASE missing from .env}"

cd "$APP_DIR"

# ---------------------------------------------------------------------------
# 1. Ensure MySQL is running
# ---------------------------------------------------------------------------
c_blue "==> Checking MySQL..."
if ! "$MYSQLADMIN_BIN" ping -h "${DB_HOST:-127.0.0.1}" --silent >/dev/null 2>&1; then
  if command -v brew >/dev/null; then
    c_yellow "    MySQL not responding — starting it via Homebrew..."
    brew services start mysql >/dev/null 2>&1 || true
  fi
  # Wait up to 60s for it to accept connections.
  for _ in $(seq 1 30); do
    "$MYSQLADMIN_BIN" ping -h "${DB_HOST:-127.0.0.1}" --silent >/dev/null 2>&1 && break
    sleep 2
  done
  "$MYSQLADMIN_BIN" ping -h "${DB_HOST:-127.0.0.1}" --silent >/dev/null 2>&1 \
    || die "MySQL did not come up. Try: brew services start mysql"
fi
c_green "    MySQL is up."

# ---------------------------------------------------------------------------
# 2. Ensure database exists and is populated
# ---------------------------------------------------------------------------
# Admin connection: local Homebrew MySQL 'root' has no password by default.
mysql_root() { "$MYSQL_BIN" -u root "$@"; }

if [[ "$RESET_DB" == "true" ]]; then
  c_yellow "==> --reset-db: dropping database '$DB_NAME'..."
  mysql_root -e "DROP DATABASE IF EXISTS \`$DB_NAME\`;"
fi

# Create database + app user (idempotent) so credentials match .env.
c_blue "==> Ensuring database and user exist..."
mysql_root <<SQL
CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$DB_USER'@'127.0.0.1' IDENTIFIED BY '$DB_PASS';
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'127.0.0.1';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
SQL

# Import the dump only if the schema is empty (first run or after --reset-db).
TABLE_COUNT="$(mysql_root -N -e \
  "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" 2>/dev/null || echo 0)"
if [[ "$TABLE_COUNT" -eq 0 ]]; then
  DUMP=""
  for f in "${DUMP_CANDIDATES[@]}"; do [[ -f "$f" ]] && DUMP="$f" && break; done
  [[ -n "$DUMP" ]] || die "SQL dump not found. Looked in: ${DUMP_CANDIDATES[*]}"
  c_yellow "==> Importing data from: $DUMP"
  mysql_root "$DB_NAME" < "$DUMP"
  c_green "    Import complete."
else
  c_green "    Database already populated ($TABLE_COUNT tables) — skipping import."
  c_yellow "    (Re-import a fresh copy with: ./scripts/launch.sh --reset-db)"
fi

# ---------------------------------------------------------------------------
# 3. Clear Laravel caches
# ---------------------------------------------------------------------------
c_blue "==> Clearing Laravel caches..."
php artisan config:clear >/dev/null 2>&1 || true
php artisan cache:clear  >/dev/null 2>&1 || true
c_green "    Caches cleared."

# ---------------------------------------------------------------------------
# 4. Start the dev server
# ---------------------------------------------------------------------------
echo
c_green  "================================================================"
c_green  "  MuveOne Pricer is starting"
c_green  "  URL:    http://$HOST:$PORT"
c_green  "  Login:  logistics@muveone.co.uk"
c_green  "  Stop:   press Ctrl+C"
c_green  "================================================================"
echo
exec php artisan serve --host="$HOST" --port="$PORT"
