import json, urllib.request, sys
from datetime import date

TARGET_MINUTES = 120

today_key = f'dailydose_{date.today().isoformat()}'
url = 'http://localhost:8765/api/data'

try:
    resp = urllib.request.urlopen(url, timeout=5)
    data = json.loads(resp.read())
except Exception as e:
    print(f"[ERROR] Kann DailyDose nicht erreichen: {e}")
    sys.exit(1)

if today_key in data:
    entries = json.loads(data[today_key])
    total_hours = sum(e.get('hours', 0) for e in entries if e.get('category') == 'Lernen')
    total_min = round(total_hours * 60)
else:
    total_min = 0

remaining = TARGET_MINUTES - total_min

if total_min >= TARGET_MINUTES:
    print(f"🎉 Chef, du hast es geschafft! {int(total_min)} Minuten gelernt — Ziel erreicht! Jetzt darfst du dir die Kopfhörer bestellen! 🎧")
elif total_min > 0:
    pct = int(total_min / TARGET_MINUTES * 100)
    print(f"📚 {int(total_min)} von {TARGET_MINUTES} Minuten gelernt ({pct}%). Noch {int(remaining)} Minuten! Weiter so, Chef — die Kopfhörer warten! 🎧")
else:
    print(f"📚 Noch 0 von {TARGET_MINUTES} Minuten gelernt. Zeit anzufangen, Chef — die Kopfhörer warten! 🎧")
