#!/bin/bash
# test_yt_key.sh — Verify the YouTube Data API v3 key in ../yt_key.txt

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
BASE_DIR="$(dirname "$SCRIPT_DIR")"
KEY_FILE="$BASE_DIR/data/yt_key.txt"

if [ ! -f "$KEY_FILE" ]; then
    echo "ERROR: Key file not found: $KEY_FILE"
    exit 1
fi

KEY=$(tr -d '[:space:]' < "$KEY_FILE")

if [ -z "$KEY" ]; then
    echo "ERROR: yt_key.txt is empty"
    exit 1
fi

echo "Key: $(echo "$KEY" | cut -c1-8)...$(echo "$KEY" | rev | cut -c1-8 | rev)"
echo "Testing against YouTube Data API v3..."

RESPONSE=$(curl -s --max-time 10 \
    "https://www.googleapis.com/youtube/v3/videos?id=dQw4w9WgXcQ&part=id&key=${KEY}")

if [ $? -ne 0 ]; then
    echo "ERROR: curl failed — no response from YouTube API"
    exit 1
fi

if echo "$RESPONSE" | grep -q '"items"'; then
    echo "OK: API key is valid and quota is accessible"
    exit 0
elif echo "$RESPONSE" | grep -q '"error"'; then
    REASON=$(echo "$RESPONSE" | grep -o '"reason": *"[^"]*"' | head -1 | sed 's/.*: *"//' | sed 's/"//')
    echo "ERROR: API returned error — ${REASON:-see response below}"
    echo "$RESPONSE" | grep -o '"message": *"[^"\\]*"' | head -1
    exit 1
else
    echo "ERROR: Unexpected response:"
    echo "$RESPONSE"
    exit 1
fi
