#!/bin/bash

# Exit immediately if a command fails (except when we explicitly allow it later)
set -e

echo "🚀 Starting Twitter to Bluesky Sync Job..."

# 1. Navigate to the directory containing the script
# (Uncomment and change the path below if running via cron so it knows where to look)
# cd /path/to/your/meteocatrss2bsky || exit

# 2. Load environment variables (Mimicking GitHub Secrets)
if [ -f ".env" ]; then
    echo "📂 Loading secrets from .env file..."
    export $(grep -v '^#' .env | xargs)
else
    echo "⚠️ No .env file found. Make sure environment variables are exported manually!"
fi

# 3. Set up Python Virtual Environment (Mimicking actions/setup-python)
if [ ! -d "venv" ]; then
    echo "🐍 Creating Python virtual environment..."
    python3 -m venv venv
fi

echo "🔄 Activating virtual environment..."
source venv/bin/activate

# 4. Install dependencies
echo "📦 Installing dependencies..."
pip install --upgrade pip -q
pip install atproto tweety-ns playwright httpx arrow python-dotenv -q

# Install the browser
playwright install chromium

# Install the required Linux system libraries
playwright install-deps chromium 

# 7. Clean up (Optional)
# Deactivate the virtual environment
deactivate
# Remove the virtual environment (if you want to start fresh next time)
# rm -rf venv   

# 5. Run the script
echo "▶️ Running the sync script..."

# Temporarily disable "exit on error" so we can catch a script crash and save the screenshot
set +e 

python3 twitter2bsky_daemon.py \
    --twitter-username "$TWITTER_USERNAME" \
    --twitter-password "$TWITTER_PASSWORD" \
    --twitter-email "$TWITTER_EMAIL" \
    --twitter-handle "$TWITTER_HANDLE" \
    --bsky-handle "$BSKY_HANDLE" \
    --bsky-password "$BSKY_APP_PASSWORD"
    
EXIT_CODE=$?

# Re-enable "exit on error"
set -e

# 6. Handle Errors and Screenshots (Mimicking actions/upload-artifact)
if [ $EXIT_CODE -ne 0 ]; then
    echo "❌ Script failed with exit code $EXIT_CODE."
    
    # Check if any screenshots were generated by Playwright
    if ls screenshot_*.png 1> /dev/null 2>&1; then
        echo "📸 Error screenshots found. Moving them to 'error_artifacts' folder..."
        mkdir -p error_artifacts
        mv screenshot_*.png error_artifacts/
        echo "✅ Screenshots saved in ./error_artifacts/"
    else
        echo "⚠️ No screenshots found."
    fi
    
    exit $EXIT_CODE
fi

echo "✅ Sync job completed successfully!"
