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

# Usage: python3 learn_check.py [target_minutes] [category]
# Defaults: 120 minutes, "Lernen" category
# Outputs a motivational one-liner based on current DailyDose status.

TARGET_MINUTES = int(sys.argv[1]) if len(sys.argv) > 1 else 120
CATEGORY = sys.argv[2] if len(sys.argv) > 2 else "Lernen"

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') == CATEGORY)
    total_min = round(total_hours * 60)
else:
    total_min = 0

remaining = TARGET_MINUTES - total_min

if total_min >= TARGET_MINUTES:
    print(f"🎉 Ziel erreicht! {total_min} Minuten {CATEGORY} — geschafft!")
elif total_min > 0:
    pct = int(total_min / TARGET_MINUTES * 100)
    print(f"📚 {total_min} von {TARGET_MINUTES} Minuten {CATEGORY} ({pct}%). Noch {remaining} Minuten!")
else:
    print(f"📚 Noch 0 von {TARGET_MINUTES} Minuten {CATEGORY}.")
