#!/usr/bin/env python3
"""Fetch Mealie meal plan and save simplified JSON for HA REST sensor."""
import json, urllib.request, datetime, os

# Read bearer token from secrets.yaml
token = None
with open('/config/secrets.yaml') as f:
    for line in f:
        if line.strip().startswith('mealie_bearer_token:'):
            token = line.split(':', 1)[1].strip().strip('"')
            break

if not token:
    data = {"count": 0, "items": []}
else:
    today = datetime.date.today()
    end = today + datetime.timedelta(days=6)
    url = f"http://10.0.0.142:9925/api/households/mealplans?start_date={today}&end_date={end}"

    try:
        req = urllib.request.Request(url, headers={"Authorization": token})
        raw = json.loads(urllib.request.urlopen(req, timeout=10).read())
        items = []
        for i in raw.get("items", []):
            recipe = i.get("recipe")
            title = i.get("title") or ""
            if recipe:
                items.append({
                    "date": i["date"],
                    "recipe": {
                        "name": recipe.get("name", ""),
                        "slug": recipe.get("slug", ""),
                    },
                })
            elif title:
                items.append({
                    "date": i["date"],
                    "recipe": {
                        "name": title,
                        "slug": "",
                    },
                })
        data = {"count": len(items), "items": items}
    except Exception:
        data = {"count": 0, "items": []}

os.makedirs('/config/www', exist_ok=True)
with open('/config/www/mealie.json', 'w') as f:
    json.dump(data, f)
print("OK")
