#!/bin/bash
# Create a stock avatar from uploaded props and set it as server default.
#
# Usage: ./stock/avatar/create-stock-avatar.sh [--force|-f] [HOST]
#
# Prerequisites:
#   1. Props must be uploaded first: ./stock/avatar/upload-stockavatars.sh
#   2. Dev server must be running: ./run-dev.sh -f
#
# This script:
#   1. Queries existing props by slug to get UUIDs
#   2. Creates a server avatar with all emotion slots populated
#   3. Sets the avatar as the server default for all gender/age combinations

set -e

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

for arg in "$@"; do
    case "$arg" in
        --force|-f)
            FORCE="?force=true"
            ;;
        http://*)
            HOST="$arg"
            ;;
    esac
done

echo "=========================================="
echo "Creating Stock Avatar"
echo "=========================================="
echo "Host: $HOST"
echo "Database: $DB"
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 "Make sure the server is running: ./run-dev.sh -f"
    exit 1
fi
echo "Server is healthy!"
echo ""

# Query prop UUIDs by slug
echo "Querying prop UUIDs..."

get_prop_id() {
    local slug="$1"
    psql -d "$DB" -t -A -c "SELECT id FROM server.props WHERE slug = '$slug'" 2>/dev/null | tr -d '[:space:]'
}

# Get face prop (skin layer)
FACE_ID=$(get_prop_id "face")
if [ -z "$FACE_ID" ]; then
    echo "ERROR: Face prop not found. Run upload-stockavatars.sh first."
    exit 1
fi
echo "  face: $FACE_ID"

# Get emotion props
NEUTRAL_ID=$(get_prop_id "neutral")
SMILE_ID=$(get_prop_id "smile")      # This is "happy" emotion
SAD_ID=$(get_prop_id "sad")
ANGRY_ID=$(get_prop_id "angry")
SURPRISED_ID=$(get_prop_id "surprised")
THINKING_ID=$(get_prop_id "thinking")
LAUGHING_ID=$(get_prop_id "laughing")
CRYING_ID=$(get_prop_id "crying")
LOVE_ID=$(get_prop_id "love")
CONFUSED_ID=$(get_prop_id "confused")
SLEEPING_ID=$(get_prop_id "sleeping")
WINK_ID=$(get_prop_id "wink")

# Validate all emotion props exist
missing=""
[ -z "$NEUTRAL_ID" ] && missing="$missing neutral"
[ -z "$SMILE_ID" ] && missing="$missing smile"
[ -z "$SAD_ID" ] && missing="$missing sad"
[ -z "$ANGRY_ID" ] && missing="$missing angry"
[ -z "$SURPRISED_ID" ] && missing="$missing surprised"
[ -z "$THINKING_ID" ] && missing="$missing thinking"
[ -z "$LAUGHING_ID" ] && missing="$missing laughing"
[ -z "$CRYING_ID" ] && missing="$missing crying"
[ -z "$LOVE_ID" ] && missing="$missing love"
[ -z "$CONFUSED_ID" ] && missing="$missing confused"
[ -z "$SLEEPING_ID" ] && missing="$missing sleeping"
[ -z "$WINK_ID" ] && missing="$missing wink"

if [ -n "$missing" ]; then
    echo "ERROR: Missing emotion props:$missing"
    echo "Run upload-stockavatars.sh first."
    exit 1
fi

echo "  neutral: $NEUTRAL_ID"
echo "  smile (happy): $SMILE_ID"
echo "  sad: $SAD_ID"
echo "  angry: $ANGRY_ID"
echo "  surprised: $SURPRISED_ID"
echo "  thinking: $THINKING_ID"
echo "  laughing: $LAUGHING_ID"
echo "  crying: $CRYING_ID"
echo "  love: $LOVE_ID"
echo "  confused: $CONFUSED_ID"
echo "  sleeping: $SLEEPING_ID"
echo "  wink: $WINK_ID"
echo ""

# Check if avatar already exists
existing_avatar=$(psql -d "$DB" -t -A -c "SELECT id FROM server.avatars WHERE slug = 'stock-avatar'" 2>/dev/null | tr -d '[:space:]')

if [ -n "$existing_avatar" ] && [ -z "$FORCE" ]; then
    echo "Stock avatar already exists with ID: $existing_avatar"
    echo "Use --force to recreate it."
    AVATAR_ID="$existing_avatar"
else
    # Create the avatar via API
    echo "Creating stock avatar via API..."

    # Build the JSON payload
    avatar_json=$(cat <<EOF
{
    "name": "Stock Avatar",
    "slug": "stock-avatar",
    "description": "Default stock avatar with all emotion faces",
    "is_public": true,
    "l_skin_4": "$FACE_ID",
    "e_neutral_4": "$NEUTRAL_ID",
    "e_happy_4": "$SMILE_ID",
    "e_sad_4": "$SAD_ID",
    "e_angry_4": "$ANGRY_ID",
    "e_surprised_4": "$SURPRISED_ID",
    "e_thinking_4": "$THINKING_ID",
    "e_laughing_4": "$LAUGHING_ID",
    "e_crying_4": "$CRYING_ID",
    "e_love_4": "$LOVE_ID",
    "e_confused_4": "$CONFUSED_ID",
    "e_sleeping_4": "$SLEEPING_ID",
    "e_wink_4": "$WINK_ID"
}
EOF
)

    # Delete existing if force mode
    if [ -n "$existing_avatar" ]; then
        echo "  Deleting existing avatar..."
        curl -s -X DELETE "$HOST/api/admin/avatars/$existing_avatar" > /dev/null
    fi

    # Create the avatar
    response=$(curl -s -w "\n%{http_code}" -X POST "$HOST/api/admin/avatars" \
        -H "Content-Type: application/json" \
        -d "$avatar_json")

    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
        AVATAR_ID=$(echo "$body" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
        echo "  ✓ Created avatar: $AVATAR_ID"
    else
        echo "  ✗ Failed to create avatar (HTTP $http_code): $body"
        exit 1
    fi
fi

echo ""

# Set as server default for all gender/age combinations
echo "Setting stock avatar as server defaults..."

psql -d "$DB" -c "
UPDATE server.config SET
    default_avatar_neutral_child = '$AVATAR_ID',
    default_avatar_neutral_adult = '$AVATAR_ID',
    default_avatar_male_child = '$AVATAR_ID',
    default_avatar_male_adult = '$AVATAR_ID',
    default_avatar_female_child = '$AVATAR_ID',
    default_avatar_female_adult = '$AVATAR_ID',
    updated_at = now()
WHERE id = '00000000-0000-0000-0000-000000000001'
" > /dev/null

echo "  ✓ Set all 6 default avatar columns"
echo ""

# Verify
echo "=========================================="
echo "Verification"
echo "=========================================="

# Check avatar slots
echo "Avatar emotion slots populated:"
psql -d "$DB" -t -c "
SELECT
    CASE WHEN l_skin_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' body (l_skin_4)',
    CASE WHEN e_neutral_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' neutral',
    CASE WHEN e_happy_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' happy',
    CASE WHEN e_sad_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' sad',
    CASE WHEN e_angry_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' angry',
    CASE WHEN e_surprised_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' surprised',
    CASE WHEN e_thinking_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' thinking',
    CASE WHEN e_laughing_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' laughing',
    CASE WHEN e_crying_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' crying',
    CASE WHEN e_love_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' love',
    CASE WHEN e_confused_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' confused',
    CASE WHEN e_sleeping_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' sleeping',
    CASE WHEN e_wink_4 IS NOT NULL THEN '✓' ELSE '✗' END || ' wink'
FROM server.avatars WHERE slug = 'stock-avatar'
" | tr '|' '\n' | grep -v '^$' | sed 's/^ */  /'

echo ""

# Check server defaults
echo "Server config defaults:"
psql -d "$DB" -t -c "
SELECT
    CASE WHEN default_avatar_neutral_adult IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_neutral_adult',
    CASE WHEN default_avatar_neutral_child IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_neutral_child',
    CASE WHEN default_avatar_male_adult IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_male_adult',
    CASE WHEN default_avatar_male_child IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_male_child',
    CASE WHEN default_avatar_female_adult IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_female_adult',
    CASE WHEN default_avatar_female_child IS NOT NULL THEN '✓' ELSE '✗' END || ' default_avatar_female_child'
FROM server.config WHERE id = '00000000-0000-0000-0000-000000000001'
" | tr '|' '\n' | grep -v '^$' | sed 's/^ */  /'

echo ""
echo "=========================================="
echo "Stock avatar setup complete!"
echo "Avatar ID: $AVATAR_ID"
echo "=========================================="
