#!/bin/bash
# Cariflex - Daily EMS Automation
# Run at 6:00 AM America/Martinique (10:00 UTC)
# Crontab: 0 10 * * * /home/eric/cariflex/scripts/daily_ems.sh

export FM_PASS="Digitribe972"
LOG_FILE="/var/log/cariflex_daily_ems.log"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

log "=== Starting Daily EMS Automation ==="

# 1. Forecasting - Generate forecasts for all sensors
log "Step 1: Forecasting..."
for sensor in $(seq 41 80); do
    result=$(docker exec flexmeasures-server bash -c "
        cd /app && timeout 120 .venv/bin/flexmeasures add forecasts \
            --sensor $sensor \
            --to-date \$(date -u -d '+24 hours' +'%Y-%m-%dT%H:%M:%S+00:00') 2>&1 | tail -3
    " 2>/dev/null)
    log "  Sensor $sensor: $result"
done

# 2. Scheduling - Create schedules for batteries and EVs
log "Step 2: Scheduling..."
bash /home/eric/cariflex/scripts/fm_scheduling.sh >> "$LOG_FILE" 2>&1

# 3. Cleanup old data (keep 30 days)
log "Step 3: Cleanup..."
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
    DELETE FROM timed_belief WHERE event_start < NOW() - INTERVAL '30 days';
    VACUUM timed_belief;
" 2>/dev/null

log "=== Daily EMS Automation Complete ==="
