"""Command-line boundary for the root ``jq`` executable."""

import json
import re
import sys
from collections.abc import Sequence
from typing import TextIO

from .builtins import InputInteger, _nondecnum, json_text
from .errors import CompileError, RuntimeError
from .evaluator import RuntimeContext, Environment, evaluate
from .parser import parse


_SPECIAL_JSON_NUMBERS = re.compile(r"(?<![A-Za-z0-9_])(-?(?:infinite|nan))(?![A-Za-z0-9_])", re.IGNORECASE)


def _parse_input(line: str) -> object:
    normalized = _SPECIAL_JSON_NUMBERS.sub(lambda match: "NaN" if match.group().lower().lstrip("-") == "nan" else ("-" if match.group().startswith("-") else "") + "Infinity", line)
    return json.loads(
        normalized,
        parse_int=lambda value: InputInteger(value),
        parse_constant=lambda value: float(value),
    )


def main(
    argv: Sequence[str] | None = None,
    stdin: TextIO | None = None,
    stdout: TextIO | None = None,
    stderr: TextIO | None = None,
) -> int:
    """Run jq and map compile/runtime failures to their specified statuses."""

    args = list(sys.argv[1:] if argv is None else argv)
    input_stream = sys.stdin if stdin is None else stdin
    output_stream = sys.stdout if stdout is None else stdout
    error_stream = sys.stderr if stderr is None else stderr
    try:
        # The corpus exercises structures around ten thousand levels deep.
        # jq's depth-limit corpus constructs values around ten thousand
        # levels deep; the renderer uses a few Python frames per level.
        sys.setrecursionlimit(100000)
        if len(args) != 2 or args[0] != "-c":
            raise CompileError("usage: jq -c PROGRAM")
        ast = parse(args[1])
        def records():
            for line in input_stream:
                # jq accepts an optional UTF-8 BOM at the beginning of an input record.
                yield _parse_input(line.removeprefix("\ufeff"))

        shared = RuntimeContext(iter(records()), stderr=error_stream)
        environment = Environment(runtime=shared)
        for value in shared.records:
            for result in evaluate(ast, value, environment):
                output_stream.write(json_text(result) + "\n")
        return 0
    except CompileError as exc:
        print(exc, file=error_stream)
        return 3
    except (RuntimeError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:
        print(exc, file=error_stream)
        return 5
