#!/bin/bash
# Cariflex - Correction des assets et lancement du scheduling

echo "=== Correction des flex_context des assets ==="

# Clear all flex_context for battery and EV assets
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
UPDATE generic_asset SET flex_context = '{}' WHERE id BETWEEN 51 AND 80;
UPDATE generic_asset SET flex_model = '{}' WHERE id BETWEEN 51 AND 80;
SELECT id, name, flex_context, flex_model FROM generic_asset WHERE id = 51;
" 2>&1

echo ""
echo "=== Lancement du scheduling Batteries ==="
for sensor_id in $(seq 51 60); do
    echo "  Scheduling sensor $sensor_id..."
    docker exec flexmeasures-server bash -c "
        cd /app && .venv/bin/flexmeasures add schedule \
            --sensor $sensor_id \
            --start \$(date -u +'%Y-%m-%dT%H:%M:%S+00:00') \
            --duration PT24H \
            --resolution PT15M \
            --soc-at-start 0.5 \
            --flex-model '{\"soc-min\": \"0.1 MWh\", \"soc-max\": \"1 MWh\", \"power-capacity\": \"0.05 MW\"}' 2>&1
    " 2>&1 | grep -E "Successfully|SAVED|Error" | head -3
done

echo ""
echo "=== Lancement du forecasting PV ==="
for sensor_id in $(seq 41 45); do
    echo "  Forecasting sensor $sensor_id..."
    docker exec flexmeasures-server bash -c "
        cd /app && .venv/bin/flexmeasures add forecasts \
            --sensor $sensor_id \
            --to-date \$(date -u -d '+24 hours' +'%Y-%m-%dT%H:%M:%S+00:00') 2>&1
    " 2>&1 | grep -E "Successfully|SAVED" | head -1
done

echo ""
echo "=== Vérification des données ==="
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT 
  'forecasts' as type,
  COUNT(*) as count
FROM timed_belief 
WHERE source_id IN (SELECT id FROM data_source WHERE name LIKE '%forecast%')
  AND event_start > NOW() - INTERVAL '1 hour'
UNION ALL
SELECT 
  'schedules' as type,
  COUNT(*) as count
FROM timed_belief 
WHERE source_id IN (SELECT id FROM data_source WHERE name LIKE '%schedule%')
  AND event_start > NOW() - INTERVAL '1 hour';
" 2>&1

echo ""
echo "=== Terminé ==="
