#!/bin/bash
#
# YouTube Intelligence Pipeline for Rivet
# Bash wrapper for youtube-pipeline.py
#
# Usage: ./youtube-pipeline.sh <youtube_url>
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_SCRIPT="$SCRIPT_DIR/youtube-pipeline.py"
OUTPUT_DIR="/home/ccuser/rateright-growth/rivet/memory/youtube"

# Check arguments
if [ $# -lt 1 ]; then
    echo -e "${RED}Error: No YouTube URL provided${NC}"
    echo ""
    echo "Usage: $0 <youtube_url>"
    echo ""
    echo "Example:"
    echo "  $0 https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    exit 1
fi

URL="$1"

# Validate URL
if [[ ! "$URL" =~ (youtube\.com|youtu\.be) ]]; then
    echo -e "${YELLOW}Warning: URL doesn't look like a YouTube URL${NC}"
    echo "Proceeding anyway..."
fi

# Check if Python script exists
if [ ! -f "$PYTHON_SCRIPT" ]; then
    echo -e "${RED}Error: Python script not found at $PYTHON_SCRIPT${NC}"
    exit 1
fi

# Check if yt-dlp is installed
if ! command -v yt-dlp &> /dev/null; then
    echo -e "${RED}Error: yt-dlp is not installed${NC}"
    echo "Install with: pip install yt-dlp"
    exit 1
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Export OpenAI API key if not already set
if [ -z "$OPENAI_API_KEY" ]; then
    # Try to read from Clawdbot config
    CLAWDBOT_CONFIG="$HOME/.clawdbot/config.json"
    if [ -f "$CLAWDBOT_CONFIG" ]; then
        OPENAI_API_KEY=$(python3 -c "import json; config = json.load(open('$CLAWDBOT_CONFIG')); print(config.get('skills', {}).get('entries', {}).get('openai-whisper-api', {}).get('apiKey', ''))" 2>/dev/null || echo "")
        export OPENAI_API_KEY
    fi
fi

# Run the Python pipeline
echo -e "${BLUE}Starting YouTube Intelligence Pipeline...${NC}"
echo ""

python3 "$PYTHON_SCRIPT" "$URL"

EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}✅ Pipeline completed successfully!${NC}"
    echo ""
    echo "Output files saved to: $OUTPUT_DIR"
    echo ""
    echo "View the latest summary with:"
    echo "  cat $OUTPUT_DIR/*_summary.md | tail -n 100"
else
    echo -e "${RED}❌ Pipeline failed with exit code $EXIT_CODE${NC}"
    exit $EXIT_CODE
fi
