"""Builds the site's starting content from Shanina's Word documents, the restored old site,
and the data files in scripts/data (meditations playlist, remedies catalogue).

Outputs:
  content/seed.json            - used by the site when no Sanity project is configured
  content/sanity-import/       - data.ndjson + images/, for `npm run import-seed` in /studio
                                 (relative asset paths, so it imports from any computer)

Run from the shanina-site folder:  python scripts/build-seed.py
The Word files and the "restoring old site" folder are read from the parent folder.
Only needed BEFORE the one-time import to Sanity: after that, Sanity is the source of the content
and re-importing with --replace would overwrite Shanina's edits.
"""
import json
import os
import re
import sys
import csv
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import docx_pt as d  # noqa: E402
import import_old  # noqa: E402  (content restored from the archived old site)

sys.stdout.reconfigure(encoding="utf-8")

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DOCS = os.path.dirname(ROOT)
IMAGES = os.path.join(ROOT, "web", "public", "images")

_key_counter = [0]


def k():
    _key_counter[0] += 1
    return f"k{_key_counter[0]:04d}"


def doc(name):
    return d.read_paragraphs(os.path.join(DOCS, name))


def blocks(paragraphs, center=None):
    return d.to_blocks(paragraphs, center=center)


def between(paragraphs, start, end=None, include_start=True):
    return blocks(d.slice_between(paragraphs, start, end, include_start))


def items(paragraphs, start, end=None):
    """Each non-empty paragraph becomes its own block (list items)."""
    ps = [p for p in d.slice_between(paragraphs, start, end) if d.para_text(p)]
    return [d.to_blocks([p], center=False)[0] for p in ps]


def text(s, style="normal", marks=None):
    return d.plain_block(s, style, marks)


def img(name, alt=""):
    return {"_type": "image", "src": f"/images/{name}.webp", "alt": alt}


def section(_type, **fields):
    return {"_type": _type, "_key": k(), **fields}


def button(label, href, variant="primary"):
    return {"_key": k(), "label": label, "href": href, "variant": variant}


def ref(_id):
    return {"_type": "reference", "_ref": _id, "_key": k()}


def page(slug, title, sections, description="", **extra):
    return {"_id": f"page-{slug}", "_type": "page", "title": title,
            "slug": {"_type": "slug", "current": slug}, "description": description,
            "sections": sections, **extra}


WHATSAPP = "https://api.whatsapp.com/message/3XGICYGP2MV6P1?autoload=1&app_absent=0"
YOUTUBE = "https://www.youtube.com/@shaninaWay"

# ---------------------------------------------------------------- settings
principles_src = doc("2. מי אני.docx")
principle_ps = [p for p in d.slice_between(principles_src, "העבר שלך", None) if d.para_text(p)]
# "קחי אחריות" and the sentence after it are one principle in the source layout.
grouped, i = [], 0
while i < len(principle_ps):
    group = [principle_ps[i]]
    if d.para_text(principle_ps[i]).startswith("קחי") and i + 1 < len(principle_ps):
        group.append(principle_ps[i + 1])
        i += 1
    grouped.append(group)
    i += 1
principles = [{"_key": k(), "text": blocks(g, center=False)} for g in grouped]

settings = {
    "_id": "siteSettings",
    "_type": "siteSettings",
    "title": "שנינה",
    "ownerName": "שני קפלן סרודי",
    "tagline": "מטפלת בגישה שלמה",
    "modalities": ["נטורופתיה", "רפלקסולוגיה", "ארומתרפיה", 'שיטת אי"ך', "נומרולוגיה"],
    "description": "שני קפלן סרודי – מטפלת בגישה שלמה: נטורופתיה, רפלקסולוגיה, ארומתרפיה, "
                   'שיטת אי"ך ונומרולוגיה. באר שבע או אונליין.',
    "phone": "050-2156640",
    "email": "shaninab7@gmail.com",  # shown on the site (contact page, footer); Shanina asked for this address
    "whatsappUrl": WHATSAPP,
    "location": "באר שבע או אונליין",
    "social": {
        "instagram": "https://www.instagram.com/shaninaway",
        "youtube": YOUTUBE,
        "tiktok": "https://www.tiktok.com/@shaninaway",
        "facebook": "https://www.facebook.com/SHANINA.CLINIC.PAGE",
        "facebookMethod": "https://www.facebook.com/howshanina",
        "facebookPersonal": "https://www.facebook.com/iamshanina",
        "telegram": "https://t.me/youthechange",
        "podcast": "",
    },
    "instagramHandle": "shaninaway",
    "principles": principles,
    "medicalDisclaimer": "התכנים באתר נועדו לספק מידע בלבד ואינם מהווים עצה רפואית "
                         "או תחליף להתייעצות עם רופא/ה.",
}

# ---------------------------------------------------------------- home
home_src = doc("1. עמוד הבית.docx")
home = page("home", "עמוד הבית", [
    section("hero",
            title="ברוכה הבאה",
            text=[text("טוב שהגעת – אם את חדשה הקדישי כמה רגעים לקרוא את ההקדמה למטה.", "center")],
            note="*התכנים כתובים בלשון נקבה. מופנים לכל מי שכאן על כל האפשרויות הקיימות.",
            image=img("shani-flowers", "שני קפלן סרודי עם זר פרחים"),
            buttons=[button("לשיחת היכרות", WHATSAPP), button("להקדמה", "#intro", "ghost")]),
    section("tilesSection", heading="", tiles=[
        {"_key": k(), "title": "טיפולים", "href": "/treatments", "image": img("alchemy", "")},
        {"_key": k(), "title": "הגישה השלמה", "href": "/articles", "image": img("four-bodies", "")},
        {"_key": k(), "title": 'שיטת אי"ך', "href": "/method", "image": img("bridge-color", "")},
        {"_key": k(), "title": "מי אני", "href": "/about", "image": img("shani-smile", "")},
        {"_key": k(), "title": "תבלין ומתכון", "href": "/recipes", "image": img("spices", "")},
        {"_key": k(), "title": "הכשרות ואירועים", "href": "/events", "image": img("meditation-hands", "")},
        {"_key": k(), "title": "צרי קשר", "href": "/contact", "image": img("shani-vivian", "")},
    ]),
    section("richTextSection", anchor="intro", heading="", width="narrow", background="floral",
            body=between(home_src, "אם הגעת לכאן", "כמה הנחות יסוד")),
    section("principlesSection", heading="כמה הנחות יסוד שהן הבסיס להכל", intro=[]),
    section("latestSection", heading="מאמרים בגישה השלמה", kind="article", count=3,
            linkLabel="לכל המאמרים"),
    section("latestSection", heading="תבלין ומתכון", kind="recipe", count=3,
            linkLabel="לכל המתכונים"),
    section("instagramSection", heading="מהאינסטגרם", handle="shaninaway"),
    section("ctaSection", heading="כשאת מוכנה, המורה תגיע.",
            text=[text("לשיחת היכרות, לשאלה או סתם להגיד שלום – אני כאן.", "center")],
            buttons=[button("לכתוב לי בוואטסאפ", WHATSAPP), button("לכל דרכי הקשר", "/contact", "ghost")]),
], description="שנינה – שני קפלן סרודי, מטפלת בגישה שלמה.")

# ---------------------------------------------------------------- about
about_src = doc("2. מי אני.docx")
about = page("about", "אודותיי", [
    section("richTextSection", heading="נעים להכיר", width="wide", background="none",
            image=img("shani-smile", "שני קפלן סרודי"), imagePosition="start",
            body=between(about_src, "נעים להכיר", "דרכי כמטפלת")),
    section("richTextSection", heading="", width="narrow", background="tint",
            body=between(about_src, "דרכי כמטפלת", "מאז שנת 2010")),
    section("principlesSection", heading="העקרונות שמנחים אותי",
            intro=between(about_src, "מאז שנת 2010", "העבר שלך")),
    section("ctaSection", heading='"מודטים עם שנינה"',
            text=[text("מפגשי המדיטציה והדמיון המודרך – התרומה שלי לקהילה. בזום ובערוץ היוטיוב.", "center"),
                  text('הערוץ כולו לעילוי נשמת יניב סרודי ז"ל, שנרצח ב-07/10/2023 ובדרכו האחרונה הציל 7 אנשים.',
                       "center", ["sm"])],
            buttons=[button("לערוץ היוטיוב", YOUTUBE)]),
], description="נעים להכיר, קוראים לי שני קפלן סרודי – מטפלת בגישה שלמה.")

# ---------------------------------------------------------------- method
method_src = doc("3. שיטת איך.docx")
method = page("method", 'שיטת אי"ך', [
    section("acronymSection",
            letters=[{"_key": k(), "letter": "א", "word": "אמונות"},
                     {"_key": k(), "letter": "י", "word": "ידיעה"},
                     {"_key": k(), "letter": "ך", "word": "כוונה"}],
            body=between(method_src, "השיטה שמובילה", "מאיפה כל זה")),
    section("richTextSection", heading="מאיפה כל זה התחיל...", width="wide", background="none",
            image=img("hand-how", 'המילה "איך" כתובה על כף היד'), imagePosition="end",
            body=between(method_src, "קבלתי הכשרות", "למי מתאימה", include_start=True)),
    section("listSection", heading="למי מתאימה השיטה?", marker="flower",
            items=items(method_src, "למי שרוצה לגשר", "זה נכון")),
    section("richTextSection", heading="", width="narrow", background="tint",
            body=between(method_src, "זה נכון", "השיטה מחולקת")),
    section("stepsSection", heading="איך זה עובד",
            intro=between(method_src, "השיטה מחולקת", "המפגש הראשון"),
            steps=[
                {"_key": k(), "title": "המפגש הראשון",
                 "body": between(method_src, "המפגש הראשון", "בשאר המפגשים")},
                {"_key": k(), "title": "אמונות",
                 "body": between(method_src, "בשאר המפגשים", "נתחבר למקור")},
                {"_key": k(), "title": "ידיעה",
                 "body": between(method_src, "נתחבר למקור", "וגם – נדייק")},
                {"_key": k(), "title": "כוונה",
                 "body": between(method_src, "וגם – נדייק", "מענין אותך")},
            ]),
    section("ctaSection", heading="מעניין אותך?",
            text=[text("הנה כמה פרטים לצאת איתם לדרך...", "center")]
                 + between(method_src, "הטיפולים מתקיימים"),
            buttons=[button("לשיחת התאמה", WHATSAPP), button("לטיפולים בקליניקה", "/treatments", "ghost")]),
], description='שיטת אי"ך – אמונות, ידיעה, כוונה. השיטה שמובילה להלימה בין הפעולות בחייך '
               "לבין הערכים והאמונות שלך.")

# ---------------------------------------------------------------- treatments
tr_src = doc("5. טיפולים בקליניקה.docx")
conditions = d.para_text(next(p for p in tr_src if d.para_text(p).startswith("מחלות מעי")))
requests = d.para_text(next(p for p in tr_src if d.para_text(p).startswith("גם לבקשות")))


def split_tags(s):
    s = s.split("–", 1)[-1] if s.startswith("גם") else s
    return [t.strip(" .") for t in s.split(",") if t.strip(" .")]


when_items = items(tr_src, "אם את מתמודדת")
# "אם את פשוט מרגישה..." continues on the next line in the source.
merged = []
for b in when_items:
    first = b["children"][0]["text"] if b["children"] else ""
    if merged and first.startswith("ויכול"):
        merged[-1]["children"] += [{"_type": "span", "_key": c["_key"] + "m", "text": c["text"], "marks": c["marks"]}
                                   for c in [{"_key": "nl", "text": "\n", "marks": []}] + b["children"]]
    else:
        merged.append(b)

treatments = page("treatments", "טיפולים בקליניקה", [
    section("richTextSection", heading="", width="narrow", background="none",
            body=between(tr_src, "הטיפולים שאני הכי אוהבת", "תחילת התהליך")),
    section("richTextSection", heading="תחילת התהליך", width="narrow", background="tint",
            body=between(tr_src, "אנחנו מנהלות", "קליניקה")),
    section("quoteSection", body=between(tr_src, "קליניקה", "טיפול בשיטת")),
    section("cardsSection", heading="ארגז הכלים", layout="toolbox", intro=[], cards=[
        {"_key": k(), "title": 'טיפול בשיטת אי"ך', "icon": "spiral",
         "body": between(tr_src, "שיטת אי\"ך היא", "טיפול נטורופתי"),
         "href": "/method", "linkLabel": 'עוד על שיטת אי"ך'},
        {"_key": k(), "title": "טיפול נטורופתי", "icon": "leaf", "body": between(tr_src, "טיפול שמתחיל", "טיפול רפלקסולוגי")},
        {"_key": k(), "title": "טיפול רפלקסולוגי", "icon": "foot", "body": between(tr_src, "טיפול מגע", "טיפול ארומתרפי")},
        {"_key": k(), "title": "טיפול ארומתרפי", "icon": "drop", "body": between(tr_src, "שמנים אתרים, באיכות", "חשוב לי להוסיף")},
    ]),
    section("richTextSection", heading="", width="narrow", background="none",
            body=between(tr_src, "חשוב לי להוסיף", "אלה הנושאים")),
    section("tagsSection", heading="אלה הנושאים בהם יש לי ניסיון טיפולי", groups=[
        {"_key": k(), "title": "", "tags": split_tags(conditions)},
        {"_key": k(), "title": "גם לבקשות שאינן רפואיות", "tags": split_tags(requests)},
    ], note="הטיפול בגישה שלמה משלים את הטיפול הרפואי ואינו מחליף אותו."),
    section("listSection", heading="מתי תרצי להגיע אלי לטיפול?", marker="flower", items=merged),
    section("ctaSection", heading="נצא לדרך?",
            text=[text("שיחת ההיכרות הראשונה נמשכת כשעה וחצי – פנים מול פנים או באונליין.", "center")],
            buttons=[button("לתיאום בוואטסאפ", WHATSAPP), button("050-2156640", "tel:0502156640", "ghost")]),
], description="נטורופתיה, רפלקסולוגיה, ארומתרפיה ושיטת אי\"ך – טיפולים בגישה שלמה.")

# ---------------------------------------------------------------- articles
art_src = doc("4. מאמרים בגישה השלמה.docx")
articles_page = page("articles", "מאמרים בגישה השלמה", [
    section("richTextSection", heading="", width="narrow", background="none",
            body=between(art_src, "אם ביקרת כאן", "למה גישה שלמה")),
], description="מאמרים על הגישה השלמה – גוף, רגש, מחשבה ורוח.")


def article(slug, title, excerpt, body, image=None, layout="poetic", date="2026-10-01", tags=()):
    return {"_id": f"article-{slug}", "_type": "article", "title": title,
            "slug": {"_type": "slug", "current": slug}, "excerpt": excerpt,
            "coverImage": image, "layout": layout, "publishedAt": date,
            "tags": list(tags), "body": body}


coming_soon = [text("המאמר המלא יעלה בקרוב.", "center")]
# Articles that appeared on the old site (full text restored), newest first by their original dates.
articles = import_old.old_articles() + [
    article("why-whole-approach", "למה גישה שלמה?",
            'מה "האובססיה" שלי לגישה השלמה, למה אין תרופות פלא, ומה הם ארבעת הגופים שבהם נוגע כל תהליך ריפוי.',
            between(art_src, "למה גישה שלמה", "רשימת מאמרים"), img("light-bokeh", ""),
            date="2025-01-18", tags=["הגישה השלמה"]),
]

# ---- הקלטות למטפלות ומתעניינות: the topic list as Shanina updated it (Nov 2026)
def rec_item(title, desc="", price=""):
    spans = [(title, ["strong"])]
    if desc:
        spans.append((" – " + desc, []))
    if price:
        spans.append((" " + price, ["strong"]))
    b = d.block(spans, "normal", seed="rec-" + title)
    b["listItem"], b["level"] = "number", 1
    return b


REC_PRO = [
    ("אומנות התשאול", "העמקה על טופס התשאול, דרך השאלות, למה חשוב לשים לב ואיך ומה נכון לשאול.", '75 ש"ח'),
    ("שלוש הרצאות מרתקות בנושא בריאות האישה",
     "המחזור החודשי, איברי מערכת המין הנשית, הורמונים, הגיינה נשית, ומה הגישה השלמה אומרת על כל זה. "
     "בריאות הנרתיק, מיניות, אנדומטריוזיס, היעדר וסת ודימום מוגבר, שחלות פוליציסטיות, תסמונת קדם וסתית PMS, "
     "רחם אחורי, גיל המעבר. שלוש ההרצאות האלה הן הרצאות רצופות.", '225 ש"ח'),
    ("הריון", "כניסה להריון, בחילות, דלקות גרון, בעיות חניכיים וכאבי שיניים, כאבי אגן.", '75 ש"ח'),
    ("תינוקות וקטנטנים", "שמן תינוקות למטפלות, אזהרות כלליות, שיניים וגזים, צינון, שינה, עור, דלקות שתן חוזרות. "
     "יכולה להתאים לבדה או להגיע בחבילה עם הרצאת הריון.", '75 ש"ח'),
    ("הרצאת כוכב", "שלושה נושאים חשובים – קקיולוגיה: יציאות במערכת העיכול. קפה: מיתוס הבריאות. "
     "ימים של חוסר ודאות – מה ניתן לעשות? מהו חוסן? מלחמה, החלמה והלחמה.", '75 ש"ח'),
    ("העיסוי המלא", "סרטון מפורט על העיסוי הארומתרפי המלא – הדגמה בלבד, ללא קול וכתוביות.", '75 ש"ח'),
    ("סטרס, לחץ וחרדה", "הרצאה למטפלים שכוללת את כל ההסברים.", '75 ש"ח'),
    ("הפרעת קשב וריכוז אצל מבוגרים", "", '75 ש"ח'),
    ("תשאול ילדים", "כל הדגשים החשובים ונורות האזהרה שחשוב להכיר.", '75 ש"ח'),
    ("מיגרנות וכאבי ראש", "", '75 ש"ח'),
    ("צ'אקרות, יסודות וארבעת הגופים", "הכל אחד. ואיך נעזרים בזה בטיפול?", '75 ש"ח'),
    ("גיל המעבר", "", '75 ש"ח'),
    ("טיפול פנים טבעי באמת", "", '75 ש"ח'),
    ("הכיני גופך לחורף", "ילדים ומבוגרים.", "בקרוב"),
    ("מחלות נפוצות בילדים", "", "בקרוב"),
    ("הליקובקטר פילורי", "", "בקרוב"),
]
REC_PUBLIC = [
    ("מפגשי ארומתציה", "מפגשי מדיטציה עם ניחוח של תבלין. עשרה פרקים – בכל פרק תבלין אחר ונושא אחר, "
     "תבלינים כמו לימון, רוזמרין, קוריאנדר ועוד. על כל מפגש בודד 75 ש\"ח; ברכישת כלל הפרקים –", '500 ש"ח'),
    ("ניפוץ מיתוסים בתזונה", "ההרצאה שתלמד אותך הכל. הרצאה שעוזרת לנו לחשוב מחדש על מה נכנס לנו למטבח "
     "ומשם לגוף. מומלצת ואהובה במיוחד!", '75 ש"ח'),
]
for a_ in articles:
    if a_["_id"] == "article-recordings":
        old = a_["body"]
        intro = old[:2]                     # lead line + "במהלך השנים האחרונות…" paragraph
        footer = [b for b in old if b.get("_type") == "linkButton" or
                  (b.get("_type") == "block" and "המחירים עשויים" in "".join(c["text"] for c in b["children"]))]
        a_["body"] = intro + [
            text("רשימת הנושאים – הכשרות למטפלות", "h2"),
            text("מטפלים ומטפלות שנמצאים בקבוצת הפרקטיקום לטיפול השלם של שנינה – יש הנחה על ההקלטות והמפגשים.",
                 "normal", ["accent"]),
            *[rec_item(*r) for r in REC_PRO],
            text("רשימת הנושאים – הרצאות לקהל הרחב", "h2"),
            *[rec_item(*r) for r in REC_PUBLIC],
            *footer,
        ]
        a_["excerpt"] = ("הקלטות והרצאות למטפלות ולקהל הרחב: אומנות התשאול, בריאות האישה, הריון, תינוקות, "
                         "סטרס וחרדה, ארומתציה, ניפוץ מיתוסים בתזונה ועוד.")

# Planned in the Word files but never published on the old site: drafts in Sanity, hidden on the site.
draft_articles = [
    article("disease-process", "תהליך חדירת מחלה",
            "חשבת על זה פעם? איך מחלה חודרת לנו לגוף? האם יש לנו דרך לשמוע או לדעת על הגעתה? "
            "הגוף הפיזי שלנו, הוא לא הגוף היחיד שלנו.",
            coming_soon, img("four-bodies", "ארבעת הגופים"), date="2026-10-05", tags=["ארבעת הגופים"]),
    article("digestive-system", "מערכת העיכול",
            "המערכת הרגישה ביותר שהרי היא פשוט צינור ובו פתח כניסה ופתח יציאה. "
            "תקראי כאן על תקינות המערכת והפעולות שיש בה.",
            coming_soon, img("library", ""), layout="classic", date="2026-09-01", tags=["גוף", "תזונה"]),
    article("hot-drinks", "משקאות חמים",
            "בכל מקום בעולם, בכל זמן, כנראה שיש מישהו ששותה עכשיו משקה חם. מי מהם עדיף? מה עדיף בו? "
            "למי הוא עדיף? ומתי הוא עדיף? קפה, קקאו וחליטות צמחים.",
            coming_soon, img("white-canvas", ""), layout="classic", date="2026-08-15", tags=["תזונה"]),
]
draft_articles = []  # only teasers existed; removed at Shanina's request

# ---------------------------------------------------------------- recipes & spices
rec_src = doc("6. תבלינים ומתכונים.docx")
recipes_page = page("recipes", "תבלין ומתכון", [
    section("richTextSection", heading="", width="narrow", background="none",
            body=between(rec_src, "ברחבי הרשת", "מנוע חיפוש")),
], description="להכיר את התבלין ותכונות הריפוי שלו – בחיבור עם המתכון.")

RECIPE_TITLES = {
    "לחם שקדים": ("almond-bread", "לחם שקדים", ["ללא גלוטן"], []),
    "לחם עדשים כתומות": ("red-lentil-bread", "לחם עדשים כתומות", ["ללא גלוטן"], ["oregano"]),
    "טורטיה ללא גלוטן": ("gluten-free-tortilla", "טורטיה ללא גלוטן", ["ללא גלוטן", "טבעוני"], []),
    "ממרח פסטו": ("pesto", "ממרח פסטו", ["ממרחים", "טבעוני"], ["basil", "garlic"]),
    "ממרח עגבניות": ("tomato-spread", "ממרח עגבניות", ["ממרחים", "טבעוני"], ["garlic"]),
    "ממרח זיתים": ("olive-spread", "ממרח זיתים", ["ממרחים", "טבעוני"], ["garlic"]),
    "ממרח טופו": ("tofu-spread", "ממרח טופו", ["ממרחים", "טבעוני"], ["garlic"]),
    "קרקים": ("seed-crackers", "קרקרים", ["ללא גלוטן", "טבעוני"], ["oregano"]),
    "סלט טבולה כרובית": ("cauliflower-tabbouleh", "סלט טבולה כרובית", ["סלטים", "טבעוני"], []),
    "פשטידת ברוקולי וכרובית": ("broccoli-cauliflower-pie", "פשטידת ברוקולי וכרובית", ["ללא גלוטן"], []),
    "עוגיות שוקולד צ'יפס": ("chocolate-chip-cookies", "עוגיות שוקולד צ'יפס", ["מתוקים"], []),
    "עוגיות תמרים מיוחדות": ("date-cookies", "עוגיות תמרים מיוחדות", ["מתוקים", "ללא גלוטן"], ["cinnamon", "cardamom"]),
    "רפלאו בריא": ("healthy-raffaello", "רפאלו בריא", ["מתוקים", "ללא גלוטן"], []),
}
RECIPE_IMAGES = {"almond-bread": "recipes-board", "date-cookies": "spices"}


def norm(s):
    return re.sub(r"\s+", " ", s).strip()


def _core(s):
    return norm(re.sub(r"\(.*?\)", "", s))


def match_ingredients(line, ingredients):
    """Ingredients a method line repeats. The method often restates an ingredient
    slightly shorter ("חצי כפית אורגנו" for "... (לא חובה)"), or runs two
    together where Word lost the line break."""
    if len(line) > 90:
        return []
    for ing in ingredients:
        if line in (ing, _core(ing)) or (_core(ing).startswith(line) and len(line) > 6):
            return [ing]
    found, rest = [], line
    while rest:
        for ing in ingredients:
            for candidate in (ing, _core(ing), " ".join(_core(ing).split()[:3])):
                if len(candidate) > 3 and rest.startswith(candidate):
                    found.append(ing)
                    rest = norm(rest[len(candidate):])
                    break
            else:
                continue
            break
        else:
            return []
    return found


def parse_recipes(paragraphs):
    lines = []
    started = False
    for p in paragraphs:
        t = "".join(r["text"] for r in p["runs"])
        if not started:
            started = norm(t) == "מתכון ותבלין"
            continue
        lines.extend(norm(x) for x in t.split("\n"))
    recipes, cur, mode, pending = [], None, None, []
    for line in lines:
        if not line:
            continue
        if line in RECIPE_TITLES:
            cur = {"key": line, "ingredients": [], "steps": [], "tips": []}
            recipes.append(cur)
            mode, pending = None, []
            continue
        if cur is None:
            continue
        if line == "רכיבים":
            mode = "ing"
            continue
        if line == "אופן ההכנה":
            mode = "steps"
            continue
        if re.match(r"^(טיפים|טיפים להעשיר|הערות)\s*:?$", line):
            mode = "tips"
            continue
        if line.startswith("טיפ:"):
            cur["tips"].append(line.split(":", 1)[1].strip())
            continue
        if mode == "ing":
            cur["ingredients"].append(line)
        elif mode == "steps":
            matched = match_ingredients(line, cur["ingredients"])
            if matched:
                pending.extend(matched)
            else:
                cur["steps"].append({"_key": k(), "ingredients": pending, "text": line})
                pending = []
        elif mode == "tips":
            cur["tips"].append(line.lstrip("*").strip())
    return recipes


spices = {
    "oregano": "אורגנו", "basil": "בזיליקום", "garlic": "שום",
    "cinnamon": "קינמון", "cardamom": "הל", "paprika": "פפריקה",
}
# Which recipes use which spice (shown on each spice page and as filters).
SPICE_RECIPES = {
    "cinnamon": ["date-cookies", "cinnamon-spice-cake", "pear-syrup", "honeyless-honey-cake", "honey-cake"],
    "garlic": ["pesto", "tomato-spread", "olive-spread", "tofu-spread", "vegan-tuna", "tomato-sauce-for-gnocchi"],
    "basil": ["pesto", "tomato-sauce-for-gnocchi"],
    "oregano": ["red-lentil-bread", "seed-crackers"],
    "cardamom": ["date-cookies"],
    "paprika": ["tofu-chraime", "tomato-sauce-for-gnocchi"],
}
spice_docs = [{
    "_id": f"spice-{slug}", "_type": "spice", "name": name,
    "slug": {"_type": "slug", "current": slug},
    "intro": [text("כאן יופיע תיאור קצר של התבלין: תכונות הריפוי שלו – שנחקרו או שידועות כחכמת השבט – "
                   "וכמה עובדות עליו.")],
    "facts": [],
} for slug, name in spices.items()]

recipe_docs = []
for i, r in enumerate(parse_recipes(rec_src)):
    slug, title, tags, spice_refs = RECIPE_TITLES[r["key"]]
    for st in r["steps"]:
        st["_type"] = "recipeStep"
    recipe_docs.append({
        "_id": f"recipe-{slug}", "_type": "recipe", "title": title,
        "slug": {"_type": "slug", "current": slug},
        "image": img(RECIPE_IMAGES[slug], "") if slug in RECIPE_IMAGES else None,
        "tags": tags, "spices": [],
        "ingredients": r["ingredients"], "steps": r["steps"], "tips": r["tips"],
        "publishedAt": f"2026-09-{28 - i:02d}",
    })

# The old site has all 32 recipes; its text is the published, more detailed one, so it wins.
# From the Word versions we keep only the tags added there (the old pages rarely had tags).
word_tags = {r["slug"]["current"]: r["tags"] for r in recipe_docs}
recipe_docs = import_old.old_recipes()
for r in recipe_docs:
    r["tags"] = list(dict.fromkeys(r["tags"] + word_tags.get(r["slug"]["current"], [])))
# Details that only the Word version has.
WORD_ONLY_TIPS = {
    "red-lentil-bread": ["אפשר גם להכניס את כל מרכיבי הלחם מלבד התוספות לבלנדר ולערבב היטב לבלילה אחידה. "
                         "ניתן גם לערבב עם בלנדר מוט, מטרפה או מיקסר רק שימו לב לערבב היטב שלא יישארו גושי קמח בבלילה."],
}
for r in recipe_docs:
    r["tips"] += WORD_ONLY_TIPS.get(r["slug"]["current"], [])

by_slug = {r["slug"]["current"]: r for r in recipe_docs}
for spice_slug, recipe_slugs in SPICE_RECIPES.items():
    for rs in recipe_slugs:
        by_slug[rs]["spices"].append(ref(f"spice-{spice_slug}"))

# The cinnamon cake's note on Ceylon cinnamon and cassia is the cinnamon page's text.
notes = import_old.spice_notes()
for sd in spice_docs:
    slug = sd["slug"]["current"]
    if slug in notes:
        sd["intro"] = notes[slug]

# ---------------------------------------------------------------- events & links
ev_src = doc("7. הכשרות ואירועים .docx")
events_page = page("events", "הכשרות, אירועים וקישורים", [
    section("latestSection", heading="לוח אירועים קרובים", kind="event", count=6,
            linkLabel="", intro=[text("(ימי מדיטציה, הרצאות ועוד)\nימים ושעות זמינים לטיפולים", "center")]),
    section("richTextSection", heading="", width="narrow", background="floral",
            body=[d.block([("חשוב לי לשתף בכל פועלי.", ["xxl"]), ("\n", []),
                           ("את יכולה להצטרף אלי בעזרת החיבורים הבאים:", ["lg"])], "center", seed="ev-intro")]),
    section("cardsSection", heading="", layout="numbered", intro=[], cards=[
        {"_key": k(), "title": "פרקטיקום לטיפול השלם",
         "body": between(ev_src, "מותאם", "2") + [{
             "_type": "block", "_key": k(), "style": "normal",
             "markDefs": [{"_type": "link", "_key": "lrec", "href": "/articles/recordings"}],
             "children": [{"_type": "span", "_key": k(), "marks": [],
                           "text": "על הדרכות והעשרות למטפלים ומטפלות בגישה השלמה בנושאים השונים – "},
                          {"_type": "span", "_key": k(), "marks": ["lrec"], "text": "לחצו כאן."}]}],
         "href": "/contact", "linkLabel": "להצטרפות"},
        {"_key": k(), "title": 'טיפולים פרטניים לפי שיטת אי"ך',
         "body": [text('טיפולים פרטניים לפי שיטת אי"ך.')],
         "href": "/method", "linkLabel": "לפירוט מלא"},
        {"_key": k(), "title": "ערוץ מדיטציות ביוטיוב",
         "body": [text("ערוץ מדיטציות נפלא נהדר. סופר ממולץ."),
                  text("ואם את כבר שם, תשאירי תגובה לייק ועוקב,\nזה ללא עלות עבורך ומאוד מקדם אותי.", "normal", ["sm"]),
                  text('בנימה אישית, הערוץ הוא לעילוי נשמת יניב סרודי ז"ל שנרצח בגבורה ב-7.10.2023. '
                       "תהיה נשמתו עדן. יהיה זכרו ברוך.", "normal", ["sm"])],
         "href": YOUTUBE, "linkLabel": "לערוץ"},
        {"_key": k(), "title": "להיות השינוי שאתה רוצה בעולם",
         "body": between(ev_src, "קבוצת תובנות", "https://t.me"),
         "href": "https://t.me/youthechange", "linkLabel": "לקבוצת הטלגרם"},
        {"_key": k(), "title": "פודקאסט – בגישה שלמה", "body": [text("פתוח לכולן – האזנה נעימה.")],
         "href": "", "linkLabel": "יעלה ממש בקרוב"},
    ]),
    section("videoPlaylistSection", heading="פינת המדיטציות",
            intro="מדיטציות ודמיון מודרך – לפי הסדר, מהראשונה ואילך. לבחור אחת, להתרווח ולצאת למסע.",
            playlistUrl="https://www.youtube.com/playlist?list=PL3UW_4SWt1nqzO2Vw_ouDGvFg2FiG-z79",
            linkLabel="לכל הפלייליסט ביוטיוב",
            videos=json.load(open(os.path.join(ROOT, "scripts", "data", "meditations.json"), encoding="utf-8"))),
    section("cardsSection", heading="קורסים ותהליכים", layout="programs", intro=[], cards=[
        {"_key": k(), "title": "ארומתציה", "status": "available", "price": '75 ש"ח למפגש\n500 ש"ח לכל הסדרה',
         "body": [text("קורס מוקלט בו כל מפגש מכיל נושא שקשור לתבלין שיש לנו בבית ביחד עם הסבר והרחבה על הנושא "
                       "ואז ליישום בעזרת מדיטציה מרחיבת תודעה מעצימה וקסומה במיוחד. מומלץ בחום."),
                  text('75 ש"ח לכל מפגש בודד, או 500 ש"ח לכל עשרת המפגשים.')],
         "href": "/articles/recordings", "linkLabel": "לכל ההקלטות"},
        {"_key": k(), "title": "קורס פיתוח העסק למטפלות", "status": "soon",
         "body": [text("למעלה מחצי שנה. הקורס יכיל סרטונים קצרים ובלי הבטחות מיותרות. פשוט וקל ליישום. "
                       "הוא אכן מצריך הרבה יצירתיות ומקצועיות. עוד פרטים בהמשך.")],
         "href": "", "linkLabel": ""},
        {"_key": k(), "title": 'אי"ך לחיות אחרת', "status": "soon",
         "body": [text('קורס העצמה אישית לפי שיטת אי"ך. פרטים ממש בקרוב. פתוח לכל האוכלוסיה.')],
         "href": "", "linkLabel": ""},
        {"_key": k(), "title": "קבוצת 40 יום ניקוי", "status": "ended", "price": '160 ש"ח לכל התהליך',
         "body": [text("27.10.2024", "normal", ["strong"]),
                  text("קבוצת וואטאסאפ בה יש כל יום הודעה ומשימה. 40 יום מתחלקים ל-3 חלקים:"),
                  text("חלק ראשון – ניקוי התפריט שלנו וחיבור להקשבה ולגוף.\n"
                       "חלק שני – ניקוי של 10 ימים תפריט מצומצם ויעיל שישאיר אותך שבעה.\n"
                       "החלק השלישי האחרון – כניסה לאורח חיים בריא, הכרות עם אבות המזון, העמקת החיבור לגוף "
                       "וההקשבה לגוף."),
                  text('כל הקסם הזה ב160 ש"ח לכל התהליך כולו! תמהרו לשריין את מקומכן…', "normal", ["strong"])],
         "href": "/contact", "linkLabel": "למחזור הבא – צרי קשר"},
    ]),
], description="הכשרות למטפלות, מדיטציות, אירועים קרובים וקהילה.")

LECTURE_NOTE = ('ההרשמה בהצטרפות לקבוצת הוואטסאפ של ההרצאה. יש הקלטה – היא נשלחת בקבוצה עד שבוע אחרי ההרצאה, '
                'אז כדאי להישאר בקבוצה.')


def event(slug, title, kind, start, end, price, url, body):
    return {"_id": f"event-{slug}", "_type": "event", "title": title, "kind": kind,
            "start": start, "end": end, "price": price, "registrationUrl": url,
            "description": [text(t) for t in body]}


events = [
    event("winter-body-2026-11", "הכיני את גופך לחורף", "lecture",
          "2026-11-12T20:00:00+02:00", "2026-11-12T21:30:00+02:00", '70 ש"ח',
          "https://chat.whatsapp.com/DWq1mvqwfI1AaITCmWvkht", [LECTURE_NOTE]),
    event("women-cards-2026-11", "נשים.קלפים.תודעה.", "workshop",
          "2026-11-19T10:30:00+02:00", "2026-11-19T13:30:00+02:00", '70 ש"ח',
          "https://chat.whatsapp.com/FeNPneXB5GBGiI97uE7AWx",
          ["ההרשמה בהצטרפות לקבוצת הוואטסאפ של המפגש."]),
    event("h-pylori-2026-11", "הליקובקטר פילורי", "lecture",
          "2026-11-19T20:00:00+02:00", "2026-11-19T21:30:00+02:00", '70 ש"ח',
          "https://chat.whatsapp.com/JLz6oAHJOiG3uJjkhfMbDV", [LECTURE_NOTE]),
    event("aich-business-2026-11", 'אי"ך? עסק משלך – מפגש הזנקה', "training",
          "2026-11-22T20:00:00+02:00", "2026-11-22T21:30:00+02:00", '340 ש"ח לכל התהליך',
          "https://chat.whatsapp.com/KuauOjMAzUfBVgEFSGqyWK", [
              "ייתכן שהתאריך ישתנה – עדכון יישלח בקבוצה.",
              'הקמת עסק לפי שיטת אי"ך (אמונות, ידיעה, כוונה): תהליך מרגש, מעצים ומדייק, שעוזר לך להיות בפוקוס '
              "על הכיוון שלך ובונה לך תוכנית פעולה שכולה שלך – מתאימה לך ונוחה לך.",
              "התהליך נמשך חודשיים: מפגש הזנקה, מפגש מסכם בחודש שאחריו, ובאמצע קבוצה עם משימות, תרגולים "
              "ועבודה שיתופית בהובלתי. מפגש ההזנקה מומלץ לכל מי שרוצה לקחת חלק בתהליך.",
              'כל התהליך, כולל הליווי בקבוצה – 340 ש"ח.',
          ]),
    event("kids-illness-2026-11", "מחלות נפוצות בילדים", "lecture",
          "2026-11-29T20:00:00+02:00", "2026-11-29T21:30:00+02:00", '70 ש"ח',
          "https://chat.whatsapp.com/HdpUzgSkzzk6ikfykoXWVo", [LECTURE_NOTE]),
]

# ---------------------------------------------------------------- remedies (המרקחות של שנינה)
products = []
for i, p_ in enumerate(json.load(open(os.path.join(ROOT, "scripts", "data", "products.json"), encoding="utf-8"))):
    products.append({
        "_id": f"product-{p_['slug']}", "_type": "product", "title": p_["title"],
        "slug": {"_type": "slug", "current": p_["slug"]}, "tagline": p_.get("tagline", ""),
        "sizes": [{"_key": k(), "_type": "productSize", "size": s_, "price": pr} for s_, pr in p_["sizes"]],
        **{f: p_[f] for f in ("usage", "ingredients", "benefits", "warnings", "note") if p_.get(f)},
        "order": (i + 1) * 10, "available": True,
    })

remedies = page("remedies", "המרקחות של שנינה", [
    section("productsSection", heading="",
            intro=[text("מרקחות שאני רוקחת בעבודת יד – לטיפול ולטיפוח. "
                        "אפשר גם לתאם טיפול ולקבל מרקחת בהתאמה אישית.", "center")],
            notice="המרקחות של שנינה הן בגדר המלצה ואינן מחליפות טיפול תרופתי ו/או המלצות רופא/ה או מטפל/ת.\n"
                   "ארומתרפיה אסורה לנשים בטיפולי פוריות ו/או שימור, לבעלי תפקוד נמוך של הכליות, "
                   "בשילוב עם תרופות הומאופתיות ובשילוב עם תרופות סטרואידליות.\n"
                   "נא לעדכן את שנינה לגבי רגישויות ואלרגיות ידועות, ולקרוא היטב את האזהרות לפני רכישה.",
            ctaText="להזמנה או להתאמה אישית – כתבי לי"),
], description="מרקחות ארומתרפיות בעבודת יד – שמנים, סרומים, קרמים, בשמים וחליטות צמחים.")

# ---------------------------------------------------------------- contact
ct_src = doc("8. צור קשר.docx")
contact = page("contact", "צרי קשר", [
    section("contactSection", heading="", image=img("shani-vivian", "שני עם ויויאן"),
            caption="(אני כאן בתמונה עם ויויאן שלנו)", showForm=True,
            body=between(ct_src, "בפגישה פורנטלית")),
], description="טלפון, וואטסאפ, מייל ורשתות חברתיות – באר שבע או אונליין.")

# ---------------------------------------------------------------- legal drafts
DRAFT = "טיוטה – יש להעביר לבדיקת עורך/ת דין לפני העלייה לאוויר."
terms = page("terms", "תקנון ותנאי שימוש", [section("richTextSection", heading="", width="narrow", background="none", body=[
    text(DRAFT, "normal", ["sm"]),
    text("כללי", "h2"),
    text('האתר shanina.co.il (להלן: "האתר") מופעל על ידי שני קפלן סרודי, מטפלת בגישה שלמה. '
         "השימוש באתר כפוף לתנאים המפורטים כאן. התכנים כתובים בלשון נקבה ומיועדים לכל המינים."),
    text("אין תחליף לייעוץ רפואי", "h2"),
    text("התכנים באתר נועדו לספק מידע והשראה בלבד, ואינם מהווים אבחנה, עצה רפואית או תחליף להתייעצות "
         "עם רופא/ה. אין להפסיק או לשנות טיפול רפואי על סמך התכנים באתר. במצב חירום יש לפנות מיד לרופא/ה "
         "או לחדר מיון."),
    text("טיפולים, תשלום וביטולים", "h2"),
    text("התשלום על טיפול מתבצע מראש. ביטול עד 24 שעות לפני מועד הטיפול – החזר כספי מלא. "
         "ביטול בפחות מ-24 שעות לפני מועד הטיפול – החזר של 50%."),
    text("קניין רוחני", "h2"),
    text("כל התכנים באתר – טקסטים, מתכונים, תמונות ואיורים – שייכים לשני קפלן סרודי, אלא אם צוין אחרת. "
         "מותר לשתף קישור לתכנים; העתקה או פרסום מחדש מותרים רק בהסכמה בכתב."),
    text("קישורים לאתרים אחרים", "h2"),
    text("האתר כולל קישורים לרשתות חברתיות ולאתרים חיצוניים. האחריות על תכניהם ועל מדיניות הפרטיות שלהם "
         "חלה על מפעיליהם."),
    text("שינויים בתקנון", "h2"),
    text("התקנון עשוי להתעדכן מעת לעת. הנוסח המחייב הוא הנוסח המופיע באתר."),
])], description="תקנון ותנאי שימוש באתר שנינה.")

privacy = page("privacy", "מדיניות פרטיות", [section("richTextSection", heading="", width="narrow", background="none", body=[
    text(DRAFT, "normal", ["sm"]),
    text("איזה מידע נאסף", "h2"),
    text("כאשר את פונה דרך טופס יצירת הקשר, נשמרים הפרטים שמסרת (שם, טלפון/מייל ותוכן הפנייה) "
         "לצורך מענה בלבד. האתר אינו משתמש בעוגיות פרסום ואינו מוכר מידע לצדדים שלישיים."),
    text("מידע רפואי", "h2"),
    text("מידע אישי ורפואי שנמסר במסגרת טיפול נשמר בסודיות ואינו מועבר לאיש."),
    text("שירותים חיצוניים", "h2"),
    text("האתר מאוחסן ב-Cloudflare, ותוכן האתר מנוהל ב-Sanity. סרטוני יוטיוב ופוסטים מאינסטגרם "
         "מוטמעים מהשירותים עצמם וכפופים למדיניות הפרטיות שלהם."),
    text("פנייה בנושא פרטיות", "h2"),
    text("לעיון, תיקון או מחיקה של מידע: shaninush@gmail.com או 050-2156640."),
])], description="מדיניות הפרטיות של אתר שנינה.")

accessibility = page("accessibility", "הצהרת נגישות", [section("richTextSection", heading="", width="narrow", background="none", body=[
    text(DRAFT, "normal", ["sm"]),
    text("חשוב לי שהאתר יהיה נגיש ונוח לכל אחת ואחד, כולל אנשים עם מוגבלות."),
    text("רמת הנגישות", "h2"),
    text("האתר נבנה בהתאם לתקן הישראלי ת\"י 5568 (המבוסס על הנחיות WCAG 2.0) ברמה AA."),
    text("מה נעשה באתר", "h2"),
    text("ניווט מלא במקלדת, קישור לדילוג לתוכן, טקסט חלופי לתמונות, ניגודיות צבעים תקינה, "
         "התאמה מלאה לנייד, כיבוד הגדרת \"הפחתת תנועה\" במערכת, ותפריט נגישות להגדלת טקסט, "
         "ניגודיות גבוהה והדגשת קישורים."),
    text("נתקלת בבעיה?", "h2"),
    text("אם נתקלת ברכיב שאינו נגיש, אשמח שתספרי לי ואטפל בהקדם: שני קפלן סרודי, "
         "050-2156640, shaninush@gmail.com."),
    text("ההצהרה עודכנה לאחרונה: אוקטובר 2026."),
])], description="הצהרת הנגישות של אתר שנינה.")

# ---------------------------------------------------------------- write
documents = [settings, home, about, method, treatments, articles_page, recipes_page, events_page, remedies, *products,
             contact, terms, privacy, accessibility, *articles, *draft_articles, *spice_docs, *recipe_docs, *events]

# Spelling fixes, applied to every text in the content.
TYPOS = {
    "סופר ממולץ": "סופר מומלץ", "ממולץ": "מומלץ", "מענין": "מעניין",
    "ארומתרפסטית": "ארומתרפיסטית", "ביקרותית": "ביקורתית", "חשיבת גדולה": "חשיבות גדולה",
    "פורנטלית": "פרונטלית", "בעולך": "בעולמך", "אחרי השגים": "אחרי הישגים",
    "קמחח": "קמח", "בקרעה": "בקערה", "העבניות": "העגבניות", "וואטאסאפ": "וואטסאפ", "וואטאספ": "וואטסאפ",
    "קבצת טלגרם": "קבוצת טלגרם", "ככך שיכסה": "כך שיכסה", "ההנבטת קטניות": "הנבטת קטניות",
    "טמפרוטורת": "טמפרטורת", "מוספים": "מוסיפים", "אישת עבורך": "אישית עבורך", "בכמוית": "בכמויות",
    "אויל פוילנג": "אויל פולינג", "בחומצות ושמן טובות": "בחומצות שומן טובות", "אלופציה אאורטה": "אלופציה אראטה",
    "פיתחת שיטה": "פיתחתי שיטה", "מיטבים איתך": "מיטיבים איתך", "שמיטבה אישית": "שמיטיבה אישית",
    "ההבטים": "ההיבטים", "שנתכתב": "שנכתב", "שוקולד מומוס": "שוקולד מומס", "חימום ועליון": "חימום עליון",
    "פושרים-חממים": "פושרים-חמימים", "ימביא עימו": "מביא עימו", "אמא שלי בקשה": "אמא שלי ביקשה",
    "אברים המערכת מין נשית": "איברי מערכת המין הנשית", "קרקים": "קרקרים", "לטיפוח ולטיפוח": "לטיפול ולטיפוח",
    "אי”ך": 'אי"ך', "אי״ך": 'אי"ך', "שיטת איך": 'שיטת אי"ך', "התחדשות בריאה של תאי עור (לא מאיץ": "התחדשות בריאה של תאי עור (לא מאיץ",
}


def fix_typos(value):
    if isinstance(value, str):
        for wrong, right in TYPOS.items():
            value = value.replace(wrong, right)
        return value
    if isinstance(value, list):
        return [fix_typos(v) for v in value]
    if isinstance(value, dict):
        return {key: (v if key in ("_id", "_key", "_ref", "_type", "slug", "src", "href", "style") else fix_typos(v))
                for key, v in value.items()}
    return value


documents = [fix_typos(d_) for d_ in documents]


def replace_url_with_link(value, url, phrase):
    """A bare URL printed after a phrase ("…בערוץ היוטיוב שלי" + newline + URL) becomes a link on the phrase."""
    if isinstance(value, list):
        for v in value:
            replace_url_with_link(v, url, phrase)
    elif isinstance(value, dict):
        kids = value.get("children")
        if value.get("_type") == "block" and kids and any(c.get("text", "").strip() == url for c in kids):
            kids[:] = [c for c in kids if c.get("text", "").strip() != url]
            for i, c in enumerate(kids):
                t = c.get("text", "")
                if phrase in t:
                    before, after = t.split(phrase, 1)
                    after = after.rstrip("\n") or "."
                    mk = "lnk" + c["_key"][:6]
                    value.setdefault("markDefs", []).append({"_type": "link", "_key": mk, "href": url})
                    kids[i:i + 1] = [{**c, "text": before}, {**c, "_key": k(), "text": phrase, "marks": c.get("marks", []) + [mk]},
                                     {**c, "_key": k(), "text": after}]
                    break
        else:
            for v in value.values():
                replace_url_with_link(v, url, phrase)


replace_url_with_link(documents, "https://www.youtube.com/channel/UCSyuqJIxq-7flgDuOmW4vdA", "ערוץ היוטיוב שלי")

# Array items need the member type name the schema gives them (see studio/schemas).
ITEM_TYPES = {"tiles": "tile", "letters": "letter", "cards": "card", "groups": "tagGroup",
              "principles": "principle", "buttons": "button"}


def add_item_types(value, parent_type=None):
    if isinstance(value, dict):
        for key, v in value.items():
            if isinstance(v, list) and v and isinstance(v[0], dict) and "_type" not in v[0]:
                item_type = ITEM_TYPES.get(key)
                if key == "steps":
                    item_type = "recipeStep" if value.get("_type") == "recipe" else "step"
                if item_type:
                    for item in v:
                        item.setdefault("_type", item_type)
            add_item_types(v, value.get("_type", parent_type))
    elif isinstance(value, list):
        for v in value:
            add_item_types(v, parent_type)


for document in documents:
    add_item_types(document)

os.makedirs(os.path.join(ROOT, "content"), exist_ok=True)
with open(os.path.join(ROOT, "content", "seed.json"), "w", encoding="utf-8") as f:
    json.dump(documents, f, ensure_ascii=False, indent=1)


# ---- Sanity import package: content/sanity-import/{data.ndjson, images/}
# A self-contained folder with relative asset paths (file://./images/…), so the import works on any
# computer: `sanity dataset import ../content/sanity-import production` (see studio/package.json).
IMPORT_DIR = os.path.join(ROOT, "content", "sanity-import")
used_images = set()


def for_sanity(value, in_array=False):
    """Local image paths -> _sanityAsset (uploaded by `sanity dataset import`).
    Images inside rich text keep their block type `image` (+ caption, size, _key);
    image fields use the `imageWithAlt` object type."""
    if isinstance(value, dict):
        if value.get("_type") == "image" and "src" in value:
            name = os.path.basename(value["src"])
            used_images.add(name)
            out = {k_: v for k_, v in value.items() if k_ not in ("src", "_type") and v is not None}
            out["_type"] = "image" if in_array else "imageWithAlt"
            out["_sanityAsset"] = f"image@file://./images/{name}"
            if in_array:
                out.setdefault("_key", "img" + re.sub(r"\W", "", name)[:10])
            return out
        return {key: for_sanity(v) for key, v in value.items() if v is not None}
    if isinstance(value, list):
        return [for_sanity(v, True) for v in value]
    return value


import shutil  # noqa: E402

if os.path.isdir(IMPORT_DIR):
    shutil.rmtree(IMPORT_DIR)
os.makedirs(os.path.join(IMPORT_DIR, "images"))
with open(os.path.join(IMPORT_DIR, "data.ndjson"), "w", encoding="utf-8") as f:
    for document in documents:
        f.write(json.dumps(for_sanity(document), ensure_ascii=False) + "\n")
for name in sorted(used_images):
    shutil.copyfile(os.path.join(IMAGES, name), os.path.join(IMPORT_DIR, "images", name))
old_ndjson = os.path.join(ROOT, "content", "seed.ndjson")
if os.path.exists(old_ndjson):
    os.remove(old_ndjson)  # replaced by content/sanity-import/

print(f"{len(documents)} documents: {len(articles)} articles (+{len(draft_articles)} drafts), "
      f"{len(recipe_docs)} recipes, {len(spice_docs)} spices, {len(events)} events")
for r in recipe_docs:
    print(f"  {r['title']}: {len(r['ingredients'])} ingredients, {len(r['steps'])} steps, {len(r['tips'])} tips")
with open("articles.csv", "w") as csvf:
    cw = csv.DictWriter(csvf, fieldnames=articles[0].keys())
    cw.writeheader()
    for a in articles:
        print(a)
        cw.writerow(a)
