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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

BASE_URL="${LINEUP_BASE_URL:-https://lineupfrance.com}"
RUN_TESTS=0
RUN_SMOKE=1
RUN_MIGRATE=1

usage() {
  cat <<'EOF'
Usage:
  ./scripts/go_live_v1.sh [--url <base_url>] [--with-tests] [--skip-smoke] [--skip-migrate]

Examples:
  ./scripts/go_live_v1.sh --url https://lineupfrance.com
  ./scripts/go_live_v1.sh --url https://lineupfrance.com --with-tests
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --url)
      BASE_URL="${2:-}"
      shift 2
      ;;
    --with-tests)
      RUN_TESTS=1
      shift
      ;;
    --skip-smoke)
      RUN_SMOKE=0
      shift
      ;;
    --skip-migrate)
      RUN_MIGRATE=0
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1"
      usage
      exit 1
      ;;
  esac
done

if [[ -z "$BASE_URL" ]]; then
  echo "ERROR: --url cannot be empty."
  exit 1
fi

echo "== LineUp France go-live v1 =="
echo "Root: $ROOT_DIR"
echo "Base URL: $BASE_URL"
echo

if [[ ! -f ".env" ]]; then
  echo "ERROR: .env is missing in $ROOT_DIR"
  exit 2
fi

if grep -q "/Users/gsent/" .env; then
  echo "ERROR: .env contains local macOS paths (/Users/gsent/...)."
  echo "Fix .env before go-live."
  exit 2
fi

echo
echo "-- Verifying critical source files --"
empty_php_files="$(find app -type f -name '*.php' -size 0 -print)"
if [[ -n "$empty_php_files" ]]; then
  echo "ERROR: Empty PHP file(s) detected in app/:"
  echo "$empty_php_files"
  echo "Fix these files before go-live."
  exit 2
fi
echo "OK: no empty PHP file found in app/"

echo
echo "-- Resetting stale bootstrap cache files --"
mkdir -p bootstrap/cache storage/logs
rm -f bootstrap/cache/config.php \
      bootstrap/cache/events.php \
      bootstrap/cache/routes.php \
      bootstrap/cache/routes-v7.php \
      bootstrap/cache/packages.php \
      bootstrap/cache/services.php

required_icon_fonts=(
  "public/oneui/custom/fonts/Simple-Line-Icons.woff2"
  "public/oneui/custom/fonts/fa-solid-900.woff2"
  "public/oneui/custom/fonts/fa-regular-400.woff2"
)
for font_path in "${required_icon_fonts[@]}"; do
  if [[ ! -f "$font_path" ]]; then
    echo "ERROR: Missing icon font file: $font_path"
    exit 3
  fi
done
echo "OK: icon font files present"

echo
echo "-- Clearing caches --"
if ! php artisan optimize:clear; then
  echo "WARN: optimize:clear failed with current cache store."
  echo "Retrying with CACHE_STORE=file for bootstrap cleanup..."
  CACHE_STORE=file php artisan optimize:clear
fi

if [[ "$RUN_TESTS" -eq 1 ]]; then
  echo
  echo "-- Running feature tests --"
  TEST_CACHE_ROOT="/tmp/lineup-test-cache-${USER:-lineup}-$$"
  mkdir -p "$TEST_CACHE_ROOT"

  APP_CONFIG_CACHE="$TEST_CACHE_ROOT/config.php" \
  APP_EVENTS_CACHE="$TEST_CACHE_ROOT/events.php" \
  APP_PACKAGES_CACHE="$TEST_CACHE_ROOT/packages.php" \
  APP_SERVICES_CACHE="$TEST_CACHE_ROOT/services.php" \
  APP_ROUTES_CACHE="$TEST_CACHE_ROOT/routes-v7.php" \
  CACHE_STORE=array \
  php artisan test --testsuite=Feature

  rm -rf "$TEST_CACHE_ROOT"
fi

if [[ "$RUN_MIGRATE" -eq 1 ]]; then
  echo
  echo "-- Running migrations --"
  php artisan migrate --force
fi

echo
echo "-- Verifying cache tables --"
if ! php artisan db:table cache >/dev/null 2>&1 || ! php artisan db:table cache_locks >/dev/null 2>&1; then
  echo "WARN: cache tables are missing, creating them via schema fallback..."
  php artisan tinker --execute='use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; if (!Schema::hasTable("cache")) { Schema::create("cache", function (Blueprint $table) { $table->string("key")->primary(); $table->mediumText("value"); $table->integer("expiration")->index(); }); } if (!Schema::hasTable("cache_locks")) { Schema::create("cache_locks", function (Blueprint $table) { $table->string("key")->primary(); $table->string("owner"); $table->integer("expiration")->index(); }); }'
fi

if [[ ! -L "public/storage" ]]; then
  echo
  echo "-- Creating storage symlink --"
  php artisan storage:link
fi

echo
echo "-- Optimizing app --"
php artisan optimize

echo
echo "-- Running preflight --"
./scripts/preflight_cpanel.sh

if [[ "$RUN_SMOKE" -eq 1 ]]; then
  echo
  echo "-- Running smoke --"
  ./scripts/smoke_web.sh "$BASE_URL"

  echo
  echo "-- Checking icon font HTTP availability --"
  check_font_http() {
    local path="$1"
    local status
    status="$(curl -sS -I -o /tmp/lineup_font_check.$$ -w "%{http_code}" "$BASE_URL$path" || true)"
    if [[ "$status" != "200" ]]; then
      echo "ERROR: $path returned HTTP $status"
      rm -f /tmp/lineup_font_check.$$
      exit 4
    fi

    if ! grep -Eiq '^content-type:\s*(font/|application/(font-woff|octet-stream)|binary/octet-stream)' /tmp/lineup_font_check.$$; then
      echo "WARN: $path returned unexpected Content-Type"
      sed -n '1,20p' /tmp/lineup_font_check.$$
    else
      echo "OK: $path"
    fi
    rm -f /tmp/lineup_font_check.$$
  }

  check_font_http "/oneui/custom/fonts/Simple-Line-Icons.woff2"
  check_font_http "/oneui/custom/fonts/fa-solid-900.woff2"
  check_font_http "/oneui/custom/fonts/fa-regular-400.woff2"
fi

echo
echo "GO-LIVE V1 CHECK: OK"
