# Handler v3 of the block language: plain text. Written separately from the HTML handlers (v1, v2): it shares
# only the grammar of the language (validate) and renders the same documents as text for a terminal, a README
# or a messenger. No HTML is built here; the last lines only wrap the text so the demo page can show it.
# Embedded into a device registrar: no backslashes and no triple quotes in this file.
NL = chr(10)
T_LABELS = {
    "en": {"month": "per month", "year": "per year", "once": "one-time", "vat": "incl. 12% VAT", "faq": "Questions", "features": "What you get", "plans": "Plans"},
    "ru": {"month": "в месяц", "year": "в год", "once": "разово", "vat": "с НДС 12%", "faq": "Вопросы", "features": "Что вы получаете", "plans": "Тарифы"},
}
T_CODE = {"USD": "USD", "EUR": "EUR", "KZT": "KZT", "RUB": "RUB"}


def t_money(v, cur):
    num = str(int(v)) if float(v) == int(v) else "{:.2f}".format(v)
    return num + " " + T_CODE.get(cur, "")


def t_wrap(s, width=72):
    words, lines, line = str(s).split(), [], ""
    for w in words:
        if line and len(line) + 1 + len(w) > width:
            lines.append(line)
            line = w
        else:
            line = (line + " " + w) if line else w
    if line:
        lines.append(line)
    return NL.join(lines)


def render_text(block, law=None):
    L = T_LABELS["ru"] if law == "ru" else T_LABELS["en"]
    t = block["type"]
    out = []
    if t == "hero":
        out += [block["title"].upper(), "=" * min(72, len(block["title"]))]
        if block.get("text"):
            out += ["", t_wrap(block["text"])]
        if block.get("button"):
            out += ["", "[ " + block["button"] + " ]"]
    elif t == "features":
        out += [block.get("title") or L["features"], "-" * 24]
        for it in block["items"]:
            out.append("* " + it["title"] + (": " + it["text"] if it.get("text") else ""))
    elif t == "price":
        cur = block.get("currency", "USD")
        out += [block.get("title") or L["plans"], "-" * 24]
        for pl in block["plans"]:
            amount = pl["price"] * 1.12 if law == "vat" else pl["price"]
            line = pl["name"].ljust(12) + " " + t_money(amount, cur) + " " + L[pl.get("period", "month")]
            if law == "vat":
                line += " (" + L["vat"] + ")"
            out.append(line)
            for f in pl.get("features", []):
                out.append("    - " + f)
    elif t == "faq":
        out += [block.get("title") or L["faq"], "-" * 24]
        for it in block["items"]:
            out += ["Q: " + it["q"], t_wrap("A: " + it["a"]), ""]
    elif t == "quote":
        out.append("*" * int(block.get("rating", 5)) + " (" + str(int(block.get("rating", 5))) + "/5)")
        out.append(t_wrap(chr(8220) + block["text"] + chr(8221)))
        if block.get("author"):
            out.append("  -- " + block["author"] + (", " + block["role"] if block.get("role") else ""))
    elif t == "cta":
        out += [block["title"], "-" * 24]
        if block.get("text"):
            out.append(t_wrap(block["text"]))
        if block.get("button"):
            out += ["", "[ " + block["button"] + " ]"]
    elif t == "text":
        if block.get("title"):
            out += [block["title"], "-" * 24]
        out.append(t_wrap(block["text"]))
    return NL.join(out).rstrip()


T_CSS = "pre.b{margin:0;padding:18px 28px;font:14px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;color:#1A1A1A;background:#F7F6F1;border-bottom:1px dashed #C9C4B8;white-space:pre-wrap}"


def block(code = "", filtered_source_code = "", func_name = "", **extra):
    import json, platform, socket
    source = code or filtered_source_code or ""
    params = dict(extra)
    inner = extra.get("kwargs")
    if isinstance(inner, dict):
        params.update(inner)
    try:
        doc = json.loads(source)
    except Exception as err:
        return {"status": "rejected", "reason": "block is not valid JSON: " + str(err)[:120]}
    ok, reason = validate(doc)
    if not ok:
        return {"status": "rejected", "reason": reason}
    law = params.get("law") or None
    if law not in LAWS:
        law = None
    text = render_text(doc, law)
    return {"status": "success", "language": "block", "expert": func_name, "block_type": doc["type"], "text": text,
            "html": '<pre class="b ' + doc["type"] + ' v3">' + esc(text) + "</pre>", "css": T_CSS,
            "handler_version": 3, "handler_name": "plain text", "handler_sha": HANDLER_SHA, "law": law,
            "source_sha": source_sha(doc), "model_calls": 0, "host": socket.gethostname(), "os": platform.system() + " " + platform.machine()}
