"""Public ARKHEIA clearance transport and offline Ed25519 verification.

Wire rules: docs/wire-spec-v1.0.1.md. A valid receipt signature authenticates
bytes, not a closed receipt schema, freshness, a permit, or execution authority.
Python 3.10+; install cryptography. No signing credentials or private routes.
"""
from __future__ import annotations

import argparse
import http.client
import json
import math
import re
import socket
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any, NoReturn

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

BASE_URL = "https://arkheia-cps-10.onrender.com"
CLEARANCE_KEY_ID = "ed25519:a2008a603a195230"
CLEARANCE_PUBLIC_KEY_HEX = "9e2c04f0027bce2844eb10241a9b107d215d0dfa384c537acf45d75d4f97aa27"
CLEARANCE_RECEIPT_DOMAIN = "ARKHEIA/clearance/receipt/v1"
MAX_JSON_BYTES = 65_536
MAX_DEPTH = 64
MAX_SAFE_INTEGER = 9_007_199_254_740_991


class ArkheiaError(Exception):
    """Base client error. Messages do not include submitted payloads."""


class InputError(ArkheiaError):
    pass


class TransportError(ArkheiaError):
    pass


class ProtocolError(ArkheiaError):
    pass


class KeyPinMismatch(ArkheiaError):
    pass


class UnsupportedReceiptFormat(ArkheiaError):
    """Legacy import compatibility only; the verifier now returns bool."""
    code = "UNSUPPORTED_CLEARANCE_RECEIPT_FORMAT"


class HTTPError(ArkheiaError):
    def __init__(self, status: int, endpoint: str, response_text: str):
        super().__init__(f"ARKHEIA HTTP {status} at {endpoint}; no authorization granted")
        self.status = status
        self.endpoint = endpoint
        self.response_text = response_text
        try:
            self.response_json = parse_json(response_text)
        except InputError:
            self.response_json = None


def _validate_string(value: str) -> None:
    if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
        raise InputError("Lone Unicode surrogates are not accepted")


def _validate_json(value: Any, depth: int = 0) -> None:
    if depth > MAX_DEPTH:
        raise InputError("JSON nesting exceeds the client limit")
    if value is None or type(value) is bool:
        return
    if type(value) is str:
        _validate_string(value)
        return
    if type(value) is int:
        if abs(value) > MAX_SAFE_INTEGER:
            raise InputError("Integer exceeds the interoperable JSON safe range; use a contract-defined string")
        return
    if type(value) is list:
        for item in value:
            _validate_json(item, depth + 1)
        return
    if type(value) is dict:
        for key, item in value.items():
            if type(key) is not str:
                raise InputError("JSON object keys must be strings")
            _validate_string(key)
            _validate_json(item, depth + 1)
        return
    raise InputError("Only JSON objects, arrays, strings, safe integers, booleans and null are accepted; floats are forbidden")


def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    result: dict[str, Any] = {}
    for key, value in pairs:
        if key in result:
            raise InputError("Duplicate JSON object keys are not accepted")
        result[key] = value
    return result


def _invalid_number(_: str) -> NoReturn:
    raise InputError("Float tokens and non-finite JSON numbers are forbidden")


def parse_json(text: str) -> Any:
    """Strict wire-profile parsing. Decimal/exponent tokens (even 1.0/1e0) raise.

    Parse original text before verification: duplicate keys and original numeric
    token forms cannot be recovered from an already-parsed object.
    """
    try:
        if type(text) is not str or len(text.encode("utf-8")) > MAX_JSON_BYTES:
            raise InputError("JSON input exceeds the client byte limit")
        if text.startswith("\ufeff"):
            raise InputError("UTF-8 BOM is forbidden")
        value = json.loads(text, object_pairs_hook=_unique_object,
                           parse_float=_invalid_number, parse_constant=_invalid_number)
        _validate_json(value)
        return value
    except (ValueError, UnicodeError, RecursionError) as exc:
        raise InputError("Invalid JSON input") from exc


def load_json_file(path: str | Path) -> dict[str, Any]:
    """Load a strict UTF-8 wire object; this does not validate its artifact schema."""
    with Path(path).open("rb") as handle:
        data = handle.read(MAX_JSON_BYTES + 1)
    if len(data) > MAX_JSON_BYTES:
        raise InputError("JSON input exceeds the client byte limit")
    try:
        value = parse_json(data.decode("utf-8"))
    except UnicodeError as exc:
        raise InputError("JSON input must be UTF-8") from exc
    if type(value) is not dict:
        raise InputError("The endpoint input must be a JSON object")
    return value


def canonicalize(value: Any) -> bytes:
    """RFC 8785 JCS UTF-8 bytes, integers-only profile; raises InputError.

    Keys sort by UTF-16 code units, not Python Unicode scalar order. Floats,
    surrogates, non-string keys, unsafe integers, and depth >64 are forbidden.
    The SDK also bounds canonical JSON to 65,536 bytes.
    """
    _validate_json(value)

    def encode(item: Any) -> str:
        if type(item) is dict:
            keys = sorted(item, key=lambda key: key.encode("utf-16-be"))
            return "{" + ",".join(encode(key) + ":" + encode(item[key]) for key in keys) + "}"
        if type(item) is list:
            return "[" + ",".join(encode(child) for child in item) + "]"
        return json.dumps(item, ensure_ascii=False, allow_nan=False, separators=(",", ":"))

    data = encode(value).encode("utf-8")
    if len(data) > MAX_JSON_BYTES:
        raise InputError("JSON input exceeds the client byte limit")
    return data


def signing_input(domain: str, artifact: dict[str, Any], signature_field: str = "sig") -> bytes:
    """ASCII domain || NUL || JCS(artifact minus one top-level signature field).

    This constructs public bytes only; it neither signs nor establishes trust.
    Other fields, including nested signatures and any public_key_id, stay signed.
    """
    if type(domain) is not str or not domain or "\x00" in domain:
        raise InputError("Domain must be non-empty ASCII without NUL")
    try:
        tag = domain.encode("ascii")
    except UnicodeError as exc:
        raise InputError("Domain must be ASCII") from exc
    if type(artifact) is not dict or type(signature_field) is not str or not signature_field:
        raise InputError("Artifact must be an object with a named signature-carrying field")
    canonicalize(artifact)  # Validate all original fields and the complete object bound.
    unsigned = {key: value for key, value in artifact.items() if key != signature_field}
    return tag + b"\x00" + canonicalize(unsigned)


def verify_clearance_receipt(receipt: Any) -> bool:
    """Verify only receipt Ed25519 authenticity under the out-of-band public pin.

    Invalid/malformed input or signatures return False. All fields except the
    top-level `signature` are signed exactly as received, without guessed schema
    fields. If public_key_id is present, it must equal CLEARANCE_KEY_ID. No key
    from the receipt, head, network, or legacy /v1 family is dynamically trusted.
    True does NOT establish receipt schema validity or execution authorization.
    """
    try:
        if type(receipt) is not dict:
            return False
        canonicalize(receipt)
        signature = receipt.get("signature")
        if type(signature) is not str or re.fullmatch(r"[0-9a-f]{128}", signature) is None:
            return False
        if "public_key_id" in receipt and receipt["public_key_id"] != CLEARANCE_KEY_ID:
            return False
        if re.fullmatch(r"[0-9a-f]{64}", CLEARANCE_PUBLIC_KEY_HEX) is None:
            return False
        key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(CLEARANCE_PUBLIC_KEY_HEX))
        key.verify(bytes.fromhex(signature), signing_input(CLEARANCE_RECEIPT_DOMAIN, receipt, "signature"))
        return True
    except Exception:
        # Two-outcome API, including invalid key/signature and malformed objects.
        return False


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class ArkheiaClient:
    """Transport only. Pins are out-of-band constants, never auto-rotated from head.

    Timeout applies to blocking network operations. POSTs are never retried and
    redirects are rejected. Request and response bodies are capped at 65,536 bytes
    (request cap matches wire spec; response cap is additional client policy).
    """
    def __init__(self, base_url: str = BASE_URL, timeout: float = 20.0):
        try:
            parsed = urllib.parse.urlsplit(base_url)
            port = parsed.port
        except (ValueError, TypeError) as exc:
            raise InputError("Invalid API origin") from exc
        if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
                or parsed.query or parsed.fragment or parsed.path not in ("", "/")
                or port not in (None, 443)):
            raise InputError("API base URL must be an HTTPS origin without credentials, path or query")
        if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
            raise InputError("Timeout must be a positive finite number of seconds")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self._opener = urllib.request.build_opener(_NoRedirect())

    def _request(self, method: str, endpoint: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
        data = None
        if payload is not None:
            if type(payload) is not dict:
                raise InputError("Endpoint input must be a JSON object")
            data = canonicalize(payload)
        headers = {"Accept": "application/json", "User-Agent": "arkheia-public-sdk/1.0.1"}
        if data is not None:
            headers["Content-Type"] = "application/json"
        request = urllib.request.Request(self.base_url + endpoint, data=data, headers=headers, method=method)
        try:
            with self._opener.open(request, timeout=self.timeout) as response:
                status = response.status
                raw = response.read(MAX_JSON_BYTES + 1)
        except urllib.error.HTTPError as exc:
            try:
                raw = exc.read(MAX_JSON_BYTES + 1)
            except (TimeoutError, OSError, http.client.HTTPException) as body_error:
                raise TransportError(f"Unable to read HTTP error body at {endpoint}; outcome unknown") from body_error
            finally:
                exc.close()
            raise HTTPError(exc.code, endpoint, raw[:MAX_JSON_BYTES].decode("utf-8", errors="replace")) from exc
        except (urllib.error.URLError, TimeoutError, socket.timeout, OSError, http.client.HTTPException) as exc:
            raise TransportError(f"Network failure or timeout at {endpoint}; outcome unknown, do not retry automatically") from exc
        if not 200 <= status < 300:
            raise HTTPError(status, endpoint, raw[:MAX_JSON_BYTES].decode("utf-8", errors="replace"))
        if len(raw) > MAX_JSON_BYTES:
            raise ProtocolError("API response exceeds the client byte limit")
        try:
            value = parse_json(raw.decode("utf-8"))
        except (InputError, UnicodeError) as exc:
            raise ProtocolError("API returned invalid or unsupported JSON") from exc
        if type(value) is not dict:
            raise ProtocolError("Expected a JSON object response")
        return value

    def clearance_head(self) -> dict[str, Any]:
        """Check BOTH public pins; a head match is not receipt verification."""
        head = self._request("GET", "/api/clearance/head")
        if (head.get("public_key_id") != CLEARANCE_KEY_ID
                or head.get("engine_public_key") != CLEARANCE_PUBLIC_KEY_HEX):
            raise KeyPinMismatch("Clearance head does not match the pinned key and ID; block execution")
        return head

    def mandate_verify(self, payload: dict[str, Any]) -> dict[str, Any]:
        """POST a provider-issued signed MANDATE; return UNVERIFIED raw response."""
        if type(payload) is not dict:
            raise InputError("Endpoint input must be a JSON object")
        canonicalize(payload)
        self.clearance_head()
        return self._request("POST", "/api/mandate/verify", payload)

    def aegis_evaluate(self, payload: dict[str, Any]) -> dict[str, Any]:
        """POST a signed OBSERVATION/HUMAN_RELEASE; return UNVERIFIED raw response."""
        if type(payload) is not dict:
            raise InputError("Endpoint input must be a JSON object")
        canonicalize(payload)
        self.clearance_head()
        return self._request("POST", "/api/aegis/evaluate", payload)


def _main() -> int:
    parser = argparse.ArgumentParser(description="Public gate transport and offline receipt signature verification; never execution authorization")
    parser.add_argument("operation", choices=("head", "mandate", "aegis", "verify"))
    parser.add_argument("json_file", nargs="?", help="Provider-supplied request or receipt JSON file")
    parser.add_argument("--timeout", type=float, default=20.0)
    args = parser.parse_args()
    if args.operation != "head" and not args.json_file:
        parser.error("this operation requires a JSON file")
    try:
        if args.operation == "verify":
            valid = verify_clearance_receipt(load_json_file(args.json_file))
            print(json.dumps({"signature_valid": valid, "execution_authorized": False,
                              "warning": "Signature validity is not schema validation or permission to execute"}, indent=2))
            return 0 if valid else 3
        client = ArkheiaClient(timeout=args.timeout)
        if args.operation == "head":
            print(json.dumps({"key_pin_match": True, "head": client.clearance_head()}, indent=2))
            return 0
        payload = load_json_file(args.json_file)
        result = client.mandate_verify(payload) if args.operation == "mandate" else client.aegis_evaluate(payload)
        print(json.dumps({"verified": False, "raw_response": result, "warning": "Do not execute a protected action"}, indent=2))
        return 3
    except HTTPError as exc:
        print(json.dumps({"error": str(exc), "status": exc.status, "response": exc.response_json}, indent=2), file=sys.stderr)
        return 2
    except (ArkheiaError, OSError) as exc:
        print(str(exc), file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(_main())
