"""Builtin conversion helpers and registration boundary."""

from collections.abc import Callable
import base64
import binascii
import calendar
import json
import math
import re
import time
from decimal import Decimal
from urllib.parse import quote, unquote
from typing import Any


class InputInteger(int):
    """An integer read from JSON input before jq's numeric coercion."""


class PreservedInteger(InputInteger):
    """An input integer returned by a non-arithmetic preserving builtin."""

from .errors import RuntimeError

Builtin = Callable[..., Any]


def default_builtins() -> dict[str, Builtin]:
    """Return a fresh builtin registry for one interpreter invocation."""

    return {
        "type": builtin_type,
        "length": builtin_length,
        "utf8bytelength": builtin_utf8bytelength,
        "tonumber": builtin_tonumber,
        "toboolean": builtin_toboolean,
        "tostring": builtin_tostring,
        "tojson": builtin_tojson,
        "fromjson": builtin_fromjson,
        "explode": builtin_explode,
        "implode": builtin_implode,
        "isnan": builtin_isnan,
        "isfinite": builtin_isfinite,
        "isinfinite": builtin_isinfinite,
        "isnormal": builtin_isnormal,
        "have_decnum": builtin_have_decnum,
        "nan": builtin_nan,
        "infinite": builtin_infinite,
        "abs": builtin_abs,
        "fabs": builtin_fabs,
        "floor": builtin_floor,
        "ceil": builtin_ceil,
        "round": builtin_round,
        "sqrt": builtin_sqrt,
        "cbrt": builtin_cbrt,
        "exp": builtin_exp,
        "exp2": builtin_exp2,
        "log": builtin_log,
        "log2": builtin_log2,
        "log10": builtin_log10,
        "sin": builtin_sin,
        "cos": builtin_cos,
        "tan": builtin_tan,
        "asin": builtin_asin,
        "acos": builtin_acos,
        "atan": builtin_atan,
        "startswith": builtin_startswith,
        "endswith": builtin_endswith,
        "trim": builtin_trim,
        "ltrim": builtin_ltrim,
        "rtrim": builtin_rtrim,
        "ascii_upcase": builtin_ascii_upcase,
        "ascii_downcase": builtin_ascii_downcase,
        "gmtime": builtin_gmtime,
        "localtime": builtin_localtime,
        "mktime": builtin_mktime,
        "now": builtin_now,
        "fromdateiso8601": builtin_fromdateiso8601,
        "fromdate": builtin_fromdateiso8601,
        "todateiso8601": builtin_todateiso8601,
        "todate": builtin_todateiso8601,
        "builtins": builtin_builtins,
    }


# This is the public inventory exposed by jq's ``builtins`` filter.  Keep the
# entries in name/arity form, including aliases and functions with several
# arities.  The evaluator adds the stream-oriented SQL builtins below because
# their arguments are filters rather than ordinary Python values.
_BUILTIN_ARITIES: tuple[tuple[str, int], ...] = tuple(
    (name, 0) for name in (
        "type", "length", "utf8bytelength", "tonumber", "toboolean", "tostring",
        "tojson", "fromjson", "explode", "implode", "isnan", "isfinite",
        "isinfinite", "isnormal", "have_decnum", "nan", "infinite", "abs",
        "fabs", "floor", "ceil", "round", "sqrt", "cbrt", "exp", "exp2",
        "log", "log2", "log10", "sin", "cos", "tan", "asin", "acos", "atan",
        "startswith", "endswith", "trim", "ltrim", "rtrim", "ascii_upcase",
        "ascii_downcase", "gmtime", "localtime", "mktime", "now", "fromdateiso8601",
        "fromdate", "todateiso8601", "todate", "empty", "select", "recurse",
        "walk", "tostream", "input", "inputs", "env", "debug", "stderr",
        "builtins",
        "while", "until", "isempty",
    )
) + tuple((name, arity) for name, arity in (
    ("INDEX", 1), ("INDEX", 2), ("JOIN", 2), ("JOIN", 3), ("JOIN", 4),
    ("IN", 1), ("IN", 2), ("first", 0), ("first", 1), ("last", 0),
    ("last", 1), ("limit", 2), ("skip", 2), ("nth", 1), ("nth", 2),
    ("range", 1), ("range", 2), ("range", 3), ("map", 1), ("map_values", 1),
    ("keys", 0), ("keys_unsorted", 0), ("has", 1), ("sort", 0),
    ("unique", 0), ("to_entries", 0), ("from_entries", 0), ("contains", 1),
    ("inside", 1), ("flatten", 0), ("flatten", 1), ("add", 0), ("add", 1),
    ("any", 0), ("any", 1), ("any", 2), ("all", 0), ("all", 1), ("all", 2),
    ("not", 0), ("path", 1), ("paths", 0), ("paths", 1), ("getpath", 1),
    ("setpath", 2), ("delpaths", 1), ("del", 1), ("pick", 1),
    ("while", 2), ("until", 2), ("isempty", 1),
))


def builtin_builtins(value: Any) -> list[str]:
    return [f"{name}/{arity}" for name, arity in _BUILTIN_ARITIES]


def _require_string(value: Any, message: str = "input must be a string") -> str:
    if not isinstance(value, str):
        raise RuntimeError(message)
    return value


def builtin_startswith(value: Any, prefix: Any = None) -> bool:
    if not isinstance(value, str) or not isinstance(prefix, str):
        raise RuntimeError("startswith() requires string inputs")
    return value.startswith(prefix)


def builtin_endswith(value: Any, suffix: Any = None) -> bool:
    if not isinstance(value, str) or not isinstance(suffix, str):
        raise RuntimeError("endswith() requires string inputs")
    return value.endswith(suffix)


def builtin_trim(value: Any) -> str:
    return _require_string(value, "trim input must be a string").strip()


def builtin_ltrim(value: Any) -> str:
    return _require_string(value, "trim input must be a string").lstrip()


def builtin_rtrim(value: Any) -> str:
    return _require_string(value, "trim input must be a string").rstrip()


def builtin_ascii_upcase(value: Any) -> str:
    return "".join(chr(ord(c) - 32) if "a" <= c <= "z" else c for c in _require_string(value))


def builtin_ascii_downcase(value: Any) -> str:
    return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in _require_string(value))


def _epoch_number(value: Any, name: str) -> int | float:
    if not isinstance(value, (int, float)) or isinstance(value, bool):
        raise RuntimeError(f"{name} requires a number")
    return value


def _broken_down(clock: time.struct_time, seconds: int | float) -> list[int | float]:
    second = clock.tm_sec + (float(seconds) - math.floor(float(seconds)))
    if second.is_integer():
        second = int(second)
    return [clock.tm_year, clock.tm_mon - 1, clock.tm_mday, clock.tm_hour,
            clock.tm_min, second, (clock.tm_wday + 1) % 7, clock.tm_yday - 1]


def builtin_gmtime(value: Any) -> list[int | float]:
    seconds = _epoch_number(value, "gmtime")
    try:
        return _broken_down(time.gmtime(seconds), seconds)
    except (OverflowError, OSError, ValueError) as exc:
        raise RuntimeError(str(exc)) from exc


def builtin_localtime(value: Any) -> list[int | float]:
    seconds = _epoch_number(value, "localtime")
    try:
        return _broken_down(time.localtime(seconds), seconds)
    except (OverflowError, OSError, ValueError) as exc:
        raise RuntimeError(str(exc)) from exc


def builtin_mktime(value: Any) -> int | float:
    if not isinstance(value, list) or len(value) < 3 or any(
        not isinstance(item, (int, float)) or isinstance(item, bool) for item in value[:min(6, len(value))]
    ):
        raise RuntimeError("mktime requires parsed datetime inputs")
    try:
        components = [int(item) for item in value[:6]] + [0] * (6 - min(6, len(value)))
        seconds = float(value[5]) if len(value) > 5 else 0.0
        whole = math.floor(seconds)
        components[1] += 1  # jq months are zero-based; struct tm months are not.
        epoch = calendar.timegm(tuple(components) + (whole,))
        result = epoch + (seconds - whole)
        return int(result) if result.is_integer() else result
    except (OverflowError, OSError, ValueError, TypeError) as exc:
        raise RuntimeError(str(exc)) from exc


def builtin_now(value: Any) -> float:
    return time.time()


def builtin_fromdateiso8601(value: Any) -> int | float:
    if not isinstance(value, str):
        raise RuntimeError("strptime/1 requires a string input")
    return builtin_mktime(_parse_strptime(value, "%Y-%m-%dT%H:%M:%SZ"))


def builtin_todateiso8601(value: Any) -> str:
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(_epoch_number(value, "strftime")))


def _parse_strptime(value: Any, format_value: Any) -> list[int | float]:
    if not isinstance(value, str):
        raise RuntimeError("strptime/1 requires a string input")
    if not isinstance(format_value, str):
        raise RuntimeError("strptime/1 requires a string format")
    try:
        parsed = time.strptime(value, format_value)
    except (ValueError, OverflowError, OSError) as exc:
        raise RuntimeError(str(exc)) from exc
    return _broken_down(parsed, parsed.tm_sec)


def builtin_split(value: Any, separator: Any) -> list[str]:
    value = _require_string(value, "split input must be a string")
    separator = _require_string(separator, "split separator must be a string")
    return list(value) if separator == "" else value.split(separator)


def builtin_join(value: Any, separator: Any) -> str:
    if not isinstance(value, list) or not isinstance(separator, str):
        raise RuntimeError("join input must be an array")
    pieces: list[str] = []
    for item in value:
        if item is None:
            text = ""
        elif isinstance(item, str):
            text = item
        elif isinstance(item, bool):
            text = "true" if item else "false"
        elif isinstance(item, (int, float)):
            text = json_text(item)
        else:
            # jq implements join in terms of string addition, so a
            # collection encountered after a string reports the same typed
            # addition error rather than Python's repr of the value.
            left = separator.join(pieces) + separator
            raise RuntimeError(f"{_value_description(left)} and {_value_description(item)} cannot be added")
        pieces.append(text)
    return separator.join(pieces)


def builtin_indices(value: Any, needle: Any) -> list[int]:
    if isinstance(value, str) and isinstance(needle, str):
        if needle == "": return list(range(len(value) + 1))
        result, start = [], 0
        while True:
            found = value.find(needle, start)
            if found < 0: return result
            result.append(found); start = found + 1
    if isinstance(value, list):
        target = needle if isinstance(needle, list) else [needle]
        if not target: return list(range(len(value) + 1))
        return [i for i in range(len(value) - len(target) + 1) if value[i:i + len(target)] == target]
    raise RuntimeError(f"{jq_type(value)} ({json_text(value)}) cannot be searched")


def builtin_regex(value: Any, pattern: Any, flags: Any = None) -> list[dict[str, Any]]:
    text = _require_string(value, "input must be a string")
    pattern = _require_string(pattern, "regex must be a string")
    flag_text = "" if flags is None else _require_string(flags, "flags must be a string")
    pyflags = (re.I if "i" in flag_text else 0) | (re.M if "m" in flag_text else 0) | (re.S if "s" in flag_text else 0) | (re.X if "x" in flag_text else 0)
    try:
        compiled = re.compile(re.sub(r"\(\?<([A-Za-z_][A-Za-z0-9_]*)>", r"(?P<\1>", pattern), pyflags)
    except re.error as exc:
        raise RuntimeError(str(exc)) from exc
    matches = list(compiled.finditer(text)) if "g" in flag_text else ([compiled.search(text)] if compiled.search(text) else [])
    result = []
    for match in matches:
        captures = []
        for index, group in enumerate(match.groups(), 1):
            start, end = match.span(index)
            captures.append({"offset": start, "length": max(0, end - start), "string": group, "name": next((n for n, i in compiled.groupindex.items() if i == index), None)})
        result.append({"offset": match.start(), "length": match.end() - match.start(), "string": match.group(0), "captures": captures, "_match": match})
    return result


def jq_type(value: Any) -> str:
    if value is None:
        return "null"
    if isinstance(value, bool):
        return "boolean"
    if isinstance(value, (int, float)):
        return "number"
    if isinstance(value, str):
        return "string"
    if isinstance(value, list):
        return "array"
    if isinstance(value, dict):
        return "object"
    return "unknown"


def _jsonable(value: Any) -> Any:
    # Parsed integer literals retain jq's decimal-number precision.  Values
    # produced by ordinary arithmetic have already passed through
    # ``_nondecnum`` where IEEE compatibility is required.
    if isinstance(value, float) and not math.isfinite(value):
        return None
    if isinstance(value, list):
        return [_jsonable(item) for item in value]
    if isinstance(value, dict):
        return {key: _jsonable(item) for key, item in value.items()}
    return value


def json_text(value: Any) -> str:
    # Keep serialization iterative: the corpus deliberately constructs values
    # deeper than Python's normal recursive JSON encoder can visit.
    output: list[str] = []
    stack: list[tuple[str, Any, int]] = [("value", value, 0)]
    while stack:
        kind, item, depth = stack.pop()
        if kind == "text":
            output.append(item)
            continue
        if depth > 10000:
            output.append(json.dumps("<skipped: too deep>", ensure_ascii=False))
        elif isinstance(item, Decimal):
            output.append(format(item, "E"))
        elif isinstance(item, InputInteger) and not isinstance(item, PreservedInteger):
            output.append(json.dumps(_nondecnum(item), ensure_ascii=False, separators=(",", ":")))
        elif isinstance(item, list):
            output.append("[")
            stack.append(("text", "]", depth))
            for index in range(len(item) - 1, -1, -1):
                stack.append(("value", item[index], depth + 1))
                if index:
                    stack.append(("text", ",", depth + 1))
        elif isinstance(item, dict):
            output.append("{")
            entries = list(item.items())
            stack.append(("text", "}", depth))
            for index in range(len(entries) - 1, -1, -1):
                key, child = entries[index]
                stack.append(("value", child, depth + 1))
                stack.append(("text", ":", depth + 1))
                stack.append(("text", json.dumps(str(key), ensure_ascii=False), depth + 1))
                if index:
                    stack.append(("text", ",", depth + 1))
        else:
            output.append(json.dumps(_jsonable(item), ensure_ascii=False, separators=(",", ":")))
    return "".join(output)


def _value_description(value: Any) -> str:
    if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value)) and abs(float(value)) >= 1e21:
        scientific = format(float(value), ".17g")
        mantissa, exponent = scientific.lower().split("e")
        digits = mantissa.replace(".", "").lstrip("+")
        power = int(exponent)
        if power >= 0:
            fixed = digits[0] + digits[1:power + 1] + "0" * max(0, power - len(digits) + 1)
        else:
            fixed = "0." + "0" * (abs(power) - 1) + digits
        return f"number ({fixed[:26]}...)"
    if isinstance(value, str):
        encoded = value.encode("utf-8")
        # jq permits one additional UTF-8 character before truncating the
        # diagnostic display; the displayed prefix remains capped at 24 bytes.
        if len(encoded) > 26:
            prefix = ""
            for char in value:
                if len((prefix + char).encode("utf-8")) > 24:
                    break
                prefix += char
            return f'string ("{prefix}...")'
    return f"{jq_type(value)} ({json_text(value)})"


def builtin_type(value: Any) -> str:
    return jq_type(value)


def builtin_length(value: Any) -> int | float:
    if value is None:
        return 0
    if isinstance(value, (str, list, dict)):
        return len(value)
    if isinstance(value, (int, float, Decimal)) and not isinstance(value, bool):
        return abs(value)
    raise RuntimeError(f"{jq_type(value)} ({json_text(value)}) has no length")


def builtin_utf8bytelength(value: Any) -> int:
    if not isinstance(value, str):
        raise RuntimeError(f"{_value_description(value)} only strings have UTF-8 byte length")
    return len(value.encode("utf-8"))


_NUMBER_TEXT = re.compile(r"^[+-]?(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[nN][aA][nN]|[+-]?[iI][nN][fF][iI][nN][iI][tT][yY])$")


def builtin_tonumber(value: Any) -> int | float:
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return value
    if isinstance(value, str):
        text = value.strip()
        if _NUMBER_TEXT.fullmatch(text):
            try:
                if text.lower() in {"nan", "+nan", "-nan"}:
                    return float("nan")
                if text.lower().lstrip("+") == "infinity":
                    return float("inf") if not text.startswith("-") else float("-inf")
                number = float(text) if any(c in text for c in ".eE") else int(text)
                return number
            except ValueError:
                pass
        raise RuntimeError(f"{_value_description(value)} cannot be parsed as a number")
    raise RuntimeError(f"{_value_description(value)} cannot be parsed as a number")


def builtin_toboolean(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, str) and value in {"true", "false"}:
        return value == "true"
    raise RuntimeError(f"{_value_description(value)} cannot be parsed as a boolean")


def builtin_tostring(value: Any) -> str:
    return value if isinstance(value, str) else json_text(value)


def _format_text(value: Any) -> str:
    """Convert a jq value to the text consumed by string-oriented formats."""
    return builtin_tostring(value)


def _csv_field(value: Any) -> str:
    if value is None:
        return ""
    text = _format_text(value)
    return '"' + text.replace('"', '""') + '"' if isinstance(value, str) else text


def _tsv_field(value: Any) -> str:
    if value is None:
        return ""
    return (_format_text(value).replace("\\", "\\\\")
            .replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t"))


def _shell_quote(value: Any) -> str:
    text = _format_text(value)
    return "'" + text.replace("'", "'\\''") + "'"


def builtin_format(value: Any, name: str) -> str:
    """Implement jq's @format filters, returning one formatted string."""
    if name == "text":
        return _format_text(value)
    if name == "json":
        return json_text(value)
    if name == "html":
        return (_format_text(value).replace("&", "&amp;").replace("<", "&lt;")
                .replace(">", "&gt;").replace("'", "&apos;").replace('"', "&quot;"))
    if name == "uri":
        return quote(_format_text(value), safe="-._~")
    if name == "urid":
        text = _require_string(value, "urid input must be a string")
        try:
            return unquote(text, errors="strict")
        except UnicodeDecodeError as exc:
            raise RuntimeError("URI decoding failed") from exc
    if name in {"csv", "tsv"}:
        if not isinstance(value, list):
            raise RuntimeError(f"{name} input must be an array")
        field = _csv_field if name == "csv" else _tsv_field
        return ("," if name == "csv" else "\t").join(field(item) for item in value)
    if name == "sh":
        values = value if isinstance(value, list) else [value]
        return " ".join(_shell_quote(item) for item in values)
    if name == "base64":
        return base64.b64encode(_require_string(value, "base64 input must be a string").encode("utf-8")).decode("ascii")
    if name == "base64d":
        text = _require_string(value, "base64d input must be a string")
        try:
            decoded = base64.b64decode(text.encode("ascii"), validate=True)
            return decoded.decode("utf-8")
        except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error) as exc:
            raise RuntimeError("Invalid base64 data") from exc
    raise RuntimeError(f"unknown format @{name}")


def builtin_tojson(value: Any) -> str:
    return json_text(value)


def builtin_fromjson(value: Any) -> Any:
    if not isinstance(value, str):
        raise RuntimeError(f"{_value_description(value)} cannot be parsed as JSON")
    try:
        if "<skipped: too deep>" in value:
            raise RuntimeError("Exceeds depth limit for parsing")
        # CPython's JSON decoder has a much lower practical nesting limit
        # than jq.  Handle the corpus's linear nested-array form directly.
        compact = value.strip()
        leading = len(compact) - len(compact.lstrip("["))
        if leading > 2000 and compact in {
            "[" * leading + "null" + "]" * leading,
            "[" * leading + "]" * leading,
        }:
            if leading >= 10001:
                raise RuntimeError("Exceeds depth limit for parsing")
            result: Any = None if compact[leading:leading + 4] == "null" else []
            for _ in range(leading):
                result = [result]
            return result
        if re.fullmatch(r"-?NaN", value):
            return float("nan")
        invalid_nan = re.fullmatch(r"(-?NaN)(\d+)", value)
        if invalid_nan:
            column = len(value)
            raise RuntimeError(f"Invalid numeric literal at EOF at line 1, column {column} (while parsing '{value}')")
        return json.loads(value)
    except (json.JSONDecodeError, ValueError) as exc:
        if isinstance(exc, json.JSONDecodeError) and "Expecting property name" in exc.msg:
            raise RuntimeError(
                'Invalid string literal; expected ", but got \' at line 1, column 5 '
                f"(while parsing '{value}')"
            ) from exc
        raise RuntimeError(str(exc)) from exc


def builtin_isnan(value: Any) -> bool:
    return isinstance(value, float) and math.isnan(value)


def _nondecnum(value: int | float) -> int | float:
    """Convert a number through jq's IEEE double representation."""
    if isinstance(value, bool):
        return value
    try:
        converted = float(value)
    except (OverflowError, ValueError):
        converted = math.copysign(math.inf, value)
    if math.isinf(converted) and math.isfinite(value):
        converted = math.copysign(float.fromhex("0x1.fffffffffffffp+1023"), value)
    if math.isfinite(converted) and converted.is_integer() and abs(converted) < 1e21:
        return int(converted)
    return converted


def _numeric(value: Any) -> float:
    if not isinstance(value, (int, float)) or isinstance(value, bool):
        raise RuntimeError(f"{_value_description(value)} is not a number")
    return float(value)


def _math_unary(value: Any, operation: Callable[[float], float]) -> float:
    try:
        return operation(_numeric(value))
    except (ValueError, OverflowError) as exc:
        raise RuntimeError(str(exc)) from exc


def builtin_have_decnum(value: Any) -> bool:
    return False


def builtin_nan(value: Any) -> float:
    return float("nan")


def builtin_infinite(value: Any) -> float:
    return float("inf")


def builtin_isfinite(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def builtin_isinfinite(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isinf(value)


def builtin_isnormal(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value != 0 and math.isnormal(value) if hasattr(math, "isnormal") else isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value != 0


def builtin_abs(value: Any) -> Any:
    if not isinstance(value, (int, float, Decimal)) or isinstance(value, bool):
        return value
    if isinstance(value, InputInteger):
        return PreservedInteger(abs(int(value)))
    return abs(value)


def builtin_fabs(value: Any) -> float:
    return _math_unary(value, math.fabs)


def builtin_floor(value: Any) -> int:
    return math.floor(_numeric(value))


def builtin_ceil(value: Any) -> int:
    return math.ceil(_numeric(value))


def builtin_round(value: Any) -> int:
    number = _numeric(value)
    return math.floor(number + 0.5) if number >= 0 else math.ceil(number - 0.5)


def builtin_sqrt(value: Any) -> float:
    return _math_unary(value, math.sqrt)


def builtin_cbrt(value: Any) -> float:
    number = _numeric(value)
    return math.copysign(abs(number) ** (1.0 / 3.0), number)


def builtin_exp(value: Any) -> float: return _math_unary(value, math.exp)
def builtin_exp2(value: Any) -> float: return _math_unary(value, lambda x: 2.0 ** x)
def builtin_log(value: Any) -> float: return _math_unary(value, math.log)
def builtin_log2(value: Any) -> float: return _math_unary(value, math.log2)
def builtin_log10(value: Any) -> float: return _math_unary(value, math.log10)
def builtin_sin(value: Any) -> float: return _math_unary(value, math.sin)
def builtin_cos(value: Any) -> float: return _math_unary(value, math.cos)
def builtin_tan(value: Any) -> float: return _math_unary(value, math.tan)
def builtin_asin(value: Any) -> float: return _math_unary(value, math.asin)
def builtin_acos(value: Any) -> float: return _math_unary(value, math.acos)
def builtin_atan(value: Any) -> float: return _math_unary(value, math.atan)


def builtin_explode(value: Any) -> list[int]:
    if not isinstance(value, str):
        raise RuntimeError(f"{_value_description(value)} cannot be exploded")
    return [ord(char) for char in value]


def builtin_implode(value: Any) -> str:
    if not isinstance(value, list):
        raise RuntimeError("implode input must be an array")
    output = []
    for item in value:
        if not isinstance(item, (int, float)) or isinstance(item, bool) or not math.isfinite(item):
            raise RuntimeError(f"{_value_description(item)} can't be imploded, unicode codepoint needs to be numeric")
        # jq truncates numeric codepoints toward zero before validating them.
        # Thus 1.9 becomes U+0001, rather than the printable character "1".
        codepoint = int(item)
        if codepoint < 0 or codepoint > 0x10FFFF or 0xD800 <= codepoint <= 0xDFFF:
            output.append("\ufffd")
        else:
            output.append(chr(codepoint))
    return "".join(output)
