#!/bin/bash
# Upload all stock props to the server.
#
# Usage: ./stock/props/upload-stockprops.sh [--force|-f] [HOST]
#
# Options:
#   --force, -f   Update existing props instead of failing with 409 Conflict
#
# HOST defaults to http://localhost:3001 (owner admin port)
#
# Prerequisites:
#   1. Run the dev server: ./run-dev.sh -f
#   2. Wait for it to finish building: ./run-dev.sh -s
#
# The owner admin server (port 3001) uses the chattyness_owner DB role
# which bypasses RLS, so no authentication is required.

set -e

# Parse arguments
FORCE=""
HOST="http://localhost:3001"

for arg in "$@"; do
    case "$arg" in
        --force|-f)
            FORCE="?force=true"
            ;;
        http://*)
            HOST="$arg"
            ;;
    esac
done
# Script directory is the stock/props directory
PROPS_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "Uploading stock props to $HOST/api/admin/props"
echo "Source directory: $PROPS_DIR"
echo ""

# Check if server is running
echo "Checking server health..."
health_response=$(curl -s -o /dev/null -w "%{http_code}" "$HOST/api/admin/health" 2>/dev/null || echo "000")
if [ "$health_response" != "200" ]; then
    echo "ERROR: Server is not responding at $HOST (HTTP $health_response)"
    echo ""
    echo "Make sure the server is running:"
    echo "  ./run-dev.sh -f"
    echo "  ./run-dev.sh -s  # Check status"
    exit 1
fi
echo "Server is healthy!"
echo ""

# Function to create display name from filename
# e.g., "hookah-traditional.svg" -> "Hookah Traditional"
make_display_name() {
    local filename="$1"
    local name_without_ext="${filename%.svg}"
    # Replace hyphens with spaces and capitalize each word
    echo "$name_without_ext" | sed 's/-/ /g' | sed 's/\b\(.\)/\u\1/g'
}

# Function to extract category from filename
# e.g., "hookah-traditional.svg" -> "hookah"
get_category() {
    local filename="$1"
    local name_without_ext="${filename%.svg}"
    echo "${name_without_ext%%-*}"
}

# Function to determine tags based on category
get_tags() {
    local category="$1"
    case "$category" in
    hookah)
        echo '["hookah", "smoking", "droppable"]'
        ;;
    coffee)
        echo '["coffee", "beverage", "droppable"]'
        ;;
    soda)
        echo '["soda", "beverage", "droppable"]'
        ;;
    tea)
        echo '["tea", "beverage", "droppable"]'
        ;;
    misc)
        echo '["misc", "droppable"]'
        ;;
    screen)
        echo '["screen", "projector", "droppable"]'
        ;;
    keyboard)
        echo '["keyboard", "media", "droppable"]'
        ;;
    *)
        echo '["prop", "droppable"]'
        ;;
    esac
}

# Track success/failure counts
success_count=0
fail_count=0

# Upload each SVG file
for file in "$PROPS_DIR"/*.svg; do
    if [ ! -f "$file" ]; then
        continue
    fi

    filename=$(basename "$file")
    display_name=$(make_display_name "$filename")
    category=$(get_category "$filename")
    tags=$(get_tags "$category")

    echo "Uploading: $filename -> $display_name (category: $category)"

    # Create metadata JSON - props are droppable loose items and public by default
    metadata=$(cat <<EOF
{
    "name": "$display_name",
    "tags": $tags,
    "droppable": true,
    "public": true
}
EOF
    )

    # Upload via curl
    response=$(curl -s -w "\n%{http_code}" -X POST "$HOST/api/admin/props$FORCE" \
        -F "metadata=$metadata" \
        -F "file=@$file")

    # Extract HTTP status code (last line)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
        echo "  Success: $body"
        ((++success_count))
    else
        echo "  Failed (HTTP $http_code): $body"
        ((++fail_count))
    fi

    echo ""
done

echo "=========================================="
echo "Upload complete: $success_count succeeded, $fail_count failed"
