#!/bin/bash
# /opt/scripts/sync-tiktok.sh
# TikTok analytics sync for Firefrost Gaming

set -e

TOKEN_FILE="/opt/scripts/.tiktok-tokens"
ARBITER_URL="https://discord-bot.firefrostgaming.com/api/internal/social"
ARBITER_TOKEN="6fYF1akCRW6pM2F8n3S3RxeIod4YgRniUJNEQurvBP4="

CLIENT_KEY="sbawse6t5serp8xdqp"
CLIENT_SECRET="Ib24OixwLnjZbB8KXAUcYn6ewM60KKDp"

if [ -f "$TOKEN_FILE" ]; then
    source "$TOKEN_FILE"
else
    echo "ERROR: Token file not found at $TOKEN_FILE"
    exit 1
fi

refresh_token() {
    echo "Refreshing TikTok access token..."
    
    RESPONSE=$(curl -s -X POST 'https://open.tiktokapis.com/v2/oauth/token/' \
        -H 'Content-Type: application/x-www-form-urlencoded' \
        -d "client_key=$CLIENT_KEY" \
        -d "client_secret=$CLIENT_SECRET" \
        -d "refresh_token=$REFRESH_TOKEN" \
        -d 'grant_type=refresh_token')
    
    NEW_ACCESS=$(echo "$RESPONSE" | jq -r '.access_token // empty')
    NEW_REFRESH=$(echo "$RESPONSE" | jq -r '.refresh_token // empty')
    
    if [ -z "$NEW_ACCESS" ]; then
        echo "ERROR: Token refresh failed"
        echo "$RESPONSE"
        exit 1
    fi
    
    ACCESS_TOKEN="$NEW_ACCESS"
    [ -n "$NEW_REFRESH" ] && REFRESH_TOKEN="$NEW_REFRESH"
    
    cat > "$TOKEN_FILE" << TOKENS
ACCESS_TOKEN="$ACCESS_TOKEN"
REFRESH_TOKEN="$REFRESH_TOKEN"
TOKENS
    chmod 600 "$TOKEN_FILE"
    echo "  Token refreshed"
}

sync_account_stats() {
    echo "Syncing account stats..."
    
    RESPONSE=$(curl -s -X GET \
        'https://open.tiktokapis.com/v2/user/info/?fields=follower_count,following_count,likes_count,video_count' \
        -H "Authorization: Bearer $ACCESS_TOKEN")
    
    FOLLOWERS=$(echo "$RESPONSE" | jq -r '.data.user.follower_count // 0')
    FOLLOWING=$(echo "$RESPONSE" | jq -r '.data.user.following_count // 0')
    LIKES=$(echo "$RESPONSE" | jq -r '.data.user.likes_count // 0')
    VIDEOS=$(echo "$RESPONSE" | jq -r '.data.user.video_count // 0')
    
    echo "  Followers: $FOLLOWERS, Likes: $LIKES, Videos: $VIDEOS"
    
    curl -s -X POST "$ARBITER_URL/snapshot" \
        -H "Authorization: Bearer $ARBITER_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"platform\":\"tiktok\",\"total_followers\":$FOLLOWERS}" > /dev/null
    
    echo "  Account snapshot synced"
}

sync_videos() {
    echo "Syncing video stats..."
    
    RESPONSE=$(curl -s -X POST \
        'https://open.tiktokapis.com/v2/video/list/?fields=id,title,view_count,like_count,comment_count,share_count' \
        -H "Authorization: Bearer $ACCESS_TOKEN" \
        -H "Content-Type: application/json" \
        -d '{"max_count": 20}')
    
    VIDEO_COUNT=$(echo "$RESPONSE" | jq -r '.data.videos | length')
    echo "  Found $VIDEO_COUNT videos"
    
    echo "$RESPONSE" | jq -c '.data.videos[]' | while read -r video; do
        VID=$(echo "$video" | jq -r '.id')
        # Get first 80 chars of title, escape quotes for JSON
        TITLE=$(echo "$video" | jq -r '.title // "Untitled"' | head -c 80 | sed 's/"/\\"/g')
        VIEWS=$(echo "$video" | jq -r '.view_count // 0')
        LIKES=$(echo "$video" | jq -r '.like_count // 0')
        COMMENTS=$(echo "$video" | jq -r '.comment_count // 0')
        SHARES=$(echo "$video" | jq -r '.share_count // 0')
        
        POST_URL="https://www.tiktok.com/@playfirefrost/video/$VID"
        
        curl -s -X POST "$ARBITER_URL/sync" \
            -H "Authorization: Bearer $ARBITER_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"platform\":\"tiktok\",\"platform_post_id\":\"$VID\",\"post_title\":\"$TITLE\",\"post_url\":\"$POST_URL\",\"metrics\":{\"views\":$VIEWS,\"likes\":$LIKES,\"comments\":$COMMENTS,\"shares\":$SHARES}}" > /dev/null
        
        echo "    $VID: $VIEWS views, $LIKES likes"
    done
    
    echo "  Videos synced"
}

echo "=== TikTok Sync $(date) ==="
refresh_token
sync_account_stats
sync_videos
echo "=== Complete ==="
