"""Bounded decode of base64, hex and rot13 text, the Python twin of
decodedVariants in pipeline/lib/normalize-text.mjs.

Both sides take the same limits, find the same runs, decode with the same
hand-written decoders and return the same copies in the same order;
test/normalize-decode.test.mjs holds them to that on one set of samples.
The guard runs its credential-read rule over these copies, so a command that
hides `security find-generic-password -w` inside base64 is read as what it
decodes to. Stdlib only.
"""
import re
import string

DECODE_LIMITS = {
    "maxDepth": 2,
    "maxInputChars": 256 * 1024,
    "maxVariants": 32,
    "maxDecodedChars": 256 * 1024,
    "minBytes": 8,
    "minPrintable": 0.9,
}

B64_RUN = re.compile(r"[A-Za-z0-9+/_-]{16,}={0,2}")
HEX_RUN = re.compile(r"(?:[0-9a-fA-F]{2}){8,}")
_ALPHA = string.ascii_uppercase + string.ascii_lowercase + string.digits
_B64_VALUE = {c: i for i, c in enumerate(_ALPHA)}
_B64_VALUE.update({"+": 62, "-": 62, "/": 63, "_": 63})


def decode_base64(run):
    """Standard or URL-safe base64, padding optional, as one char per byte."""
    out, acc, bits = [], 0, 0
    for ch in run.rstrip("="):
        v = _B64_VALUE.get(ch)
        if v is None:
            return None
        acc = ((acc << 6) | v) & 0xFFFFFF
        bits += 6
        if bits >= 8:
            bits -= 8
            out.append(chr((acc >> bits) & 0xFF))
    return "".join(out)


def decode_hex(run):
    return "".join(chr(int(run[i:i + 2], 16)) for i in range(0, len(run) - 1, 2))


def rot13(text):
    out = []
    for ch in text:
        c = ord(ch)
        if 65 <= c <= 90:
            out.append(chr((c - 65 + 13) % 26 + 65))
        elif 97 <= c <= 122:
            out.append(chr((c - 97 + 13) % 26 + 97))
        else:
            out.append(ch)
    return "".join(out)


def _printable(data, min_bytes, min_printable):
    if len(data) < min_bytes:
        return False
    ok = sum(1 for ch in data if 0x20 <= ord(ch) <= 0x7E or ch in "\t\n\r")
    return ok / len(data) >= min_printable


def decoded_variants(text, limits=None):
    """[{"kind", "text"}] decoded copies of the runs inside text; see
    decodedVariants in normalize-text.mjs for the order and the limits."""
    lim = dict(DECODE_LIMITS)
    lim.update(limits or {})
    out, seen = [], set()
    budget = [lim["maxDecodedChars"]]

    def keep(kind, decoded, nxt):
        if len(out) >= lim["maxVariants"] or len(decoded) > budget[0] or decoded in seen:
            return
        seen.add(decoded)
        budget[0] -= len(decoded)
        out.append({"kind": kind, "text": decoded})
        nxt.append({"kind": kind, "text": decoded})

    frontier = [{"kind": "", "text": str(text or "")[: lim["maxInputChars"]]}]
    depth = 1
    while depth <= lim["maxDepth"] and frontier:
        nxt = []
        for item in frontier:
            prefix = item["kind"] + ">" if item["kind"] else ""
            for kind, pattern, decode, ratio in (
                ("base64", B64_RUN, decode_base64, 0.75),
                ("hex", HEX_RUN, decode_hex, 0.5),
            ):
                for m in pattern.finditer(item["text"]):
                    if len(out) >= lim["maxVariants"]:
                        break
                    if len(m.group(0)) * ratio > budget[0]:
                        continue
                    data = decode(m.group(0))
                    if data is not None and _printable(data, lim["minBytes"], lim["minPrintable"]):
                        keep(prefix + kind, data, nxt)
            if depth == 1 and re.search(r"[A-Za-z]", item["text"]):
                keep("rot13", rot13(item["text"]), [])
        frontier = nxt
        depth += 1
    return out
