"""Content restored from the archived shanina.co.il (folder "restoring old site").

old_articles() / old_recipes() return seed documents in the same shapes build-seed.py
uses; extract_images() saves the pictures these pages use into design/old-site/.
Per-page rules below only restructure (headings, lists, sections) – the text is kept.
"""
import os
import re

import old_site as o

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OLD = os.path.join(os.path.dirname(ROOT), "restoring old site")
IMG_OUT = os.path.join(ROOT, "design", "old-site")

_counter = [0]


def k():
    _counter[0] += 1
    return f"o{_counter[0]:04d}"


def _resolve(name):
    """Saved file names carry irregular spaces; match ignoring whitespace."""
    folder, base = os.path.split(os.path.join(OLD, name))
    want = re.sub(r"\s+", "", base + "_Shanina.mhtml")
    for f in os.listdir(folder):
        if re.sub(r"\s+", "", f) == want:
            return os.path.join(folder, f)
    raise FileNotFoundError(name)


def page(name):
    soup, images = o.load(_resolve(name))
    return soup, images, o.page_lines(soup)


def img(name, alt=""):
    return {"_type": "image", "src": f"/images/{name}.webp", "alt": alt}


def text_block(text, style="normal", marks=()):
    line = {"tag": "p", "spans": [(text, False, None, None)], "text": text}
    return o.to_block(line, style=style, extra_marks=marks, seed=text)


def content(lines, skip=0):
    """Drop the first `skip` real lines (image, title...). Empty lines stay: they mark paragraph breaks."""
    out, seen = [], 0
    for l in lines:
        if l["tag"] == "gap":
            if seen > skip:
                out.append(l)
            continue
        seen += 1
        if seen > skip:
            out.append(l)
    return out


def split_long(lines):
    """Old pages sometimes glue several sentences into one <p> as separate spans; split them."""
    out = []
    for l in lines:
        spans = l.get("spans") or []
        if l["tag"] == "p" and len(l["text"]) > 160 and len(spans) > 2:
            cur = []
            for s in spans:
                cur.append(s)
                if re.search(r"[.:?!–\-)]\s*$", s[0]) and "".join(x[0] for x in cur).strip():
                    t = "".join(x[0] for x in cur)
                    out.append({**l, "spans": cur, "text": t.strip()})
                    cur = []
            if cur and "".join(x[0] for x in cur).strip():
                out.append({**l, "spans": cur, "text": "".join(x[0] for x in cur).strip()})
        else:
            out.append(l)
    return out


def blocks_from(lines, styles=None, seed=""):
    """lines -> PT blocks. `styles` maps a line's exact text (or a regex) to a style.
    Consecutive plain lines join into one paragraph with line breaks; an empty line,
    a heading, a list item or an image starts a new one."""
    styles = styles or {}
    out = []
    joinable = None  # the paragraph block the next plain line may extend
    for i, l in enumerate(lines):
        if l["tag"] in ("gap",):
            joinable = None
            continue
        if l["tag"] == "img":
            joinable = None
            out.append({"_type": "image", "_key": k(), "src": f"/images/{l['src']}", "alt": l.get("alt", "")})
            continue
        if re.fullmatch(r"[_\-–—=\s]{8,}", l.get("text", "") or "x"):
            out.append({"_type": "divider", "_key": k(), "style": "flower"})
            joinable = None
            continue
        if l["tag"] == "button":
            if l.get("href"):
                out.append({"_type": "linkButton", "_key": k(), "label": l["text"], "href": l["href"]})
            continue
        style = None
        for pattern, st in styles.items():
            if (pattern.startswith("re:") and re.search(pattern[3:], l["text"])) or o.plain(l["text"]) == o.plain(pattern):
                style = st
                break
        block = o.to_block(l, style=style, seed=f"{seed}{i}")
        plain_para = block["style"] in ("normal", "center") and not block.get("listItem")
        if plain_para and joinable is not None and joinable["style"] == block["style"] and block["children"]:
            nl = {"_type": "span", "_key": block["_key"] + "n", "text": "\n", "marks": []}
            joinable["children"] += [nl] + block["children"]
            joinable["markDefs"] += [d for d in block["markDefs"] if d not in joinable["markDefs"]]
            continue
        out.append(block)
        joinable = block if plain_para else None
    return out


def numbered_list(lines, start_re=r"^\s*\d+\s*[.)]\s*", stop_re=r"^(רשימת הנושאים|\*|הרשימה|ההנבטת)"):
    """'1. text' + continuation lines -> list items (continuations joined with a line break)."""
    out, cur = [], None
    for l in lines:
        if l["tag"] in ("p", "div") and re.match(start_re, l["text"]):
            if cur:
                out.append(cur)
            spans = list(l["spans"])
            first = re.sub(start_re, "", spans[0][0].lstrip()) if spans else ""
            # number may sit in its own span
            while spans and not re.sub(start_re, "", spans[0][0]).strip():
                spans.pop(0)
                first = spans[0][0] if spans else ""
            if spans:
                spans[0] = (re.sub(start_re, "", spans[0][0].lstrip()),) + tuple(spans[0][1:])
            cur = {**l, "spans": spans, "text": re.sub(start_re, "", l["text"]), "list": "ol"}
        elif cur and l["tag"] == "p" and l["text"] and not re.match(stop_re, l["text"]):
            cur = {**cur, "spans": cur["spans"] + [("\n", False, None, None)] + list(l["spans"]),
                   "text": cur["text"] + "\n" + l["text"]}
        else:
            if cur:
                out.append(cur)
                cur = None
            out.append(l)
    if cur:
        out.append(cur)
    return out


def drop(lines, *texts):
    return [l for l in lines if o.plain(l.get("text", "")) not in {o.plain(t) for t in texts}]


# ------------------------------------------------------------------ articles
VALUES = """אדיבות אהבה|אהבת המולדת|אהדה|אומץ|אופטימיות|אושר|אותנטיות|אחדות|אכפתיות|אמון|אמפתיה|אנושיות|אסטתיקה|אסרטיביות|בטחון|ביטוי עצמי|גמישות|דוגמה אישית|דו קיום|הארת פנים|הגיוניות|השראה|הגשמה|הדדיות|הובלה|הומור|השגיות|הוקרת תודה|החלטיות|הנאה|הסתפקות במועט|הקשבה|הרפתקנות|התלהבות|התמדה|התנדבות|התמסרות|התפתחות|חברות|חדשנות|חופש בחירה|חינוך|חוכמה|חמלה|חריצות|יוזמה|יושרה|ייחודיות|יסודיות|יציבות|יצירתיות|ישירות|כיבוד האדם|כנות|כריזמה|למידה|לקיחת סיכונים|מחוייבות|מחילה|מיקוד במטרה|מנהיגות|מסורת|מעורבות|מצוינות|מקוריות|מקצועיות|משמעת עצמית|משפחה|נאמנות|נדיבות|נחישות|נימוס|נכונות|נקיון|נתינה|סבלנות|סדר|סובלנות|סלחנות|ספונטניות|סקרנות|עבודת צוות|עדינות|עוצמה|עזרה לזולת|עליזות|ענווה|עצמאות|עקביות|עשיית הבדל|פטריוטיות|פרפקציוניזם|פשטות|פתיחות|צדק|צמיחה|צניעות|קבלה עצמית|קדושת החיים|קידמה|קלילות|רוגע|רוחניות|ריגוש|ריכוז|רכות|רצינות|רעות|שאפתנות|שוויון|שונות|שותפות|שחרור|שייכות|שיתוף|שלווה|שלום|שליטה|שלמות|שמחה|שמחת חיים|שפע|שקט|שקיפות|תושייה|תמימות|תעוזה"""
VALUES = VALUES.replace("אדיבות אהבה", "אדיבות|אהבה").split("|")


def article(slug, title, excerpt, body, cover, date, tags, layout="classic"):
    # The page title is the h1, so an article's top-level subheadings must be h2.
    if not any(b.get("style") == "h2" for b in body):
        for b in body:
            if b.get("style") == "h3":
                b["style"] = "h2"
    return {"_id": f"article-{slug}", "_type": "article", "title": title,
            "slug": {"_type": "slug", "current": slug}, "excerpt": excerpt, "coverImage": cover,
            "layout": layout, "publishedAt": date, "tags": tags, "body": body}


def old_articles():
    docs = []

    # תזונה מבריאה
    soup, _, lines = page("תזונה מבריאה")
    lines = content(lines, 2)  # image, title line
    out = []
    for l in lines:
        if o.plain(l["text"]) == "לצרף קישור למאמר על הנבטה":
            continue  # a note-to-self on the old page; replaced by a real link below
        if o.plain(l["text"]).startswith("קטניות מכל הסוגים במיוחד אם הם עוברים הנבטה"):
            l = {**l, "spans": [("קטניות מכל הסוגים במיוחד אם הם עוברים ", False, None, None),
                                ("הנבטה", False, None, "/articles/sprouting")]}
        out.append(l)
    body = blocks_from(out, {"גישת הצלחת היומית שלי": "lead", "re:^לתזונה פלקסטיבית": "h3",
                             "re:^היא נקראת – ניפוץ מיתוסים": "h3"}, "plate")
    docs.append(article("healthy-plate", "תזונה בריאה ומבריאה בגישה השלמה",
                        "גישת הצלחת היומית שלי – טכניקה שעושה סדר באכילה היומיומית: חצי צלחת ירקות ופירות, "
                        "רבע חלבונים, שמינית פחמימות ושמינית שומנים.",
                        body, img("old-daily-plate", "איך נרצה שהצלחת היומית שלנו תראה? ורוד – ירקות ופירות, "
                                  "צהוב – חלבונים, כחול – פחמימות, אדום – שומנים"),
                        o.published(soup), ["תזונה", "הגישה השלמה"]))

    # פטריות – הטיפול בהן
    soup, _, lines = page("פטריות - הטיפול בהן")
    lines = content(lines, 2)
    body = blocks_from(lines, {"מה עושים בטיפול?": "h3", "re:^מה ההנחיות התזונתיות הכלליות": "h3"}, "fungi")
    docs.append(article("fungi", "פטריות – הטיפול בהן",
                        "כמה זמן לוקח לפטריה לשגשג בגוף שלנו? האם יש דרך טבעית לטפל בה? מה אם יש אותה כבר שנים?",
                        body, img("old-fungi", "פטריה אדומה בטבע"), o.published(soup), ["גוף", "ארומתרפיה"]))

    # הגיינת הפה
    soup, _, lines = page("הגיינת הפה")
    lines = content(lines, 2)
    fixed = []
    for l in lines:
        if l["text"].startswith("◦"):
            sp = list(l["spans"])
            sp[0] = (sp[0][0].lstrip("◦ \t"),) + tuple(sp[0][1:])
            l = {**l, "spans": sp, "text": l["text"].lstrip("◦ "), "list": "ul"}
        fixed.append(l)
    body = blocks_from(fixed, {"טיפים כללים:": "h3", "מה כן לעשות?": "h3",
                               "re:^וגם – תחליפים מעולים": "h3", "רפואה שלמה": "center"}, "mouth")
    docs.append(article("oral-hygiene", "הגיינת הפה – המלצות",
                        "הרבה זמן חיפשנו את הדרך הטובה ביותר לשמור על חלל הפה שלנו: מה כדאי להפסיק, ומתכונים "
                        "לאבקת שיניים מחימר, מי פה בריאים, אויל פולינג וסרום לחניכיים.",
                        body, img("old-mouth", ""), o.published(soup), ["גוף", "ארומתרפיה"]))

    # שמני נשא
    soup, _, lines = page("שמני נשא")
    lines = split_long(content(lines, 2))
    oil = r"re:^(שמן|חמאת) [^.]{2,25} כבישה קרה\s*$"
    body = blocks_from(lines, {
        oil: "h3", "re:^שמן (גזר|קלנדולה|ארניקה)\\s*$": "h3",
        "re:^המלצות רכישת שמני נשא": "h2", "שמני נשא:": "h2",
        "re:^שמני נשא שניתן להוביל איתם תערובות": "h2",
        "re:^שמני נשא מיוחדים": "h2",
        "re:^קבוצת שמני נשא נוספת": "h2",
        "re:^מתכון להכנת שמן תשרית": "h3",
        "re:^שמני תשרית נפוצים": "h3",
    }, "oils")
    docs.append(article("carrier-oils", "שמני נשא – כל מה שרצית לדעת עליהם",
                        "שמני נשא, כל אחד מהם לעצמו, מביאים איתם תכונות שונות ומגוונות: המלצות רכישה, פירוט "
                        "של כל שמן – ספיגה, תוקף ולמה הוא מתאים – ומתכון להכנת שמן תשרית.",
                        body, img("old-carrier-oils", "גינה ירוקה וחממה"), o.published(soup), ["ארומתרפיה", "טיפוח"]))

    # ערכים
    soup, _, lines = page("ערכים")
    lines = content(lines, 1)
    body = blocks_from(lines, {}, "values")
    body += [text_block("רשימת ערכים", "h2"),
             text_block("אפשר להיעזר ברשימה כדי לבחור את חמשת הערכים שלך:"),
             {"_type": "tagCloud", "_key": k(), "title": "", "tags": VALUES},
             {"_type": "image", "_key": k(), "src": "/images/old-values-list.webp", "alt": "רשימת ערכים", "size": "narrow"}]
    docs.append(article("values", "ערכים",
                        "אם הייתי מבקשת ממך לבחור 5 ערכים שבעינייך חשובים ביותר – בין אם הם כבר לוקחים חלק "
                        "מחייך ובין אם לאו, מי הם היו?",
                        body, img("old-values-cover", "רשימת ערכים"), o.published(soup), ['שיטת אי"ך']))

    # הנבטה
    soup, _, lines = page("הנבטה")
    lines = numbered_list(content(lines, 1))
    body = [text_block("קטניות מונבטות", "lead")] + blocks_from(
        lines, {"re:^איך מנביטים": "h3", "re:^איזו קטנייה ניתן להנביט": "h3"}, "sprout")
    docs.append(article("sprouting", "הנבטה",
                        "קטניות מונבטות: איזו קטנייה ניתן להנביט, ואיך מנביטים בבית – שבעה צעדים פשוטים.",
                        body, img("old-sprouting", "קטניות מונבטות"), o.published(soup), ["תזונה"]))

    # הקלטות למטפלות ומתעניינות
    soup, _, lines = page("הקלטות למטפלות ומתעניינות")
    lines = split_long(content(lines, 1))
    lines = numbered_list(lines)
    body = blocks_from(lines, {"re:^הכשרות מוקלטות למטפלות": "lead",
                               "re:^רשימת הנושאים – הכשרות למטפלות": "h2",
                               "re:^רשימת הנושאים – הכשרות לכלל": "h2"}, "rec")
    body.append({"_type": "linkButton", "_key": k(), "label": "לתשלום וקבלת קישור – צרי קשר", "href": "/contact"})
    docs.append(article("recordings", "הקלטות למטפלות ומתעניינות",
                        "הכשרות מוקלטות למטפלות ולכלל המתעניינות: אומנות התשאול, בריאות האישה, הריון, תינוקות, "
                        "ארומתציה, ניפוץ מיתוסים בתזונה ועוד.",
                        body, img("herbs-woman", ""), o.published(soup), ["הכשרות"]))
    return docs


# ------------------------------------------------------------------ recipes
RECIPE_FILES = {
    # file name: (slug, title override or None)
    "אורז לניקוי": ("cleansing-rice", None),
    "בצק לפיצה": ("gluten-free-pizza-dough", None),
    "ג'לי": ("jelly", None),
    "חריימה טופו": ("tofu-chraime", None),
    "כמו-טונה טבעוני": ("vegan-tuna", None),
    "מוס שוקולד": ("chocolate-mousse", None),
    "מטבל ממרח שקדים מלוח": ("salty-almond-dip", None),
    "ניוקי ללא גלוטן": ("gluten-free-gnocchi", "ניוקי בטטה ותפוח אדמה"),
    "סושי ללא אורז": ("riceless-sushi", None),
    "סירופ אגסים": ("pear-syrup", None),
    "סלט טבולה קינואה": ("quinoa-tabbouleh", None),
    "סלט שורשים": ("root-salad", None),
    "עוגיות שקדים": ("almond-cookies", None),
    "עוגיות שקדים ללא אפיה": ("no-bake-almond-cookies", None),
    "עוגת דבש": ("honey-cake", None),
    "עוגת דבש ללא דבש": ("honeyless-honey-cake", None),
    "עוגת קינמון ותבלינים": ("cinnamon-spice-cake", None),
    "רוטב עגבניות לניוקי": ("tomato-sauce-for-gnocchi", "רוטב עגבניות לניוקי"),  # old page repeats the gnocchi title
    "שוקולד ביתי": ("homemade-chocolate", None),
}
# Recipes that also exist in the Word files: keep their step layout, take these from the old site.
OVERLAP_FILES = {
    "טורטיה ללא גלוטן": "gluten-free-tortilla", "לחם עדשים כתומות ": "red-lentil-bread",
    "לחם  שקדים": "almond-bread", "ממרח זיתים": "olive-spread", "ממרח טופו": "tofu-spread",
    "ממרח עגבניות": "tomato-spread", "ממרח פסטו": "pesto", "קרקים": "seed-crackers",
    "סלט טבולה כרובית": "cauliflower-tabbouleh", "פשטידת ברוקולי וכרובית": "broccoli-cauliflower-pie",
    "עוגיות שוקולד צ'יפס": "chocolate-chip-cookies", "עוגיות תמרים מיוחדות": "date-cookies",
    "רפאלו בריא": "healthy-raffaello",
}
CATEGORY_IMAGES = {"stew": "old-recipe-pot", "Cookies": "old-recipe-cookies", "cake": "old-recipe-cake",
                   "bread": "old-recipe-bread", "spread": "old-recipe-spread", "salad": "old-recipe-salad",
                   "pie": "old-recipe-pie"}
# Where a recipe's closing remarks begin (they become the recipe's afterword).
OUTRO_START = {
    "cleansing-rice": "האורז המומלץ ביותר", "jelly": "ג’לטין", "tofu-chraime": "מתכון אהוב מעולה",
    "vegan-tuna": "המרקם אמור להיות דומה", "gluten-free-gnocchi": "מומלץ להכין ביחד עם",
    "pear-syrup": "לאגסים", "almond-cookies": "העוגיות האלה הן נשנוש", "honeyless-honey-cake": "שתהיה שנה יפה",
    "cinnamon-spice-cake": "כשאנחנו מדברות על", "tomato-sauce-for-gnocchi": "יש גם מתכון לניוקי",
    "gluten-free-pizza-dough": "בתאבון",
    "tomato-spread": "הממרח הזה הוא", "date-cookies": "מומלץ לנשים הרות",
}
# Old pages where Word lost a line break between two ingredients.
ING_FIX = {
    "חופן קטן חמוציות ללא סוכר חופן קטן אגוזי מלך": ["חופן קטן חמוציות ללא סוכר", "חופן קטן אגוזי מלך"],
    "מיץ מחצי לימון טרי 4-6 כפות שמן זית מלח": ["מיץ מחצי לימון טרי", "4-6 כפות שמן זית", "מלח"],
}
TIPS_HEADING = re.compile(r"^(טיפים|טיפים להעשיר|הערות)\s*:?$")
TIPS = {"quinoa-tabbouleh": ["*לבדוק טעמים כמובן."],
        "honeyless-honey-cake": ["המתכון בכמות הזו מתאים לתבנית אינגליש קייק אחת."]}
INTRO_FROM_METHOD = {"salty-almond-dip": "דומה לממרח בוטנים וסויה כמטבל לסושי."}
STEP_HEADINGS = {"הרכבת הסושי", "המשך לפיצה:"}
GROUP_WORDS = {"יבשים", "רטובים", "תיבול"}

ING_START = re.compile(r"(^|\s)רכיבים(\s|$|:)")
METHOD_START = re.compile(r"^(אופן ה?הכנ|הכנת הבצק|להכנת הניוקי)")


def _tags_and_intro(line):
    parts = [p.strip(" .") for p in re.split(r"[,،]", line) if p.strip(" .")]
    tags = [p for p in parts if len(p.split()) <= 3]
    rest = [p for p in parts if len(p.split()) > 3]
    return tags, rest


def parse_recipe(lines, slug):
    rows = [l for l in lines if l["tag"] not in ("img", "gap")]
    title = o.plain(rows[0]["text"])
    rows = rows[1:]
    intro, tags, ingredients, steps, outro, tips = [], [], [], [], [], list(TIPS.get(slug, []))
    mode, heading = "intro", None
    outro_marker = OUTRO_START.get(slug)
    for l in rows:
        t = o.plain(l["text"]).replace("**", "")
        if not t:
            continue
        if (outro_marker and t.startswith(outro_marker)) or t == "בתאבון":
            mode = "outro"
        if mode == "outro":
            if t in [o.plain(x) for x in TIPS.get(slug, [])]:
                continue
            outro.append(l)
            continue
        if t in [o.plain(x) for x in TIPS.get(slug, [])]:
            continue
        if ING_START.search(t) and len(t) < 45:
            mode = "ing"
            group = re.sub(r"\s*[–-]?\s*רכיבים\s*[–-]?\s*", " ", t).strip(" –-")
            if group:
                ingredients.append(group + ":")
                heading = group
            continue
        if METHOD_START.match(t) or (t in STEP_HEADINGS):
            mode = "steps"
            if t in STEP_HEADINGS or (heading and METHOD_START.match(t)):
                steps.append({"heading": t.rstrip(":") if t in STEP_HEADINGS else heading})
                heading = None
            continue
        if mode == "intro":
            if not tags and "," in t and all(len(p.split()) <= 4 for p in t.split(",")) or t in ("ללא גלוטן",):
                tg, rest = _tags_and_intro(t)
                tags += tg
                if rest:
                    intro.append(text_block(", ".join(rest) + "."))
            else:
                intro.append(o.to_block(l, style="normal", seed=slug + t))
        elif mode == "ing":
            if t.rstrip(":") in GROUP_WORDS or (t.endswith(":") and len(t) < 30):
                ingredients.append(t.rstrip(":") + ":")
            else:
                ingredients.extend(ING_FIX.get(t, [t]))
        elif mode in ("steps", "tips"):
            if INTRO_FROM_METHOD.get(slug) == t:
                intro.append(text_block(t))
                continue
            if TIPS_HEADING.match(t):
                mode = "tips"
                continue
            if t.startswith("טיפ:"):
                tips.append(t.split(":", 1)[1].strip())
                continue
            if mode == "tips" or t.startswith("*"):
                if t.startswith("*") or not tips:
                    tips.append(t.lstrip("*").strip())
                else:
                    tips[-1] += " " + t
                continue
            if steps and "text" in steps[-1] and t.startswith(steps[-1]["text"]):
                steps[-1] = {"text": t}  # the old page repeats a step with more detail
                continue
            steps.append({"text": t})
    # step headings become their own entries; attach to the following step
    merged, pending_heading = [], None
    for s in steps:
        if "heading" in s:
            pending_heading = s["heading"]
            continue
        item = {"_key": k(), "_type": "recipeStep", "ingredients": [], "text": s["text"]}
        if pending_heading:
            item["heading"] = pending_heading
            pending_heading = None
        merged.append(item)
    outro_blocks = blocks_from(outro, {"רפואה שלמה": "center", "בתאבון": "center"}, slug + "-outro")
    return {"title": title, "tags": tags, "intro": intro, "ingredients": ingredients, "steps": merged,
            "tips": tips, "outro": outro_blocks}


def category_image(lines):
    for l in lines:
        if l["tag"] == "img":
            for key, name in CATEGORY_IMAGES.items():
                if l["src"].startswith(key + "-"):
                    return img(name, "")
    return None


# Recipe names as the old site listed them; a page heading that differs becomes the opening line.
LIST_TITLES = {
    "gluten-free-tortilla": "טורטיה ללא גלוטן", "red-lentil-bread": "לחם עדשים כתומות", "almond-bread": "לחם שקדים",
    "olive-spread": "ממרח זיתים", "tofu-spread": "ממרח טופו", "tomato-spread": "ממרח עגבניות", "pesto": "ממרח פסטו",
    "seed-crackers": "קרקרים", "cauliflower-tabbouleh": "סלט טבולה כרובית",
    "broccoli-cauliflower-pie": "פשטידת ברוקולי וכרובית", "chocolate-chip-cookies": "עוגיות שוקולד צ'יפס",
    "date-cookies": "עוגיות תמרים מיוחדות", "healthy-raffaello": "רפאלו בריא",
}


def old_recipes():
    """All 32 recipes of the old site, as recipe documents."""
    docs = []
    files = [(f, slug, title) for f, (slug, title) in RECIPE_FILES.items()]
    files += [(f, slug, LIST_TITLES[slug]) for f, slug in OVERLAP_FILES.items()]
    for fname, slug, title in files:
        soup, _, lines = page(os.path.join("תבלינים ומתכונים", fname))
        r = parse_recipe(lines, slug)
        intro = r["intro"]
        if title and o.plain(r["title"]).replace("’", "'") != title and slug in LIST_TITLES:
            intro = [text_block(r["title"], "lead")] + intro
        docs.append({
            "_id": f"recipe-{slug}", "_type": "recipe", "title": title or r["title"],
            "slug": {"_type": "slug", "current": slug}, "image": category_image(lines),
            "intro": intro, "tags": [t.lstrip("*") for t in r["tags"]], "spices": [],
            "ingredients": r["ingredients"], "steps": r["steps"], "tips": r["tips"], "outro": r["outro"],
            "publishedAt": o.published(soup),
        })
    return docs


def spice_notes():
    """Spice knowledge written inside recipes, for the spice pages (the recipe keeps it too)."""
    _, _, lines = page(os.path.join("תבלינים ומתכונים", "עוגת קינמון ותבלינים"))
    rows = [l for l in lines if l["tag"] != "img"]
    start = next(i for i, l in enumerate(rows) if o.plain(l["text"]).replace("**", "").startswith("כשאנחנו מדברות על"))
    end = next(i for i, l in enumerate(rows) if o.plain(l["text"]).startswith("והעוגה הזו"))
    return {"cinnamon": blocks_from(rows[start:end], {}, "cinnamon-note")}


# ------------------------------------------------------------------ images
NEEDED_IMAGES = {
    "old-daily-plate": ("תזונה מבריאה", "הצלחת-היומית-1-768x432.png"),
    "old-fungi": ("פטריות - הטיפול בהן", "fungels-768x511.jpg"),
    "old-mouth": ("הגיינת הפה", "mouth-768x512.jpg"),
    "old-carrier-oils": ("שמני נשא", "Local-Collaboration.jpg"),
    "old-values-list": ("ערכים", "רשימת-ערכים-שנינה-576x1024.png"),
    "old-sprouting": ("הנבטה", "הנבטה-2.png"),
    "old-recipe-pot": ("תבלינים ומתכונים", "stew-300x300.png"),
    "old-recipe-cookies": ("תבלינים ומתכונים", "Cookies-300x300.png"),
    "old-recipe-cake": ("תבלינים ומתכונים", "cake-300x300.png"),
    "old-recipe-bread": ("תבלינים ומתכונים/טורטיה ללא גלוטן", "bread-300x300.png"),
    "old-recipe-spread": ("תבלינים ומתכונים/כמו-טונה טבעוני", "spread-300x300.png"),
    "old-recipe-salad": ("תבלינים ומתכונים/סלט טבולה כרובית", "salad-300x300.png"),
    "old-recipe-pie": ("תבלינים ומתכונים/פשטידת ברוקולי וכרובית", "pie-300x300.png"),
}


def extract_images():
    """Save the images restored pages use into design/old-site (largest copy found)."""
    os.makedirs(IMG_OUT, exist_ok=True)
    for name, (pagefile, wanted) in NEEDED_IMAGES.items():
        _, images = o.load(_resolve(pagefile))
        stem = re.sub(r"-\d+x\d+(?=\.\w+$)", "", wanted)
        candidates = [(n, v) for n, v in images.items() if re.sub(r"-\d+x\d+(?=\.\w+$)", "", n) == stem]
        if not candidates:
            print("missing image", name, wanted)
            continue
        n, (ct, data) = max(candidates, key=lambda c: len(c[1][1] or b""))
        ext = os.path.splitext(n)[1] or ".png"
        open(os.path.join(IMG_OUT, name + ext), "wb").write(data)
        print("saved", name + ext, len(data) // 1024, "KB")
