#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Scrape Uber Eats store menus with headless chromium into cache/ue_<slug>.html,
then parse via parse_ubereats.fix_blob into menu_items."""
import subprocess, sys, os, time
sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))
from parse_ubereats import main as parse_main

UA="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
HERE=os.path.dirname(os.path.abspath(__file__))
CACHE=os.path.join(HERE,"cache"); os.makedirs(CACHE,exist_ok=True)

STORES=[
 "boom-smashburger",
 "master-pizza-%26-more",
 "tele-pizza-krefeld",
 "pizza-cab-krefeld",
 "dominos-krefeld-inrath",
 "xpo-pizza",
 "pizzeria-tosca-krefeld",
 "donaladn-meats-borgaladn-krefeld",
 "kostlicher-krefeld",
 "loco-chicken-krefeld-mitte",
 "ali-baba",
 "take-%E2%80%93-the-good-food-krefeld",
 "rnbeef-krefeld",
 "indian-heritage",
 "favo-krefeld",
 "pizzeria-da-nico",
]
def chromium(url,out,tries=3):
    for t in range(tries):
        cmd=["chromium","--headless=new","--no-sandbox","--disable-gpu",
             "--window-size=1400,2500","--virtual-time-budget=25000",
             f"--user-agent={UA}","--dump-dom",url]
        with open(out,"w") as f:
            subprocess.run(cmd,stdout=f,stderr=subprocess.DEVNULL,timeout=150)
        size=os.path.getsize(out)
        head=open(out,encoding="utf-8",errors="ignore").read(4000)
        if size>600000 and "nichts zu essen" not in head:
            return size
        time.sleep(40)
    return size

for slug in STORES:
    if sys.argv[1:] and slug not in sys.argv[1:]: continue
    out=os.path.join(CACHE,f"ue_{slug}.html")
    try:
        size=chromium(f"https://www.ubereats.com/de/store/{slug}",out)
        print(f"{slug}: cache {size//1024}KB", flush=True)
    except Exception as e:
        print(f"{slug}: FAIL {e}", flush=True)
parse_main(*[s for s in STORES])
