#!/usr/bin/env python3

# reads Attawar API and generates diagram with 
# prices for the next 24 hours and sends it per mail

# requirements: * requests   (pip install requests)
#               * matplotlib (pip install matplotlib)
#               * local mail server (MTA) listening on localhost:25

import locale, os, requests, smtplib, ssl
from email.message import EmailMessage
from datetime import datetime
import matplotlib.pyplot as plt

# use system settings to set language for day names
locale.setlocale(locale.LC_ALL, '')

surcharge = 1.5     # Awattar adds 1.5 ct per kWh
vat = 0.20          # 20% VAT (Austria); use 0.19 for Germany

url = 'https://api.awattar.at/v1/marketdata'   # Austria
# url = 'https://api.awattar.de/v1/marketdata' # Germany

response = requests.get(url)
jsondata = response.json()

hours = []
prices = []
dateStart = None

# show prices as text
for price in jsondata['data']:
    startDt = \
      datetime.fromtimestamp(price['start_timestamp'] / 1000)
    hour = startDt.strftime('%H:%M')
    day = startDt.strftime('%a')
    if not dateStart:  # initialize only once
        dateStart = startDt.strftime('%Y-%m-%d')
    dateEnd = startDt.strftime('%Y-%m-%d')  # overwrite
    priceCentKw = (round(price['marketprice'] / 10 + surcharge) * (1 + vat))
    hours += [hour]
    prices += [priceCentKw]

# plot a simple diagram
fig, ax = plt.subplots()
ax.bar(hours, prices)
plt.xticks(rotation=90)
plt.title('Prices in ct/kWh from %s to %s' % (dateStart, dateEnd))

# hide every second x tick label
for label in ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)
fig.savefig('prices.png', dpi=200) 

# setup email and send
msg = EmailMessage()
msg["Subject"] = "Electricity prices"
msg["From"]    = "alice@example.com
msg["To"]      = "bob@otherhost.com"

# plain text
msg.set_content('Electricity prices from %s to %s' % (dateStart, dateEnd))

# add attachment
with open("prices.png", "rb") as f:
    msg.add_attachment(f.read(),
                       maintype="image",
                       subtype="png",
                       filename="prices.png")

# send
try:
    with smtplib.SMTP("localhost", 25) as smtp:
        smtp.send_message(msg)
except (smtplib.SMTPException, OSError) as e:
    print(f"Failed to send email: {e}")
