#!/usr/bin/env bash
# Batch-upload fake crash reports (java + native) from test_reports/.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
REPORTS_DIR="${REPORTS_DIR:-$ROOT/test_reports}"
BASE="${BASE:-https://apps.f0xx.org/app/androidcast_project/crashes}"
UPLOAD_URL="$BASE/api/upload.php"
JAR="${JAR:-/tmp/ac_crash_cookies.txt}"
LOGIN="${LOGIN:-0}"
DELAY_MS="${DELAY_MS:-50}"
ONLY="${ONLY:-all}" # all | java | native

if [[ ! -d "$REPORTS_DIR" ]]; then
  echo "Missing $REPORTS_DIR — run: python3 $ROOT/generate_test_reports.py" >&2
  exit 1
fi

shopt -s nullglob
FILES=()
case "$ONLY" in
  java)
    FILES=("$REPORTS_DIR"/crash_java_*.json)
    ;;
  native)
    FILES=("$REPORTS_DIR"/crash_native_*.json)
    ;;
  all|*)
    FILES=("$REPORTS_DIR"/crash_java_*.json "$REPORTS_DIR"/crash_native_*.json)
    # legacy single-prefix files from older generator
    LEGACY=("$REPORTS_DIR"/crash_[0-9][0-9][0-9].json)
    if [[ ${#FILES[@]} -eq 0 && ${#LEGACY[@]} -gt 0 ]]; then
      FILES=("${LEGACY[@]}")
    fi
    ;;
esac
shopt -u nullglob

if [[ ${#FILES[@]} -eq 0 ]]; then
  echo "No reports in $REPORTS_DIR (expected crash_java_*.json / crash_native_*.json)" >&2
  exit 1
fi

IFS=$'\n' FILES=($(printf '%s\n' "${FILES[@]}" | sort))
unset IFS

java_n=0
native_n=0
for f in "${FILES[@]}"; do
  case "$(basename "$f")" in
    crash_java_*) ((java_n++)) || true ;;
    crash_native_*) ((native_n++)) || true ;;
  esac
done

if [[ "$LOGIN" == "1" ]]; then
  curl -sk -c "$JAR" -b "$JAR" -L -X POST "$BASE/login" \
    -d 'username=admin&password=admin' -o /dev/null
  echo "Logged in (cookie jar: $JAR)"
fi

ok=0
fail=0
dup=0
ok_java=0
ok_native=0

echo "Uploading ${#FILES[@]} reports to $UPLOAD_URL (java=$java_n native=$native_n only=$ONLY)"

for f in "${FILES[@]}"; do
  name="$(basename "$f")"
  body="$(curl -sk -w '\n%{http_code}' -H 'Content-Type: application/json' --data-binary "@$f" "$UPLOAD_URL")"
  code="$(echo "$body" | tail -n1)"
  json="$(echo "$body" | sed '$d')"

  case "$code" in
    200)
      ((ok++)) || true
      case "$name" in
        crash_java_*) ((ok_java++)) || true; echo "  OK   [java]   $name" ;;
        crash_native_*) ((ok_native++)) || true; echo "  OK   [native] $name" ;;
        *) echo "  OK   $name" ;;
      esac
      ;;
    409)
      ((dup++)) || true
      echo "  DUP  $name (report_id already stored)"
      ;;
    *)
      ((fail++)) || true
      echo "  FAIL $name HTTP $code — $json" >&2
      ;;
  esac

  if [[ "$DELAY_MS" -gt 0 ]]; then
    sleep "$(awk "BEGIN { print $DELAY_MS / 1000 }")"
  fi
done

echo "Done: ok=$ok (java=$ok_java native=$ok_native) duplicate=$dup failed=$fail (total=${#FILES[@]})"
[[ "$fail" -eq 0 ]]
