#!/bin/sh
# hn-marketing.sh — Fetch top 10 HN stories and save to CSV
# Dependencies: curl, jq (install with: apk add -q curl jq)

set -e

CSV="${HN_CSV:-./hn-top10.csv}"
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")

# Write CSV header if file doesn't exist
if [ ! -f "$CSV" ]; then
  echo "timestamp,rank,score,title,url,hn_link" > "$CSV"
fi

echo "=== HN Top 10 ==="
echo "Fetched at: $TIMESTAMP"
echo ""

# Get top 10 story IDs
IDS=$(curl -sf "https://hacker-news.firebaseio.com/v0/topstories.json" | jq -r '.[0:10] | .[]')

RANK=0
for ID in $IDS; do
  RANK=$((RANK + 1))
  ITEM=$(curl -sf "https://hacker-news.firebaseio.com/v0/item/${ID}.json")

  TITLE=$(echo "$ITEM" | jq -r '.title // "untitled"' | tr -d '\n\r' | sed 's/,/;/g')
  URL=$(echo "$ITEM" | jq -r '.url // ""' | tr -d '\n\r')
  SCORE=$(echo "$ITEM" | jq -r '.score // 0')
  HN_LINK="https://news.ycombinator.com/item?id=$ID"

  [ -z "$URL" ] && URL="$HN_LINK"

  echo "[$RANK] $TITLE"
  echo "    Score: $SCORE | $URL"
  echo ""

  echo "$TIMESTAMP,$RANK,$SCORE,$TITLE,$URL,$HN_LINK" >> "$CSV"
done

echo "---"
echo "Saved to $CSV"
