#!/bin/bash
# TCG Price Lookup - scrapes PriceCharting for Pokemon card values
# Usage: tcg-price.sh "card name"
# Example: tcg-price.sh "charizard base set"

CARD_NAME="${1:-charizard}"

# URL encode the search
SEARCH_QUERY=$(echo "$CARD_NAME" | sed 's/ /+/g')
URL="https://www.pricecharting.com/search-products?q=${SEARCH_QUERY}+pokemon&type=prices"

echo "🔍 Searching PriceCharting for: $CARD_NAME"
echo ""

# Get search results page
SEARCH_PAGE=$(curl -sL "$URL")

# Extract card links (look for /game/ links)
RESULTS=$(echo "$SEARCH_PAGE" | grep -o 'href="/game/[^"]*pokemon[^"]*"' | sed 's/href="\/game\///;s/"$//' | head -5)

if [ -z "$RESULTS" ]; then
    echo "❌ No results found for '$CARD_NAME'"
    exit 1
fi

echo "📋 Found cards:"
echo "$RESULTS" | head -3 | while read -r card; do
    echo "  → https://www.pricecharting.com/game/$card"
done

echo ""

# Get first result details
FIRST_CARD=$(echo "$RESULTS" | head -1)
CARD_URL="https://www.pricecharting.com/game/$FIRST_CARD"

echo "💰 Price data for: $FIRST_CARD"
echo "🔗 $CARD_URL"
echo ""

# Fetch card page
CARD_PAGE=$(curl -sL "$CARD_URL")

# Extract title
TITLE=$(echo "$CARD_PAGE" | grep -o '<title>[^<]*' | sed 's/<title>//')
echo "📦 $TITLE"
echo ""

# Extract prices (dollar amounts)
echo "Recent sale prices:"
echo "$CARD_PAGE" | grep -oE '\$[0-9,]+\.[0-9]{2}' | sort -u | head -8 | while read -r price; do
    echo "  $price"
done
