"""block: a tiny language for the blocks of a small website.

A block is a JSON document with one of seven types and plain-text fields. No markup, no scripts, no links
can be expressed: the handler escapes every string, so a visitor can add blocks to a live site safely.
Pure Python, standard library only, no backslashes (the source is embedded into device handlers).

  {"type": "hero", "title": "...", "text": "...", "button": "..."}
  {"type": "features", "title": "...", "items": [{"title": "...", "text": "..."}]}        1..4 items
  {"type": "price", "title": "...", "currency": "USD|EUR|KZT|RUB", "plans": [{"name", "price": number, "period": "month|year|once", "features": ["..."]}]}   1..3 plans
  {"type": "faq", "title": "...", "items": [{"q": "...", "a": "..."}]}                     1..5 items
  {"type": "quote", "text": "...", "author": "...", "role": "...", "rating": 1..5}
  {"type": "cta", "title": "...", "text": "...", "button": "..."}
  {"type": "text", "title": "...", "text": "..."}
Rendering belongs to the handler on the device: version 1 is editorial, version 2 is compact dark.
Laws (a run parameter): "vat" shows prices with 12% VAT; "ru" puts interface labels in Russian.
"""
import hashlib
import json

TYPES = ("hero", "features", "price", "faq", "quote", "cta", "text")
FIELDS = {
    "hero": {"title": 80, "text": 240, "button": 40},
    "features": {"title": 80, "items": None},
    "price": {"title": 80, "currency": 3, "plans": None},
    "faq": {"title": 80, "items": None},
    "quote": {"text": 300, "author": 60, "role": 60, "rating": None},
    "cta": {"title": 80, "text": 200, "button": 40},
    "text": {"title": 80, "text": 600},
}
REQUIRED = {"hero": ("title",), "features": ("items",), "price": ("plans",), "faq": ("items",), "quote": ("text",), "cta": ("title",), "text": ("text",)}
CURRENCIES = ("USD", "EUR", "KZT", "RUB")
PERIODS = ("month", "year", "once")
LAWS = ("vat", "ru")
VAT = 0.12


def _s(v, n):
    return isinstance(v, str) and 0 < len(v.strip()) <= n


def validate(block):
    if not isinstance(block, dict):
        return False, "a block must be an object"
    t = block.get("type")
    if t not in TYPES:
        return False, "type must be one of " + ", ".join(TYPES)
    allowed = FIELDS[t]
    for k in block:
        if k != "type" and k not in allowed:
            return False, "'%s' is not a word in block type %s" % (k, t)
    for k in REQUIRED[t]:
        if k not in block:
            return False, "block type %s needs '%s'" % (t, k)
    for k, n in allowed.items():
        if k in block and n is not None and not _s(block[k], n):
            return False, "'%s' must be text up to %d characters" % (k, n)
    if t == "features":
        items = block.get("items")
        if not isinstance(items, list) or not 1 <= len(items) <= 4:
            return False, "features needs 1 to 4 items"
        for i, it in enumerate(items):
            if not isinstance(it, dict) or set(it) - {"title", "text"} or not _s(it.get("title"), 60) or not _s(it.get("text", "x"), 160):
                return False, "item %d: title up to 60 and text up to 160 characters, nothing else" % (i + 1)
    if t == "faq":
        items = block.get("items")
        if not isinstance(items, list) or not 1 <= len(items) <= 5:
            return False, "faq needs 1 to 5 items"
        for i, it in enumerate(items):
            if not isinstance(it, dict) or set(it) - {"q", "a"} or not _s(it.get("q"), 120) or not _s(it.get("a"), 300):
                return False, "item %d: q up to 120 and a up to 300 characters, nothing else" % (i + 1)
    if t == "price":
        if block.get("currency", "USD") not in CURRENCIES:
            return False, "currency must be one of " + ", ".join(CURRENCIES)
        plans = block.get("plans")
        if not isinstance(plans, list) or not 1 <= len(plans) <= 3:
            return False, "price needs 1 to 3 plans"
        for i, pl in enumerate(plans):
            if not isinstance(pl, dict) or set(pl) - {"name", "price", "period", "features"}:
                return False, "plan %d: name, price, period, features only" % (i + 1)
            if not _s(pl.get("name"), 40):
                return False, "plan %d needs a name" % (i + 1)
            if not isinstance(pl.get("price"), (int, float)) or isinstance(pl.get("price"), bool) or not 0 <= pl["price"] <= 1000000:
                return False, "plan %d: price must be a number from 0 to 1000000" % (i + 1)
            if pl.get("period", "month") not in PERIODS:
                return False, "plan %d: period must be month, year or once" % (i + 1)
            f = pl.get("features", [])
            if not isinstance(f, list) or len(f) > 6 or not all(_s(x, 80) for x in f):
                return False, "plan %d: up to 6 features, each text up to 80 characters" % (i + 1)
    if t == "quote":
        r = block.get("rating", 5)
        if not isinstance(r, int) or isinstance(r, bool) or not 1 <= r <= 5:
            return False, "rating must be a whole number from 1 to 5"
    return True, "ok"


def esc(s):
    s = str(s)
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


def source_sha(block):
    return hashlib.sha256(json.dumps(block, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()


LABELS = {
    "en": {"per_month": "/ month", "per_year": "/ year", "once": "once", "vat": "incl. 12% VAT", "faq": "Questions", "features": "What you get", "plans": "Plans", "said": "said"},
    "ru": {"per_month": "/ месяц", "per_year": "/ год", "once": "разово", "vat": "с НДС 12%", "faq": "Вопросы", "features": "Что вы получаете", "plans": "Тарифы", "said": "сказал(а)"},
}
SYMBOL = {"USD": "$", "EUR": "€", "KZT": "₸", "RUB": "₽"}


def money(v, cur):
    if float(v) == int(v):
        num = "{:,}".format(int(v)).replace(",", " ")
    else:
        num = "{:,.2f}".format(v).replace(",", " ")
    return SYMBOL.get(cur, "") + num


def render(block, version, law=None):
    """Returns an HTML fragment. Every string from the block passes through esc(). The look is the handler's."""
    L = LABELS["ru"] if law == "ru" else LABELS["en"]
    t = block["type"]
    v = "v%d" % version
    out = []
    if t == "hero":
        out.append('<section class="b hero ' + v + '"><h1>' + esc(block["title"]) + "</h1>")
        if block.get("text"):
            out.append("<p>" + esc(block["text"]) + "</p>")
        if block.get("button"):
            out.append('<span class="btn">' + esc(block["button"]) + "</span>")
        out.append("</section>")
    elif t == "features":
        out.append('<section class="b features ' + v + '"><h2>' + esc(block.get("title") or L["features"]) + '</h2><div class="grid">')
        for it in block["items"]:
            out.append('<div class="card"><h3>' + esc(it["title"]) + "</h3><p>" + esc(it.get("text", "")) + "</p></div>")
        out.append("</div></section>")
    elif t == "price":
        cur = block.get("currency", "USD")
        out.append('<section class="b price ' + v + '"><h2>' + esc(block.get("title") or L["plans"]) + '</h2><div class="grid">')
        for pl in block["plans"]:
            amount = pl["price"] * (1 + VAT) if law == "vat" else pl["price"]
            per = {"month": L["per_month"], "year": L["per_year"], "once": L["once"]}[pl.get("period", "month")]
            out.append('<div class="card"><h3>' + esc(pl["name"]) + '</h3><div class="amount">' + esc(money(amount, cur)) + ' <small>' + per + "</small></div>")
            if law == "vat":
                out.append('<div class="vat">' + L["vat"] + "</div>")
            if pl.get("features"):
                out.append("<ul>" + "".join("<li>" + esc(f) + "</li>" for f in pl["features"]) + "</ul>")
            out.append("</div>")
        out.append("</div></section>")
    elif t == "faq":
        out.append('<section class="b faq ' + v + '"><h2>' + esc(block.get("title") or L["faq"]) + "</h2>")
        for it in block["items"]:
            out.append('<div class="qa"><h3>' + esc(it["q"]) + "</h3><p>" + esc(it["a"]) + "</p></div>")
        out.append("</section>")
    elif t == "quote":
        stars = "★" * int(block.get("rating", 5)) + "☆" * (5 - int(block.get("rating", 5)))
        out.append('<section class="b quote ' + v + '"><div class="stars">' + stars + "</div><blockquote>" + esc(block["text"]) + "</blockquote>")
        if block.get("author"):
            out.append('<div class="who">' + esc(block["author"]) + (", " + esc(block["role"]) if block.get("role") else "") + "</div>")
        out.append("</section>")
    elif t == "cta":
        out.append('<section class="b cta ' + v + '"><h2>' + esc(block["title"]) + "</h2>")
        if block.get("text"):
            out.append("<p>" + esc(block["text"]) + "</p>")
        if block.get("button"):
            out.append('<span class="btn">' + esc(block["button"]) + "</span>")
        out.append("</section>")
    elif t == "text":
        out.append('<section class="b text ' + v + '">' + ("<h2>" + esc(block["title"]) + "</h2>" if block.get("title") else "") + "<p>" + esc(block["text"]) + "</p></section>")
    return "".join(out)


CSS = {
    1: """
.b{font-family:Georgia,'Times New Roman',serif;color:#1A1A1A;background:#FBFAF6;padding:56px 64px;border-bottom:1px solid #E6E2DA;line-height:1.5}
.b h1{font-size:44px;font-weight:400;letter-spacing:-.01em;margin:0 0 14px;max-width:26ch}.b h2{font-size:30px;font-weight:400;margin:0 0 20px}.b h3{font-size:19px;font-weight:600;margin:0 0 6px}
.b p{font-size:17px;margin:0 0 12px;max-width:60ch;color:#3A3631}.b .btn{display:inline-block;border:1px solid #1A1A1A;padding:10px 22px;border-radius:2px;font-size:15px;letter-spacing:.04em;text-transform:uppercase}
.b .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:24px}.b .card{border-top:2px solid #1A1A1A;padding-top:14px}
.b .amount{font-size:30px;margin:8px 0}.b .amount small{font-size:14px;color:#7A756D}.b .vat{font-size:13px;color:#7A756D;margin-bottom:8px}.b ul{padding-left:18px;margin:8px 0 0;font-size:15px}
.b.quote blockquote{font-size:24px;font-style:italic;margin:0 0 10px;max-width:50ch}.b .stars{color:#C57E33;letter-spacing:2px;margin-bottom:8px}.b .who{font-size:15px;color:#7A756D}
.b.cta{background:#1A1A1A;color:#FBFAF6}.b.cta p{color:#D8D3C8}.b.cta .btn{border-color:#FBFAF6}.b.faq .qa{border-top:1px solid #E6E2DA;padding:12px 0}
""",
    2: """
.b{font-family:'DM Sans',Inter,system-ui,sans-serif;color:#F5F3EE;background:#0F0E0C;padding:36px 40px;border-bottom:1px solid rgba(255,255,255,.08);line-height:1.45}
.b h1{font-size:40px;font-weight:700;letter-spacing:-.03em;margin:0 0 10px}.b h2{font-size:22px;font-weight:600;letter-spacing:-.01em;margin:0 0 16px;color:#D4944A;text-transform:uppercase;font-size:14px;letter-spacing:.18em}
.b h3{font-size:17px;font-weight:600;margin:0 0 4px}.b p{font-size:15px;margin:0 0 10px;color:#BDB8B0;max-width:62ch}
.b .btn{display:inline-block;background:#D4944A;color:#0F0E0C;padding:10px 20px;border-radius:999px;font-size:14px;font-weight:600}
.b .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}.b .card{background:#181614;border:1px solid rgba(255,255,255,.08);border-radius:14px;padding:16px}
.b .amount{font-size:26px;font-weight:700;margin:6px 0}.b .amount small{font-size:12px;color:#9C978F;font-weight:400}.b .vat{font-size:12px;color:#9C978F;margin-bottom:6px}.b ul{padding-left:16px;margin:6px 0 0;font-size:14px;color:#BDB8B0}
.b.quote blockquote{font-size:20px;margin:0 0 8px;max-width:56ch}.b .stars{color:#D4944A;letter-spacing:2px;margin-bottom:6px}.b .who{font-size:13px;color:#9C978F}
.b.cta{background:#D4944A;color:#0F0E0C}.b.cta h2{color:#0F0E0C}.b.cta p{color:#3A2A17}.b.cta .btn{background:#0F0E0C;color:#F5F3EE}.b.faq .qa{padding:10px 0;border-top:1px solid rgba(255,255,255,.08)}
""",
}
NAMES = {1: "editorial", 2: "compact dark"}


def check_block(block):
    ok, reason = validate(block)
    if not ok:
        return False, {"grammar": reason}
    report = {"grammar": "ok", "renders": []}
    for version in (1, 2):
        for law in (None, "vat", "ru"):
            html = render(block, version, law)
            report["renders"].append({"version": version, "law": law, "bytes": len(html), "ok": "<script" not in html.lower()})
    return True, report


if __name__ == "__main__":
    b = {"type": "price", "title": "Plans", "currency": "USD", "plans": [{"name": "Team", "price": 49, "period": "month", "features": ["5 cabinets", "<b>bold</b> attempt"]}]}
    print(validate(b)); print(render(b, 1, "vat")[:300]); print(render(b, 2, "ru")[:200])
    print(validate({"type": "hero", "title": "x", "onclick": "alert(1)"}))
