#!/bin/bash
# Fetch Google Doc/Sheet/Slides content using Gee's OAuth tokens
# Usage: ./fetch-google-doc.sh <url>

set -e

URL="$1"
CONFIG_DIR="$HOME/.config/bebot"
OAUTH_FILE="$CONFIG_DIR/google-oauth.json"
TOKENS_FILE="$CONFIG_DIR/google-tokens.json"

if [ -z "$URL" ]; then
  echo "Usage: $0 <google-doc-url>"
  exit 1
fi

# Extract document ID and type
if [[ "$URL" =~ docs\.google\.com/document/d/([a-zA-Z0-9_-]+) ]]; then
  DOC_ID="${BASH_REMATCH[1]}"
  DOC_TYPE="doc"
elif [[ "$URL" =~ docs\.google\.com/spreadsheets/d/([a-zA-Z0-9_-]+) ]]; then
  DOC_ID="${BASH_REMATCH[1]}"
  DOC_TYPE="sheet"
elif [[ "$URL" =~ docs\.google\.com/presentation/d/([a-zA-Z0-9_-]+) ]]; then
  DOC_ID="${BASH_REMATCH[1]}"
  DOC_TYPE="slides"
else
  echo "ERROR: Not a recognized Google Doc/Sheet/Slides URL"
  exit 1
fi

# Refresh access token
CLIENT_ID=$(jq -r '.installed.client_id' "$OAUTH_FILE")
CLIENT_SECRET=$(jq -r '.installed.client_secret' "$OAUTH_FILE")
REFRESH_TOKEN=$(jq -r '.refresh_token' "$TOKENS_FILE")

TOKEN_RESPONSE=$(curl -s -X POST 'https://oauth2.googleapis.com/token' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d "client_id=$CLIENT_ID" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "refresh_token=$REFRESH_TOKEN" \
  -d "grant_type=refresh_token")

ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.access_token')

if [ "$ACCESS_TOKEN" == "null" ] || [ -z "$ACCESS_TOKEN" ]; then
  echo "ERROR: Failed to refresh token"
  echo "$TOKEN_RESPONSE"
  exit 1
fi

# Fetch content based on type
case "$DOC_TYPE" in
  doc)
    echo "=== Google Doc ==="
    RESPONSE=$(curl -s "https://docs.googleapis.com/v1/documents/$DOC_ID" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    
    TITLE=$(echo "$RESPONSE" | jq -r '.title // "Untitled"')
    echo "Title: $TITLE"
    echo ""
    
    # Extract text content
    echo "$RESPONSE" | jq -r '
      .body.content[]? | 
      if .paragraph then
        .paragraph.elements[]? | .textRun?.content // ""
      elif .table then
        "[TABLE]\n" + (
          .table.tableRows[]? | 
          (.tableCells[]? | .content[]?.paragraph?.elements[]?.textRun?.content // "") + " | "
        ) + "\n"
      else
        ""
      end
    ' 2>/dev/null | head -500
    ;;
    
  sheet)
    echo "=== Google Sheet ==="
    # Get metadata
    META=$(curl -s "https://sheets.googleapis.com/v4/spreadsheets/$DOC_ID" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    
    TITLE=$(echo "$META" | jq -r '.properties.title // "Untitled"')
    echo "Title: $TITLE"
    echo ""
    
    # Get first sheet data
    SHEET_NAME=$(echo "$META" | jq -r '.sheets[0].properties.title // "Sheet1"')
    RANGE=$(echo "$SHEET_NAME" | sed "s/'/\\\\'/g")"!A1:Z100"
    
    DATA=$(curl -s "https://sheets.googleapis.com/v4/spreadsheets/$DOC_ID/values/$(echo "$RANGE" | jq -Rr @uri)" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    
    echo "## $SHEET_NAME"
    echo "$DATA" | jq -r '.values[]? | join(" | ")' 2>/dev/null | head -100
    ;;
    
  slides)
    echo "=== Google Slides ==="
    RESPONSE=$(curl -s "https://slides.googleapis.com/v1/presentations/$DOC_ID" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    
    TITLE=$(echo "$RESPONSE" | jq -r '.title // "Untitled"')
    echo "Title: $TITLE"
    echo ""
    
    # Extract text from each slide
    SLIDE_NUM=1
    echo "$RESPONSE" | jq -r '
      .slides[]? | 
      "## Slide \(.objectId)\n" + (
        .pageElements[]? |
        if .shape?.text then
          .shape.text.textElements[]?.textRun?.content // ""
        elif .table then
          "[TABLE]\n" + (
            .table.tableRows[]? |
            (.tableCells[]?.text?.textElements[]?.textRun?.content // "") + " | "
          ) + "\n"
        else
          ""
        end
      )
    ' 2>/dev/null | head -500
    ;;
esac
