#!/bin/bash

# Product Hunt Daily Fetch Script
# Fetches top 20 products of the day with their top 10 comments
# Outputs markdown format for AI processing
#
# Usage: ./fetch-producthunt.sh [YYYY-MM-DD]
# If no date provided, uses today's date

TOKEN="TrIg_LxIzJ-Lg9IwxfEMLszuSC7oPyl78fq_iFAeFpE"
API_URL="https://api.producthunt.com/v2/api/graphql"

# Get the date (from argument or today)
if [ -n "$1" ]; then
  TODAY="$1"
  # Calculate tomorrow (macOS vs Linux)
  TOMORROW=$(date -j -f "%Y-%m-%d" -v+1d "$TODAY" +%Y-%m-%d 2>/dev/null || date -d "$TODAY +1 day" +%Y-%m-%d)
else
  TODAY=$(date -u +%Y-%m-%d)
  TOMORROW=$(date -u -v+1d +%Y-%m-%d 2>/dev/null || date -u -d "+1 day" +%Y-%m-%d)
fi

# Build the GraphQL query
read -r -d '' QUERY << 'GRAPHQL'
query($postedAfter: DateTime!, $postedBefore: DateTime!) {
  posts(order: VOTES, first: 20, postedAfter: $postedAfter, postedBefore: $postedBefore) {
    edges {
      node {
        id
        name
        tagline
        votesCount
        commentsCount
        url
        website
        createdAt
        description
        thumbnail {
          url
        }
        comments(first: 10) {
          edges {
            node {
              id
              body
              createdAt
            }
          }
        }
      }
    }
  }
}
GRAPHQL

# Create the JSON payload
PAYLOAD=$(jq -n \
  --arg query "$QUERY" \
  --arg after "${TODAY}T00:00:00Z" \
  --arg before "${TOMORROW}T00:00:00Z" \
  '{query: $query, variables: {postedAfter: $after, postedBefore: $before}}')

# Make the API request
RESPONSE=$(curl -s "$API_URL" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d "$PAYLOAD")

# Check for errors
if echo "$RESPONSE" | jq -e '.errors' > /dev/null 2>&1; then
  echo "# Error fetching Product Hunt data"
  echo ""
  echo '```json'
  echo "$RESPONSE" | jq '.errors'
  echo '```'
  exit 1
fi

# Count products
PRODUCT_COUNT=$(echo "$RESPONSE" | jq '.data.posts.edges | length')

# Output as Markdown
echo "# Product Hunt Top Products - $TODAY"
echo ""
echo "Fetched at: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
echo "Products found: $PRODUCT_COUNT"
echo ""
echo "---"
echo ""

# Parse and format each product with ranking
echo "$RESPONSE" | jq -r '
.data.posts.edges | to_entries | .[] |
"## #\(.key + 1) - \(.value.node.name) - \(.value.node.votesCount) upvotes\n" +
"**Tagline:** \(.value.node.tagline)\n\n" +
"**Description:** \(.value.node.description)\n\n" +
"- **ID:** \(.value.node.id)\n" +
"- **Votes:** \(.value.node.votesCount)\n" +
"- **Comments:** \(.value.node.commentsCount)\n" +
"- **URL:** \(.value.node.url | split("?")[0])\n" +
"- **Website:** \(.value.node.website | split("?")[0])\n" +
"- **Thumbnail:** \(.value.node.thumbnail.url // "none")\n\n" +
"### Top Comments\n\n" +
(if (.value.node.comments.edges | length) > 0 then
  (.value.node.comments.edges | to_entries | map(
    "> **Comment \(.key + 1):**\n> \(.value.node.body | gsub("<[^>]*>"; "") | gsub("\n"; "\n> "))\n"
  ) | join("\n"))
else
  "_No comments yet_\n"
end) +
"\n---\n"
'
