#!/bin/bash
########################################
# Laravel Schedule Runner with Context
# Wraps php artisan schedule:run with
# proper error context for cron emails
########################################

# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Load cron context library
source "$SCRIPT_DIR/_cron-context.sh"

# Change to project directory
cd "$PROJECT_ROOT" || exit 1

# Capture both stdout and stderr (silently)
OUTPUT=$(php artisan schedule:run 2>&1)
EXIT_CODE=$?

# Only output if there's actual content or error
if [ $EXIT_CODE -ne 0 ] || echo "$OUTPUT" | grep -qE "(Error|Exception|Failed|Warning)"; then
    # Print context header ONLY when there's an error
    get_cron_context "$PROJECT_ROOT"
    echo "Running Laravel scheduler..."
    echo ""
    echo "$OUTPUT"
    echo ""

    if [ $EXIT_CODE -ne 0 ]; then
        cron_error "Schedule run failed with exit code $EXIT_CODE" "php artisan schedule:run"
        exit $EXIT_CODE
    else
        echo "⚠️  Scheduler ran but commands reported errors (see above)"
        echo ""
    fi
fi

# Silent success (no email)
exit 0
