"""Read the archived WordPress/Elementor site (MHTML files saved from the Wayback Machine).

Turns each page into "lines": paragraphs with Portable Text spans, carrying the same
word-level vocabulary as the Word import (strong + sizes sm/lg/xl/xxl), links remapped
to the new site's paths, and images by their original file name.

Needs BeautifulSoup:  pip install beautifulsoup4
"""
import email
import hashlib
import os
import re
import urllib.parse
from email import policy

from bs4 import BeautifulSoup, Comment, NavigableString, Tag

BASE_PX = 18.5  # Elementor body text on the old site (1.8rem / 14pt / 18.67px)

OLD_PATHS = {
    "": "/",
    "מי-אני": "/about",
    "שיטת-איך": "/method",
    "מאמרים": "/articles",
    "טיפולים-בקליניקה": "/treatments",
    "תבלינים-ומתכונים": "/recipes",
    "הכשרות-ואירועים": "/events",
    "צור-קשר": "/contact",
    "הצלחת-היומית-שלי": "/articles/healthy-plate",
    "פטריות": "/articles/fungi",
    "הגיינת-הפה": "/articles/oral-hygiene",
    "שמני-נשא": "/articles/carrier-oils",
    "ערכים": "/articles/values",
    "הנבטה": "/articles/sprouting",
    "הקלטות_למטפלות_ומתעניינות": "/articles/recordings",
    "רוטב_עגבניות_לניוקי": "/recipes/tomato-sauce-for-gnocchi",
    "ניוקי_ללא_גלוטן": "/recipes/gluten-free-gnocchi",
    "ניוקי-ללא-גלוטן": "/recipes/gluten-free-gnocchi",
}


# ------------------------------------------------------------------ loading
def load(path):
    """MHTML -> (BeautifulSoup, {image file name: (content_type, bytes)})."""
    msg = email.message_from_binary_file(open(path, "rb"), policy=policy.default)
    html, images = None, {}
    for part in msg.walk():
        ct = part.get_content_type()
        if ct == "text/html" and html is None:
            html = part.get_payload(decode=True).decode("utf-8", errors="replace")
        elif ct.startswith("image/"):
            name = urllib.parse.unquote(part.get("Content-Location", "").split("/")[-1])
            images[name] = (ct, part.get_payload(decode=True))
    return BeautifulSoup(html or "", "html.parser"), images


def remap_href(href):
    if not href:
        return None
    href = re.sub(r"^https?://web\.archive\.org/web/[0-9a-z_]+/", "", href)
    m = re.match(r"^https?://(www\.)?shanina\.co\.il/?([^#?]*)", href)
    if not m:
        return href if href.startswith(("http", "mailto:", "tel:")) else None
    slug = urllib.parse.unquote(m.group(2)).strip("/")
    return OLD_PATHS.get(slug, "/" if not slug else None)


def image_name(src):
    src = re.sub(r"^https?://web\.archive\.org/web/[0-9a-z_]+/", "", src or "")
    return urllib.parse.unquote(src.split("/")[-1])


# ------------------------------------------------------------------ inline -> spans
def _px(style):
    m = re.search(r"font-size:\s*([\d.]+)\s*(px|pt|rem|em)", style or "")
    if not m:
        return None
    v, unit = float(m.group(1)), m.group(2)
    return v * {"px": 1, "pt": 4 / 3, "rem": 10, "em": BASE_PX}[unit]


def size_mark(px):
    if px is None:
        return None
    if px < 15:
        return "sm"
    if px < 21.5:
        return None
    if px < 26:
        return "lg"
    if px < 32:
        return "xl"
    return "xxl"


def _bold(el):
    st = el.get("style", "") if isinstance(el, Tag) else ""
    return el.name in ("b", "strong") or bool(re.search(r"font-weight:\s*(bold|[6-9]00)", st))


def spans_of(el, state=None, out=None):
    """Flatten inline content into [(text, bold, size_px, href)] with '\n' for <br>."""
    state = state or {"bold": False, "px": None, "href": None}
    out = [] if out is None else out
    for c in el.children:
        if isinstance(c, Comment):
            continue
        if isinstance(c, NavigableString):
            t = str(c).replace("\xa0", " ")
            t = re.sub(r"\[(if [^\]]*|endif)\]", "", t)
            if t:
                out.append((t, state["bold"], state["px"], state["href"]))
        elif isinstance(c, Tag):
            if c.name == "br":
                out.append(("\n", False, None, None))
                continue
            if c.name in ("script", "style", "svg", "img"):
                continue
            s = dict(state)
            if _bold(c):
                s["bold"] = True
            px = _px(c.get("style", ""))
            if px:
                s["px"] = px
            if c.name == "a" and c.get("href"):
                s["href"] = remap_href(c["href"])
            spans_of(c, s, out)
    return out


BLOCK_TAGS = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "figure", "table", "section"}


def _align(el):
    for node in [el, *el.parents][:3]:
        if isinstance(node, Tag) and re.search(r"text-align:\s*center", node.get("style", "")):
            return "center"
    return None


def lines_of(container):
    """Block-level walk: every paragraph/heading/list item becomes one line dict."""
    lines = []

    def emit(el, tag, spans):
        text = "".join(s[0] for s in spans)
        if not text.strip():
            if tag == "p":
                lines.append({"tag": "gap", "spans": [], "text": ""})
            return
        lines.append({"tag": tag, "spans": spans, "text": text.strip(), "align": _align(el),
                      "list": el.name == "li" and el.parent.name if el.name == "li" else None,
                      "px": _px(el.get("style", ""))})

    def walk(el):
        pending = []
        for c in el.children:
            if isinstance(c, Comment):
                continue
            if isinstance(c, Tag) and c.name == "img":
                lines.append({"tag": "img", "src": image_name(c.get("src")), "alt": c.get("alt", ""), "text": ""})
                continue
            if isinstance(c, Tag) and c.name in BLOCK_TAGS:
                if pending:
                    emit(el, "p", pending)
                    pending = []
                if c.name in ("ul", "ol", "div", "section", "figure", "table", "blockquote") and c.find(list(BLOCK_TAGS | {"img"})):
                    walk(c)
                elif c.name in ("ul", "ol"):
                    walk(c)
                else:
                    tag = c.name if c.name in ("h1", "h2", "h3", "h4", "h5", "h6", "li") else "p"
                    state = {"bold": _bold(c), "px": _px(c.get("style", "")), "href": None}
                    emit(c, tag, spans_of(c, state))
                    for img in c.find_all("img"):
                        lines.append({"tag": "img", "src": image_name(img.get("src")), "alt": img.get("alt", ""), "text": ""})
            else:
                if isinstance(c, Tag):
                    if c.name == "br":
                        pending.append(("\n", False, None, None))
                        continue
                    state = {"bold": _bold(c), "px": _px(c.get("style", "")),
                             "href": remap_href(c.get("href")) if c.name == "a" else None}
                    pending.extend(spans_of(c, state))
                else:
                    t = str(c).replace("\xa0", " ")
                    if t.strip():
                        pending.append((t, False, None, None))
        if pending:
            emit(el, "p", pending)

    walk(container)
    return lines


def page_lines(soup):
    """All content lines of a page, in order, without the shared footer and mobile duplicates."""
    root = soup.find(attrs={"data-elementor-type": re.compile("wp-(post|page)")})
    out = []
    for w in root.select(".elementor-widget"):
        if w.find_parent(class_="elementor-widget") is not None:
            continue
        hidden = " ".join(" ".join(a.get("class") or []) for a in [w, *w.parents] if isinstance(a, Tag))
        if "elementor-hidden-desktop" in hidden or "ftter" in hidden:
            continue
        kind = (w.get("data-widget_type") or "").split(".")[0]
        if kind == "heading":
            h = w.find(re.compile("^h[1-6]$"))
            if h and h.get_text(strip=True) in ("קישור מהיר", "איש קשר"):
                break
            if h:
                out.append({"tag": h.name, "spans": spans_of(h, {"bold": False, "px": _px(h.get("style", "")), "href": None}),
                            "text": h.get_text(" ", strip=True), "align": None, "list": None, "px": None, "widget": "heading"})
        elif kind == "image":
            img = w.find("img")
            if img:
                out.append({"tag": "img", "src": image_name(img.get("src")), "alt": img.get("alt", ""), "text": ""})
        elif kind == "text-editor":
            box = w.find(class_="elementor-widget-container") or w
            out.extend(lines_of(box))
        elif kind == "button":
            a = w.find("a")
            out.append({"tag": "button", "text": w.get_text(" ", strip=True), "href": remap_href(a.get("href") if a else None)})
    return out


def published(soup):
    m = soup.find("meta", attrs={"property": "article:published_time"})
    return m["content"][:10] if m else None


# ------------------------------------------------------------------ lines -> Portable Text
def _key(*parts):
    return hashlib.md5("|".join(map(str, parts)).encode("utf8")).hexdigest()[:12]


def to_block(line, style=None, extra_marks=(), seed=""):
    """One line -> one PT block. Heading tags pick a style; long 'headings' become emphasis."""
    tag = line["tag"]
    text_len = len(line["text"])
    marks_all = list(extra_marks)
    if style is None:
        if tag in ("h1", "h2") and text_len <= 50:
            style = "h2"
        elif tag in ("h3", "h4", "h5", "h6") and text_len <= 60:
            style = "h3"
        else:
            style = "center" if line.get("align") == "center" else "normal"
            if tag in ("h1",):
                marks_all.append("xl")
            elif tag in ("h2", "h3"):
                marks_all.append("lg")
            elif tag in ("h4", "h5", "h6"):
                marks_all.append("strong")
    defs, children = [], []
    line_px = line.get("px")
    for text, bold, px, href in line.get("spans", []):
        marks = list(marks_all)
        if bold and style not in ("h2", "h3", "lead"):
            marks.append("strong")
        sm = size_mark(px or line_px)
        if sm and style not in ("h2", "h3", "lead") and sm not in marks:
            marks.append(sm)
        if href:
            k = _key("link", href)
            if k not in [d["_key"] for d in defs]:
                defs.append({"_type": "link", "_key": k, "href": href})
            marks.append(k)
        if text == "\n":
            marks = []
        if children and (children[-1]["marks"] == marks or not text.strip(" ")):
            children[-1]["text"] += text
        else:
            children.append({"_type": "span", "text": text, "marks": marks})
    # tidy whitespace
    for c in children:
        c["text"] = re.sub(r"[ \t]+", " ", c["text"]).replace(" \n", "\n").replace("\n ", "\n")
    if children:
        children[0]["text"] = children[0]["text"].lstrip()
        children[-1]["text"] = children[-1]["text"].rstrip()
    children = [c for c in children if c["text"]]
    for i, c in enumerate(children):
        c["_key"] = _key(seed, i, c["text"])
    block = {"_type": "block", "_key": _key(seed, style, line["text"]), "style": style,
             "markDefs": defs, "children": children}
    if line.get("list"):
        block["listItem"] = "number" if line["list"] == "ol" else "bullet"
        block["level"] = 1
    return block


def plain(text):
    return re.sub(r"\s+", " ", text.replace("\xa0", " ")).strip()
