import json
import os
import sys
import threading
import time
import uuid

SENTINEL = "##UMAI:"
SEPARATOR = "##"
JSONRPC_VERSION = "2.0"
TOKEN_ENV = "UMAI_SCRIPT_TOKEN"  # nosec B105 - a variable name, not a credential.
DEFAULT_TIMEOUT_SECONDS = 30
# Answers whose `result` was never called, or was called after its timeout, are held for a later
# collection. Past this many the oldest is dropped, so a long-lived script cannot grow forever.
MAX_UNCOLLECTED_ANSWERS = 256


def is_available():
    """True when the engine started this script and is listening for its requests."""
    return bool(os.environ.get(TOKEN_ENV))


def _scope(source):
    """The `source` member of a request's params, omitted when the caller named no source."""
    return {} if source is None else {"source": source}


def _bound(held):
    """Drop the oldest entries until `held` keeps no more than MAX_UNCOLLECTED_ANSWERS."""
    while len(held) > MAX_UNCOLLECTED_ANSWERS:
        held.pop(next(iter(held)))


class UmaiScriptProtocolError(Exception):
    """The engine refused a request; `code` is its JSON-RPC error code and `message` its text.

    Branch on `code`: -32601 is a method this engine does not serve, -32602 params it would not
    take, -32001 a variable it could not resolve.
    """

    def __init__(self, code, message, request_id):
        super().__init__(f"The engine refused request '{request_id}': {message} (code {code}).")
        self.code = code
        self.message = message
        self.request_id = request_id


def _refusal(response, request_id):
    error = response.get("error") or {}
    return UmaiScriptProtocolError(error.get("code"), error.get("message"), request_id)


class UmaiScript:
    """The engine's JSON-RPC 2.0 methods, called from the script the engine is running.

    `call` sends any method name with any params, so a method a later engine adds needs no change
    here; `discover` lists what the engine on the other end actually serves, and `get_variable`
    and `set_variable` are sugar over `call` for the two methods every engine serves. `send` and
    `result` are the same exchange split in two, so several requests can be outstanding at once
    and be collected in any order. Waiting is always bounded: an answer that never arrives raises
    rather than blocking for the rest of the run. `print` is untouched and stays the script's own
    output.

    Raises:
        RuntimeError: TOKEN_ENV is unset, so no engine is listening to this script.
    """

    def __init__(self, token=None, stdin=None, stdout=None, timeout=DEFAULT_TIMEOUT_SECONDS):
        self.token = token or os.environ.get(TOKEN_ENV)
        if not self.token:
            raise RuntimeError(
                f"'{TOKEN_ENV}' is not set: this script was not started by the UMAI engine."
            )
        self._prefix = SENTINEL + self.token + SEPARATOR
        self._stdin = stdin if stdin is not None else sys.stdin
        self._stdout = stdout if stdout is not None else sys.stdout
        self._timeout = timeout
        self._arrivals = threading.Condition()
        self._answered = {}
        self._outstanding = {}
        self._rejections = 0
        self._rejected = None
        self._closed = False
        self._reader = threading.Thread(target=self._read_responses, daemon=True)
        self._reader.start()

    def call(self, method, params=None, timeout=None):
        """The engine's result for `method`, called with `params` and waited for.

        Any method name reaches the engine as it stands, so a method this client has never heard
        of is served if the engine serves it and refused with -32601 if it does not. `timeout` is
        this call's own wait in seconds, and falls back to the client's when it is not given.

        Raises:
            UmaiScriptProtocolError: the engine refused the request.
            TimeoutError: no answer arrived in time.
            ConnectionError: the engine closed this script's input without answering.
        """
        return self.result(self.send(method, params), timeout)

    def discover(self, timeout=None):
        """Every method this engine serves, each with a description and the params it takes."""
        return self.call("rpc.discover", timeout=timeout)

    def get_variable(self, name, source=None, timeout=None):
        """The engine's value for `name`, resolved within `source` when one is given.

        A name alone can match a variable in more than one source, and then which one answers is
        the engine's caller's choice; naming the source picks the variable out.
        """
        return self.call("GET_VARIABLE", {"name": name, **_scope(source)}, timeout)

    def set_variable(self, name, value, source=None, timeout=None):
        """Write `value` to `name` in `source`, returning what the engine answers.

        `source` scopes the write exactly as it scopes a read.
        """
        return self.call("SET_VARIABLE", {"name": name, "value": value, **_scope(source)}, timeout)

    def send(self, method, params=None):
        """Send one request and return its id, leaving its answer for `result` to collect."""
        request_id = uuid.uuid4().hex
        request = {"jsonrpc": JSONRPC_VERSION, "method": method, "id": request_id}
        if params is not None:
            request["params"] = params
        with self._arrivals:
            self._outstanding[request_id] = self._rejections
            _bound(self._outstanding)
        self._stdout.write(self._prefix + json.dumps(request) + "\n")
        self._stdout.flush()
        return request_id

    def result(self, request_id, timeout=None):
        """The result the engine answered `request_id` with, waiting for it if it has not arrived.

        An answer to another outstanding request is held for that request's own `result` call. An
        error the engine could not attribute to any request fails every request outstanding when
        it arrived, this one included. `timeout` is this call's own wait in seconds, and falls back
        to the client's when it is not given.

        Raises:
            UmaiScriptProtocolError: the engine refused the request, or refused something this
                script sent without saying which request it was refusing.
            TimeoutError: no answer arrived in time.
            ConnectionError: the engine closed this script's input without answering.
        """
        deadline = time.monotonic() + (self._timeout if timeout is None else timeout)
        with self._arrivals:
            rejections = self._outstanding.pop(request_id, self._rejections)
            while request_id not in self._answered:
                if rejections < self._rejections:
                    raise _refusal(self._rejected, request_id)
                if self._closed:
                    raise ConnectionError(
                        f"The engine closed this script's input before answering '{request_id}'."
                    )
                if not self._arrivals.wait(max(deadline - time.monotonic(), 0)):
                    raise TimeoutError(
                        f"The engine did not answer request '{request_id}' in time."
                    )
            response = self._answered.pop(request_id)
        if "error" in response:
            raise _refusal(response, request_id)
        return response.get("result")

    def _deliver(self, response):
        with self._arrivals:
            if response.get("id") is None:
                # The engine could not read the id of whatever it is refusing, so nothing here can
                # match this answer to a request: every outstanding request fails on it instead.
                self._rejections += 1
                self._rejected = response
            else:
                self._answered[response["id"]] = response
                _bound(self._answered)
            self._arrivals.notify_all()

    def _read_responses(self):
        try:
            for line in self._stdin:
                if not line.startswith(self._prefix):
                    continue
                try:
                    response = json.loads(line[len(self._prefix) :])
                except ValueError:
                    continue
                if isinstance(response, dict):
                    self._deliver(response)
        finally:
            # Recorded however the read ended, because a wait with no end marker to read runs its
            # whole timeout out instead of failing at once.
            with self._arrivals:
                self._closed = True
                self._arrivals.notify_all()
