#!/usr/bin/env python3
"""Place every node type on a real Mosaic document, ONE AT A TIME, and record what happened.

    python sweep_node_types.py --config sweep.json --setup            # build master + template
    python sweep_node_types.py --config sweep.json --sweep            # run the isolated sweep

sweep.json needs: base, version, cookie, nonce, themeID. --setup fills in masterID,
templateID and parentNodeID and writes them back.

## Which page it reads

The template --setup creates is assigned to `archive-post.php` - the post archive -
so the probes render wherever WordPress serves that archive. That used to be `/`,
and the sweep read `/`. Then the site got a static front page (`show_on_front=page`),
`/` became an ordinary page with its own template, and the sweep went on committing
probes into a master nothing rendered: every type, a plain `div` included, came
back COMMITTED. Nothing failed; it simply measured the wrong page.

So the page is named rather than assumed: `sweepPath` in the config, default
`?post_type=post`, which serves the post archive whatever the front page is set to.
Before a sweep, a plain `div` is committed and looked for on that page; if it does
not render, the run stops instead of recording a column of false COMMITTEDs.

## Why one at a time

A batch sweep is worthless here. Mosaic accepts structurally impossible placements at
commit time - a second `master-root` nested inside a `div` commits fine - and then the
*whole page* fails to render, emitting a bare string like
`NodeMResourceFilterFunctionInterface parent is missing` as a 200 with a ~54 byte body.
One bad type therefore destroys the evidence for every other type in the same batch.

So each type gets the document to itself: commit -> render -> classify -> delete. A type
that breaks the page only reports its own failure, and the next type starts from a clean
tree. This costs one page load per type and is the only way the numbers mean anything.

## Outcomes

    RENDERED    committed, and its attrID appeared in the delivered HTML
    COMMITTED   the row exists but nothing reached the page (usually needs content
                or a specific parent to produce output)
    BROKE_PAGE  committed, and the page stopped rendering - the silent-failure case
    REJECTED    the commit came back with an `exceptions` body (HTTP 200)
"""
import mosaic_config
import argparse
import csv
import json
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid

MARKER = "MOSAICSWEEP"
# types whose job is to hold text get a wysiwyg-text child, so the assertion has
# something to find beyond the wrapper element
TEXT_HOLDERS = {"text", "button", "menu-link", "label", "submit-label", "accordion-title"}
# a healthy render of the probe page is far bigger than this; anything smaller is
# Mosaic's bare error string rather than a page
MIN_HEALTHY_BYTES = 2000


class Client:
    def __init__(self, cfg):
        self.cfg = cfg
        self.base = cfg["base"].rstrip("/")
        self.api = "%s/wp-json/mosaic/v%s" % (self.base, cfg["version"])

    def _call(self, url, form=None):
        data = urllib.parse.urlencode(form).encode() if form else None
        req = urllib.request.Request(url, data=data, method="POST" if form else "GET")
        req.add_header("Cookie", self.cfg["cookie"])
        req.add_header("X-WP-Nonce", self.cfg["nonce"])
        if form:
            req.add_header("Content-Type", "application/x-www-form-urlencoded")
        try:
            with urllib.request.urlopen(req, timeout=120) as r:
                return json.loads(r.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            body = e.read().decode("utf-8", "replace")[:400]
            if "rest_cookie_invalid_nonce" in body or "rest_not_logged_in" in body:
                # the session minted by mint_session.php ran out mid-run (its cookie
                # lasts 12h by default, the wp_rest nonce at most a day); say so
                # instead of leaving a bare 403 in the middle of a build
                body = ("SESSION EXPIRED - mint a new one (wp eval-file tools/mint_session.php) "
                        "and update MOSAIC_REST_COOKIE / MOSAIC_REST_NONCE or --config. " + body)
            return {"_httperror": e.code, "_body": body}

    def theme_url(self, tail):
        return "%s/theme/%s/%s" % (self.api, self.cfg["themeID"], tail)

    def get(self, tail):
        return self._call(self.theme_url(tail))

    def api_get(self, tail):
        """A route outside the theme, e.g. `settingsEditorInstance` (Mosaic → Settings),
        which lives at /mosaic/v<version>/ and 404s under /theme/<id>/."""
        return self._call("%s/%s" % (self.api, tail))

    def commit(self, tail, sync, revisions):
        return self._call(
            self.theme_url(tail + "/commit"),
            {"syncCheckEnvelopes": json.dumps(sync), "revisionEnvelopes": json.dumps(revisions)},
        )

    def page(self, path=""):
        """Fetch a public page, cache-busted. `path` picks a page other than the home page:
        a slug (`my-page`) or a query (`?post_type=post`)."""
        bust = uuid.uuid4().hex[:8]
        if path.startswith("?"):
            url = "%s/%s&sweep=%s" % (self.base, path, bust)
        else:
            url = "%s/%s?sweep=%s" % (self.base, path.strip("/") + "/" if path else "", bust)
        req = urllib.request.Request(url)
        try:
            with urllib.request.urlopen(req, timeout=120) as r:
                return r.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as e:
            # A 5xx is not a page. WordPress answers a render-time PHP fatal with a
            # 2,697-byte "critical error" document, which is LARGER than
            # MIN_HEALTHY_BYTES - so returning that body made build_site print
            # "OK 2645 bytes" over a dead page, and probe.py call it healthy. An
            # empty string is what every byte-based check downstream already
            # treats as broken. 4xx bodies are kept: a 404 page is real content
            # and a 406 has none.
            if e.code >= 500:
                return ""
            return e.read().decode("utf-8", "replace")


def token_by_id(html, id_pattern):
    """{id: generated element token} for every tag whose id matches `id_pattern`.

    1.0.8 emits `<div class="m-div _e" id="x">` - class BEFORE id - where 1.0.7 emitted
    `<div id="x" class="M_EL4 M_EL_Div">`, so the token is read off the whole opening
    tag rather than assumed to follow the id. The token is the one class that opens
    with `_` (ElementTokenHelper); no user class may."""
    out = {}
    for tag in re.finditer(r"<[a-zA-Z][^>]*>", html):
        t = tag.group(0)
        i = re.search(r'\bid="(%s)"' % id_pattern, t)
        if not i:
            continue
        c = re.search(r'\bclass="([^"]*)"', t)
        tok = re.findall(r"(?:^|\s)(_[a-z0-9_-]+)(?=\s|$)", c.group(1)) if c else []
        if tok:
            out.setdefault(i.group(1), tok[0])
    return out


def document_styles(html, suffix=""):
    """{generated element class: {css property: value}} for one breakpoint's rules.

    `suffix` is the breakpoint's own key with the leading underscore dropped: "" is
    the base, "t" tablet, "m" mobile - the same spelling the three separate style
    blocks used before 1.0.9.

    1.0.9 merged those three blocks into ONE `mosaic-theme-document-styles-inline-css`
    with the breakpoints as `@media` blocks inside it, so a suffix is now a position
    in one stylesheet rather than a block id. The old ids are still read first, so
    the same tool measures a 1.0.8 site unchanged.

    The base is everything OUTSIDE any at-rule: scanning the whole block for `._x{...}`
    would read a tablet override as if it were the base, which is exactly the error
    the three-block layout made impossible.
    """
    old = re.search(
        r'<style id="mosaic-theme-block-editor-styles_%s-inline-css">(.*?)</style>'
        % re.escape(suffix), html, re.S)
    if old:
        css = old.group(1)
        inner = re.search(r"@media[^{]*\{(.*)\}\s*$", css, re.S)
        return _rules_of(inner.group(1) if inner else css)

    one = re.search(r'<style id="mosaic-theme-document-styles-inline-css">(.*?)</style>',
                    html, re.S)
    if not one:
        return None
    css = one.group(1)
    blocks = _at_rule_blocks(css)
    if suffix == "":
        outside = css
        for start, end, _head in blocks:
            outside = outside.replace(css[start:end], " ")
        return _rules_of(outside)
    # a breakpoint block is a max-width media query; they appear widest-first, the
    # order Mosaic emits them in, so "t" is the first and "m" the second
    media = [(s, e, h) for s, e, h in blocks if "max-width" in h]
    want = {"t": 0, "m": 1}.get(suffix)
    if want is None or want >= len(media):
        return None
    s, e, _h = media[want]
    body = css[css.index("{", s) + 1:e - 1]
    return _rules_of(body)


def _at_rule_blocks(css):
    """[(start, end, header)] for every top-level at-rule, found by brace depth."""
    out, i, n = [], 0, len(css)
    while True:
        at = css.find("@", i)
        if at < 0:
            return out
        brace = css.find("{", at)
        if brace < 0:
            return out
        depth, j = 0, brace
        while j < n:
            if css[j] == "{":
                depth += 1
            elif css[j] == "}":
                depth -= 1
                if depth == 0:
                    break
            j += 1
        out.append((at, j + 1, css[at:brace]))
        i = j + 1


def _rules_of(css):
    """{class: {prop: value}} from flat CSS, ignoring anything nested in an at-rule."""
    rules = {}
    for sel, decls in re.findall(r"([^{}]+)\{([^{}]*)\}", css):
        props = {}
        for decl in decls.split(";"):
            if ":" in decl:
                k, v = decl.split(":", 1)
                props[k.strip()] = v.strip()
        for one in sel.split(","):
            cls = re.match(r"^\.(_[a-z0-9_-]+)$", one.strip())
            if cls:
                rules.setdefault(cls.group(1), {}).update(props)
    return rules


def envelopes(doc):
    return {k: [[x["ID"], x["revision"]] for x in v] for k, v in doc.items()}


def exceptions_of(resp):
    """Mosaic returns validator rejections as HTTP 200 with an `exceptions` body."""
    if "_httperror" in resp:
        return "http%s: %s" % (resp["_httperror"], resp["_body"][:200])
    for holder in (resp, resp.get("response") or {}):
        if isinstance(holder, dict) and holder.get("exceptions"):
            return json.dumps(holder["exceptions"], ensure_ascii=False)[:300]
    return ""


def unwrap(resp, what):
    if "_httperror" in resp or "response" not in resp:
        sys.exit("%s failed: %s" % (what, json.dumps(resp)[:400]))
    return resp["response"]


def sweep_path(cfg):
    """The public URL the sweep master renders on. See "Which page it reads"."""
    return cfg.get("sweepPath", "?post_type=post")


def assert_probe_renders(client, cfg):
    """Commit a plain div and require it on the sweep page, then remove it.

    A div renders on any healthy page. If it does not show up, the page being read is
    not the one the sweep master renders on, and every row this run would write is
    a false COMMITTED - so stop before writing any."""
    master_id = cfg["masterID"]
    key = "node/master/%s" % master_id
    doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
    baseline_ids = {n["ID"] for n in doc[key]}
    attr, _nid, recs = probe_records("div", cfg["parentNodeID"], master_id)
    client.commit("masterDocumentInstance/%s" % master_id, envelopes(doc), {key: recs})
    try:
        html = client.page(sweep_path(cfg))
        if ('id="%s"' % attr) not in html:
            sys.exit("a plain div committed to the sweep master does not render on /%s - "
                     "that page is not the one the master renders on, so every row would "
                     "read COMMITTED. Set sweepPath in the config to a URL served by the "
                     "post archive (the default is ?post_type=post)." % sweep_path(cfg))
    finally:
        delete_subtree(client, master_id, baseline_ids, cfg["parentNodeID"])


def setup(client, cfg, config_path):
    """Create the master (which heals into a default node tree) and the template."""
    tei = unwrap(client.get("adminMasterEditorInstance"), "adminMasterEditorInstance")
    master_id = str(uuid.uuid4())
    resp = client.commit(
        "adminMasterEditorInstance",
        envelopes(tei),
        {
            "master": [
                {
                    "newRevisionRecord": {
                        "ID": master_id, "parentType": "", "parentID": "", "ordering": "a0",
                        "status": "publish", "revision": "", "version": "", "name": "Sweep Master",
                    },
                    "originalRevisionRecord": None,
                }
            ]
        },
    )
    err = exceptions_of(resp)
    if err:
        sys.exit("master commit rejected: %s" % err)

    # opening the document instance is what heals the default tree into existence
    doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
    nodes = doc["node/master/%s" % master_id]
    divs = sorted([n for n in nodes if n["type"] == "div"], key=lambda n: n["ordering"])
    if not divs:
        sys.exit("healed master has no div to hang probes on")
    parent = divs[0]["ID"]

    tei = unwrap(client.get("adminTemplateEditorInstance"), "adminTemplateEditorInstance")
    template_id = str(uuid.uuid4())
    resp = client.commit(
        "adminTemplateEditorInstance",
        envelopes(tei),
        {
            "template": [
                {
                    "newRevisionRecord": {
                        "ID": template_id, "parentType": "", "parentID": "", "ordering": "a0",
                        "status": "publish", "revision": "", "version": "", "name": "Sweep Home",
                        "masterID": master_id, "assign": "auto", "path": "archive-post.php",
                        "conditions": [],
                    },
                    "originalRevisionRecord": None,
                }
            ]
        },
    )
    err = exceptions_of(resp)
    if err:
        sys.exit("template commit rejected: %s" % err)

    cfg.update({"masterID": master_id, "templateID": template_id, "parentNodeID": parent})
    with open(config_path, "w", encoding="utf-8") as fh:
        json.dump(cfg, fh, indent=1)
    print("masterID=%s\ntemplateID=%s\nparentNodeID=%s" % (master_id, template_id, parent))

    html = client.page(sweep_path(cfg))
    print("baseline page: %d bytes%s" % (len(html), "" if len(html) >= MIN_HEALTHY_BYTES else "  <-- ALREADY BROKEN"))


def probe_records(node_type, parent_id, master_id):
    nid = str(uuid.uuid4())
    attr = "sweep-%s" % node_type
    base = {
        "parentType": "node", "parentID": parent_id, "ordering": "a0", "status": "publish",
        "revision": "", "version": "", "documentType": "master", "documentID": master_id,
    }
    recs = [{"newRevisionRecord": dict(base, ID=nid, type=node_type, data={"attrID": attr}),
             "originalRevisionRecord": None}]
    if node_type in TEXT_HOLDERS:
        recs.append(
            {"newRevisionRecord": dict(base, ID=str(uuid.uuid4()), parentID=nid, type="wysiwyg-text",
                                       data={"text": "%s_%s" % (MARKER, node_type)}),
             "originalRevisionRecord": None}
        )
    return attr, nid, recs


def delete_subtree(client, master_id, keep_ids, parent_id=None):
    """Remove the probe nodes, leaving the healed skeleton alone.

    Deleting "everything not in the original baseline" does not work: heal() rebuilds
    the master-root > document > body skeleton with FRESH ids whenever it decides one
    is missing, so a fixed baseline id set marks those rebuilds as garbage, deletes
    them, and heal makes new ones again - the document grows every round and later
    types get measured on a dirty tree. Scope the delete to the probe parent's own
    descendants instead, which the skeleton is never part of.
    """
    doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
    key = "node/master/%s" % master_id
    if parent_id:
        by_parent = {}
        for n in doc[key]:
            by_parent.setdefault(n["parentID"], []).append(n)
        doomed, stack = [], list(by_parent.get(parent_id, []))
        while stack:
            n = stack.pop()
            doomed.append(n)
            stack.extend(by_parent.get(n["ID"], []))
    else:
        doomed = [n for n in doc[key] if n["ID"] not in keep_ids]
    if not doomed:
        return
    # delete deepest-first so a parent never disappears out from under its child
    depth = {n["ID"]: n for n in doc[key]}

    def rank(n):
        d, cur = 0, n
        while cur and cur.get("parentType") == "node" and cur["parentID"] in depth:
            cur = depth[cur["parentID"]]
            d += 1
        return -d

    revisions = [
        {"newRevisionRecord": dict(n, status="delete"), "originalRevisionRecord": n}
        for n in sorted(doomed, key=rank)
    ]
    client.commit("masterDocumentInstance/%s" % master_id, envelopes(doc), {key: revisions})


def sweep(client, cfg, types, out_path):
    assert_probe_renders(client, cfg)
    master_id = cfg["masterID"]
    doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
    key = "node/master/%s" % master_id
    baseline_ids = {n["ID"] for n in doc[key]}

    path = sweep_path(cfg)
    baseline_html = client.page(path)
    if len(baseline_html) < MIN_HEALTHY_BYTES:
        sys.exit("baseline page is already broken (%d bytes); reset the theme first" % len(baseline_html))
    print("baseline: %d bytes, %d nodes\n" % (len(baseline_html), len(baseline_ids)))

    rows = []
    for node_type in types:
        doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
        attr, _nid, recs = probe_records(node_type, cfg["parentNodeID"], master_id)
        resp = client.commit("masterDocumentInstance/%s" % master_id, envelopes(doc), {key: recs})
        err = exceptions_of(resp)

        if err:
            # a 5xx is a PHP fatal on the server, not a graceful validator rejection -
            # the two say very different things about whether the type is usable
            code = resp.get("_httperror")
            outcome = "COMMIT_%d" % code if code and code >= 500 else "REJECTED"
            if code:
                err = "PHP fatal / gateway error during commit"
            tag, classes, echoed, size = "", "", "", ""
        else:
            html = client.page(path)
            size = len(html)
            if size < MIN_HEALTHY_BYTES:
                outcome, tag, classes, echoed = "BROKE_PAGE", "", "", ""
                err = html.strip()[:200]
            else:
                m = re.search(r'<([a-zA-Z0-9-]+)([^>]*\bid="%s"[^>]*)>' % re.escape(attr), html)
                if m:
                    outcome, tag = "RENDERED", m.group(1)
                    c = re.search(r'class="([^"]*)"', m.group(2))
                    classes = c.group(1) if c else ""
                else:
                    outcome, tag, classes = "COMMITTED", "", ""
                echoed = "yes" if ("%s_%s" % (MARKER, node_type)) in html else ""

        rows.append({"type": node_type, "outcome": outcome, "rendered_tag": tag,
                     "rendered_classes": classes, "text_echoed": echoed,
                     "page_bytes": size, "detail": err})
        print("%-40s %-11s %s" % (node_type, outcome, tag or err[:60]), flush=True)
        delete_subtree(client, master_id, baseline_ids, cfg["parentNodeID"])

    with open(out_path, "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)

    tally = {}
    for r in rows:
        tally[r["outcome"]] = tally.get(r["outcome"], 0) + 1
    print("\n" + "  ".join("%s=%d" % kv for kv in sorted(tally.items())) + "  -> %s" % out_path)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--config",
                    help="JSON with base/cookie/nonce; omit it and the MOSAIC_SITE_URL / MOSAIC_REST_COOKIE / MOSAIC_REST_NONCE environment variables supply them instead")
    ap.add_argument("--setup", action="store_true")
    ap.add_argument("--sweep", action="store_true")
    ap.add_argument("--types", help="comma-separated subset; overrides --edition")
    ap.add_argument("--edition", default="all", choices=["all", "free", "pro"],
                    help="which slice of node-types.csv to sweep (default: all)")
    ap.add_argument("--node-types-csv", default="../data/node-types.csv")
    ap.add_argument("--out", default="../data/node-verification.csv")
    a = ap.parse_args()

    cfg = mosaic_config.load(a.config)
    client = Client(cfg)
    if a.setup:
        setup(client, cfg, a.config)
    if a.sweep:
        if a.types:
            wanted = a.types.split(",")
        else:
            with open(a.node_types_csv, encoding="utf-8") as fh:
                wanted = [r["type"] for r in csv.DictReader(fh)
                          if a.edition in ("all", r["edition"])]
        sweep(client, cfg, wanted, a.out)
    if not (a.setup or a.sweep):
        ap.error("pass --setup and/or --sweep")
