#!/bin/bash
# Cariflex - FlexMeasures EMS Automation Script
# This script runs forecasting, scheduling, and ingestion tasks

FM_HOST="https://cariflex.digitribe.fr"
FM_EMAIL="admin@digitribe.fr"
FM_PASSWORD="Digitribe972"

echo "=== Cariflex EMS Automation ==="
echo "Date: $(date)"

# 1. FORECASTING - Generate forecasts for all PV sensors (41-50)
echo ""
echo "=== 1. Forecasting PV sensors ==="
for sensor in $(seq 41 50); do
  echo "  Forecasting sensor $sensor..."
  docker exec flexmeasures-server bash -c "
    cd /app && .venv/bin/flexmeasures add forecasts \
      --sensor $sensor \
      --to-date \$(date -u -d '+24 hours' +'%Y-%m-%dT%H:%M:%S+00:00') \
      2>&1 | grep -E 'Successfully|Error' | head -1
  " 2>/dev/null
done

# 2. SCHEDULING - Create schedules for batteries (51-60)
echo ""
echo "=== 2. Scheduling Batteries ==="
for sensor in $(seq 51 60); do
  echo "  Scheduling sensor $sensor..."
  # Get the schedule from FM API
  SCHEDULE=$(curl -sk -X POST "$FM_HOST/api/v3_0/sensors/$sensor/schedules/trigger" \
    -H "Content-Type: application/json" \
    -u "$FM_EMAIL:$FM_PASSWORD" \
    -d '{
      "start": "'"$(date -u +'%Y-%m-%dT%H:%M:%S+00:00')"'",
      "duration": "PT24H",
      "flex_model": {
        "soc-min": "0.1 kWh",
        "soc-max": "100 kWh",
        "power-capacity": "50 kW"
      }
    }' 2>/dev/null)
  echo "  Response: $(echo $SCHEDULE | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('message','?'))" 2>/dev/null)"
done

# 3. INGESTION - Check sensor data status
echo ""
echo "=== 3. Ingestion Status ==="
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT 
  s.name as sensor,
  COUNT(t.id) as data_points,
  MAX(t.event_start) as latest_data
FROM sensor s
LEFT JOIN timed_belief t ON t.sensor_id = s.id
WHERE s.id BETWEEN 41 AND 80
GROUP BY s.name
ORDER BY s.id
LIMIT 10;
" 2>/dev/null

echo ""
echo "=== EMS Automation Complete ==="
