#!/bin/bash

# Semantic Scholar API paper search script
# Usage: ./search-papers.sh "query" [--year YYYY-YYYY] [--venue VENUE] [--limit N]

QUERY="$1"
YEAR=""
VENUE=""
LIMIT="20"

# Parse optional arguments
shift
while [[ $# -gt 0 ]]; do
    case $1 in
        --year)
            YEAR="$2"
            shift 2
            ;;
        --venue)
            VENUE="$2"
            shift 2
            ;;
        --limit)
            LIMIT="$2"
            shift 2
            ;;
        *)
            shift
            ;;
    esac
done

# URL encode the query
ENCODED_QUERY=$(echo "$QUERY" | sed 's/ /%20/g')

# Build the API URL
API_URL="https://api.semanticscholar.org/graph/v1/paper/search?query=$ENCODED_QUERY&limit=$LIMIT&fields=title,authors,year,venue,citationCount,abstract,paperId"

# Add year filter if provided
if [ ! -z "$YEAR" ]; then
    API_URL="${API_URL}&year=${YEAR}"
fi

# Add venue filter if provided
if [ ! -z "$VENUE" ]; then
    VENUE_ENCODED=$(echo "$VENUE" | sed 's/ /%20/g')
    API_URL="${API_URL}&venue=${VENUE_ENCODED}"
fi

# Make the API call
curl -s "$API_URL" | python3 -m json.tool