#!/usr/bin/env bash
set -euo pipefail
PYTHON=$(which python3 || true)
if [[ -z "$PYTHON" ]]; then
  echo "python3 not found" >&2
  exit 1
fi
$PYTHON - <<'PY'
import sys,urllib.request,re,json,datetime
url='https://menu.matildaplatform.com/sv/meals/66b1f6172370d17e17aa42b7_lillangsgatan-6'
try:
    r=urllib.request.urlopen(url,timeout=15).read().decode('utf-8')
except Exception as e:
    print('Failed to fetch menu:',e)
    sys.exit(0)
# find JSON blob that starts with {"props":
m = re.search(r'\{"props":', r)
if not m:
    # fallback: try to find window.__NEXT_DATA__ = {...}
    m2 = re.search(r'window\.__NEXT_DATA__\s*=\s*({.+?})\s*;</script>', r, re.S)
    if not m2:
        print('Menu JSON not found on page')
        sys.exit(0)
    blob = m2.group(1)
else:
    start = m.start()
    # rudimentary brace-matching to find end
    i = start
    depth = 0
    end = None
    while i < len(r):
        ch = r[i]
        if ch == '{':
            depth += 1
        elif ch == '}':
            depth -= 1
            if depth == 0:
                end = i+1
                break
        i += 1
    if not end:
        print('Failed to extract JSON blob')
        sys.exit(0)
    blob = r[start:end]
# parse JSON
try:
    data = json.loads(blob)
except Exception as e:
    print('JSON parse error:',e)
    sys.exit(0)
# navigate to meals
props = data.get('props') or data.get('pageProps') or {}
pageProps = props.get('pageProps') if isinstance(props,dict) else {}
meals = pageProps.get('meals') or []
# find today's date
today = datetime.date.today()
# some dates may be like '2026-02-23T00:00:00'
found = None
for m in meals:
    d = m.get('date')
    if not d: continue
    try:
        ddate = datetime.datetime.fromisoformat(d).date()
    except:
        # try prefix
        try:
            ddate = datetime.datetime.strptime(d.split('T')[0], '%Y-%m-%d').date()
        except:
            continue
    if ddate == today:
        found = m
        break
if not found:
    print('No menu found for', today.isoformat())
    sys.exit(0)
# new compact layout: weekday only
weekday = today.strftime('%A')
print(f"Lunch menu for Lillängsgatan — {weekday}\n")

courses = found.get('courses') or []
main_options = courses[:2]

print('Main:')
for idx,c in enumerate(main_options, start=1):
    name = c.get('name') or ''
    print(f"{idx}. {name}")

sides = courses[2:]
side_names = [s.get('name') or '' for s in sides if s.get('name')]
side_str = ', '.join(side_names) if side_names else '—'
print(f"\nSide: {side_str}\n")
PY
