#!/bin/bash
#
# YouTube Autonomous Intelligence - Bash Wrapper
# Automatically searches, ranks, and processes top YouTube videos
#
# Usage: ./youtube-auto-intel.sh [options]
#

set -e

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

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

# Parse arguments
DRY_RUN=""
COOKIES_ARG=""
CONFIG_ARG=""
TOP_ARG=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN="--dry-run"
            shift
            ;;
        --cookies)
            COOKIES_ARG="--cookies $2"
            shift 2
            ;;
        --config)
            CONFIG_ARG="--config $2"
            shift 2
            ;;
        --top)
            TOP_ARG="--top $2"
            shift 2
            ;;
        -h|--help)
            echo -e "${BLUE}YouTube Autonomous Intelligence System${NC}"
            echo ""
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --dry-run              Search and rank only, don't process videos"
            echo "  --cookies FILE         Path to YouTube cookies file"
            echo "  --config FILE          Path to custom topics config file"
            echo "  --top N                Process top N videos (overrides config)"
            echo "  -h, --help             Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                                    # Run with defaults"
            echo "  $0 --dry-run                          # Search only"
            echo "  $0 --cookies ~/.youtube-cookies.txt   # With cookies"
            echo "  $0 --top 5                            # Process top 5 videos"
            echo ""
            echo "Config file: $CONFIG_FILE"
            echo "Output directory: $OUTPUT_DIR"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# 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 config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}Error: Config file not found at $CONFIG_FILE${NC}"
    exit 1
fi

# Check for default cookies file
if [ -z "$COOKIES_ARG" ]; then
    DEFAULT_COOKIES="$HOME/.youtube-cookies.txt"
    if [ -f "$DEFAULT_COOKIES" ]; then
        echo -e "${BLUE}Using default cookies: $DEFAULT_COOKIES${NC}"
        COOKIES_ARG="--cookies $DEFAULT_COOKIES"
    else
        echo -e "${YELLOW}Warning: No cookies file found (YouTube may block downloads)${NC}"
        echo -e "${YELLOW}Export cookies from Chrome/Firefox to ~/.youtube-cookies.txt${NC}"
        echo ""
    fi
fi

# Export OpenAI API key if not already set
if [ -z "$OPENAI_API_KEY" ]; then
    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

# Show banner
echo -e "${PURPLE}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║   YouTube Autonomous Intelligence System              ║"
echo "║   Automatically finds and processes top videos        ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Show mode
if [ -n "$DRY_RUN" ]; then
    echo -e "${YELLOW}⏸️  Mode: DRY RUN (search only)${NC}"
else
    echo -e "${GREEN}🚀 Mode: FULL RUN (search + process)${NC}"
fi
echo ""

# Run the Python pipeline
python3 "$PYTHON_SCRIPT" $DRY_RUN $COOKIES_ARG $CONFIG_ARG $TOP_ARG

EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}✅ Autonomous intelligence scan complete!${NC}"
    echo ""
    echo "Output directory: $OUTPUT_DIR"
    echo ""
    echo "View results:"
    echo "  ls -ltr $OUTPUT_DIR/"
    echo "  cat $OUTPUT_DIR/*_auto_intel_report.md | less"
else
    echo -e "${RED}❌ Scan failed with exit code $EXIT_CODE${NC}"
    exit $EXIT_CODE
fi
