#!/bin/bash
# Cariflex - FlexMeasures EMS Configuration Script
# This script configures FlexMeasures as a full EMS with:
# - Forecasting (PV, Load, Prices)
# - Scheduling (Batteries, EVs)
# - Ingestion (Sensors, Assets, Beliefs)

set -e

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

echo "╔══════════════════════════════════════════════════════════════════════════════╗"
echo "║                    CARIFLEX - FlexMeasures EMS Configuration                 ║"
echo "╚══════════════════════════════════════════════════════════════════════════════╝"
echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 1. INITIAL STRUCTURE
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  1. INITIAL STRUCTURE"
echo "═══════════════════════════════════════════════════════════════════════════════"

echo "  → Creating initial structure (account, roles, data sources)..."
docker exec flexmeasures-server bash -c "
cd /app && timeout 60 .venv/bin/flexmeasures add initial-structure 2>&1 | tail -5
" 2>&1

echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 2. ASSETS AND SENSORS (if not already created)
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  2. ASSETS AND SENSORS"
echo "═══════════════════════════════════════════════════════════════════════════════"

# Check if assets already exist
ASSET_COUNT=$(docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -t -c "
SELECT COUNT(*) FROM generic_asset;
" 2>/dev/null | xargs)

echo "  → Current asset count: $ASSET_COUNT"

if [ "$ASSET_COUNT" -lt 40 ]; then
    echo "  → Creating assets and sensors..."
    
    # Create PV assets (10)
    for i in $(seq 1 10); do
        echo "    Creating PV_0$i..."
        docker exec flexmeasures-server bash -c "
            cd /app && timeout 30 .venv/bin/flexmeasures add asset \
              --name 'PV_0$i' \
              --type 'solar' \
              --capacity 5 \
              --unit 'kW' \
              --latitude 14.6$(printf '%02d' $((i * 10))) \
              --longitude -61.2$(printf '%02d' $((i * 5))) \
              2>&1 | tail -3
        " 2>/dev/null
    done
    
    # Create Battery assets (10)
    for i in $(seq 1 10); do
        echo "    Creating Bat_0$i..."
        docker exec flexmeasures-server bash -c "
            cd /app && timeout 30 .venv/bin/flexmeasures add asset \
              --name 'Bat_0$i' \
              --type 'battery' \
              --capacity 100 \
              --unit 'kWh' \
              --latitude 14.5$(printf '%02d' $((i * 10))) \
              --longitude -61.1$(printf '%02d' $((i * 5))) \
              2>&1 | tail -3
        " 2>/dev/null
    done
    
    # Create EV Charger assets (10)
    for i in $(seq 1 10); do
        echo "    Creating Chg_0$i..."
        docker exec flexmeasures-server bash -c "
            cd /app && timeout 30 .venv/bin/flexmeasures add asset \
              --name 'Chg_0$i' \
              --type 'ev_charger' \
              --capacity 22 \
              --unit 'kW' \
              --latitude 14.6$(printf '%02d' $((i * 8))) \
              --longitude -61.0$(printf '%02d' $((i * 3))) \
              2>&1 | tail -3
        " 2>/dev/null
    done
    
    # Create EV assets (10)
    for i in $(seq 1 10); do
        echo "    Creating EV_0$i..."
        docker exec flexmeasures-server bash -c "
            cd /app && timeout 30 .venv/bin/flexmeasures add asset \
              --name 'EV_0$i' \
              --type 'ev' \
              --capacity 75 \
              --unit 'kWh' \
              --latitude 14.5$(printf '%02d' $((i * 7))) \
              --longitude -61.2$(printf '%02d' $((i * 4))) \
              2>&1 | tail -3
        " 2>/dev/null
    done
else
    echo "  → Assets already exist, skipping..."
fi

echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 3. FORECASTING
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  3. FORECASTING"
echo "═══════════════════════════════════════════════════════════════════════════════"

echo "  → Generating forecasts for PV sensors (41-50)..."
for sensor in $(seq 41 50); do
    echo "    Forecasting sensor $sensor..."
    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 | grep -E 'Successfully|Error|SAVED' | head -1
    " 2>/dev/null
done

echo "  → Generating forecasts for Battery sensors (51-60)..."
for sensor in $(seq 51 60); do
    echo "    Forecasting sensor $sensor..."
    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 | grep -E 'Successfully|Error|SAVED' | head -1
    " 2>/dev/null
done

echo "  → Generating forecasts for EV Charger sensors (61-70)..."
for sensor in $(seq 61 70); do
    echo "    Forecasting sensor $sensor..."
    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 | grep -E 'Successfully|Error|SAVED' | head -1
    " 2>/dev/null
done

echo "  → Generating forecasts for EV sensors (71-80)..."
for sensor in $(seq 71 80); do
    echo "    Forecasting sensor $sensor..."
    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 | grep -E 'Successfully|Error|SAVED' | head -1
    " 2>/dev/null
done

echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 4. SCHEDULING
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  4. SCHEDULING"
echo "═══════════════════════════════════════════════════════════════════════════════"

echo "  → Creating schedules for Battery sensors (51-60)..."
for sensor in $(seq 51 60); do
    echo "    Scheduling sensor $sensor..."
    docker exec flexmeasures-server bash -c "
        cd /app && timeout 60 .venv/bin/flexmeasures add schedule \
          --sensor $sensor \
          --start \$(date -u +'%Y-%m-%dT%H:%M:%S+00:00') \
          --duration PT24H \
          --resolution PT5M \
          --soc-at-start 0.5 \
          2>&1 | grep -E 'Successfully|Error|schedule' | head -1
    " 2>/dev/null
done

echo "  → Creating schedules for EV sensors (71-80)..."
for sensor in $(seq 71 80); do
    echo "    Scheduling sensor $sensor..."
    docker exec flexmeasures-server bash -c "
        cd /app && timeout 60 .venv/bin/flexmeasures add schedule \
          --sensor $sensor \
          --start \$(date -u +'%Y-%m-%dT%H:%M:%S+00:00') \
          --duration PT24H \
          --resolution PT5M \
          --soc-at-start 0.4 \
          2>&1 | grep -E 'Successfully|Error|schedule' | head -1
    " 2>/dev/null
done

echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 5. INGESTION STATUS
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  5. INGESTION STATUS"
echo "═══════════════════════════════════════════════════════════════════════════════"

echo "  → Checking sensor data status..."
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT 
  s.name as sensor,
  s.unit,
  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, s.unit
ORDER BY s.id;
" 2>/dev/null

echo ""

# ═══════════════════════════════════════════════════════════════════════════════
# 6. SUMMARY
# ═══════════════════════════════════════════════════════════════════════════════
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  6. EMS CONFIGURATION SUMMARY"
echo "═══════════════════════════════════════════════════════════════════════════════"

echo ""
echo "  Assets:"
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT gt.name as type, COUNT(*) as count 
FROM generic_asset g 
JOIN generic_asset_type gt ON g.generic_asset_type_id = gt.id 
GROUP BY gt.name;
" 2>/dev/null

echo ""
echo "  Sensors:"
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT COUNT(*) as total_sensors FROM sensor;
" 2>/dev/null

echo ""
echo "  Data Points (Beliefs):"
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT COUNT(*) as total_beliefs FROM timed_belief;
" 2>/dev/null

echo ""
echo "  Forecasts:"
docker exec flexmeasures-db psql -U flexmeasures -d flexmeasures -c "
SELECT COUNT(*) as forecasts FROM timed_belief 
WHERE source_id IN (SELECT id FROM data_source WHERE name LIKE '%forecast%');
" 2>/dev/null

echo ""
echo "╔══════════════════════════════════════════════════════════════════════════════╗"
echo "║                    EMS Configuration Complete!                               ║"
echo "╚══════════════════════════════════════════════════════════════════════════════╝"
