#!/bin/bash
# Cariflex - FlexMeasures EMS Scheduling Automation
# This script schedules batteries and EVs via FM API

FM_HOST="https://cariflex.digitribe.fr"
FM_EMAIL="admin@digitribe.fr"
FM_PASSWORD_FILE="/tmp/fm_pass.txt"

# Get password
FM_PASSWORD=$(cat "$FM_PASSWORD_FILE")

# Login and get session
login() {
    local session=$(mktemp)
    local csrf_token=$(curl -sk -c "$session" "$FM_HOST/login" | grep -oP 'id="csrf_token" value="\K[^"]+')
    curl -sk -c "$session" -b "$session" -X POST "$FM_HOST/login" \
        -d "email=$FM_EMAIL&password=$FM_PASSWORD&csrf_token=$csrf_token&remember=y" \
        -L -o /dev/null
    echo "$session"
}

# Create schedule for a sensor
create_schedule() {
    local session="$1"
    local sensor_id="$2"
    local duration="$3"
    local flex_model="$4"
    
    local start=$(date -u +'%Y-%m-%dT%H:%M:%S+00:00')
    
    curl -sk -c "$session" -b "$session" -X POST \
        "$FM_HOST/api/v3_0/sensors/$sensor_id/schedules/trigger" \
        -H "Content-Type: application/json" \
        -d "{
            \"start\": \"$start\",
            \"duration\": \"$duration\",
            \"flex_model\": $flex_model
        }"
}

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

# Login
SESSION=$(login)
echo "Logged in successfully"

# Schedule Batteries (sensors 51-60)
echo ""
echo "=== Scheduling Batteries (51-60) ==="
for sensor in $(seq 51 60); do
    echo "  Scheduling battery sensor $sensor..."
    result=$(create_schedule "$SESSION" "$sensor" "PT24H" '{
        "soc_min": "10 kWh",
        "soc_max": "100 kWh",
        "power_capacity": "50 kW",
        "charging_efficiency": "0.95",
        "discharging_efficiency": "0.95"
    }')
    echo "    Result: $(echo "$result" | grep -oP '"status":"[^"]*"' | head -1)"
done

# Schedule EVs (sensors 71-80)
echo ""
echo "=== Scheduling EVs (71-80) ==="
for sensor in $(seq 71 80); do
    echo "  Scheduling EV sensor $sensor..."
    result=$(create_schedule "$SESSION" "$sensor" "PT12H" '{
        "soc_min": "15 kWh",
        "soc_max": "75 kWh",
        "power_capacity": "11 kW",
        "charging_efficiency": "0.95",
        "discharging_efficiency": "0.95"
    }')
    echo "    Result: $(echo "$result" | grep -oP '"status":"[^"]*"' | head -1)"
done

# Cleanup
rm -f "$SESSION"

echo ""
echo "=== Scheduling Complete ==="
