"""Synthetic, read-only HTTP replies for the customer testing tutorial."""

import copy

import httpx

URL = "https://offline.bsln.invalid"
TOKEN = "offline-example-token"
DESCRIPTION = {
    "id": "demo-arm",
    "robot_type": "synthetic",
    "joint_order": ["joint1", "gripper"],
    "joints": [
        {"name": "joint1", "unit": "rad", "safe_range": [-0.5, 0.5]},
        {"name": "gripper", "unit": "normalized", "safe_range": [0.0, 1.0]},
    ],
    "control_hz": 30.0,
    "cameras": [],
    "chunks": {"max_targets": 32, "max_horizon_s": 0.5, "playout_delay_s": 0.15},
}


class FakeApi:
    """Accept only the three named GET requests. Nothing falls back to a network."""

    def __init__(self):
        self.requests = []
        self.fail_identity = False

    def __call__(self, request):
        key = (request.method, request.url.path)
        if (request.url.scheme != "https" or request.url.host != "offline.bsln.invalid"
                or request.url.port not in (None, 443) or request.url.query):
            raise AssertionError("unexpected HTTP destination or query")
        allowed = {
            ("GET", "/v1/whoami"),
            ("GET", "/v1/sessions/ses_0000000000000001/description"),
            ("GET", "/v1/sessions/ses_00000000000000ff"),
        }
        if key not in allowed:
            raise AssertionError(f"unexpected HTTP request: {key[0]} {key[1]}")
        if request.headers.get("authorization") != f"Bearer {TOKEN}":
            raise AssertionError("expected the synthetic tutorial token")
        self.requests.append(key)
        if key[1] == "/v1/whoami":
            if self.fail_identity:
                raise httpx.ReadTimeout("synthetic read timeout", request=request)
            return httpx.Response(200, json={"user_id": "demo-user", "name": "offline-user", "scopes": ["read"]})
        if key[1].endswith("/description"):
            return httpx.Response(200, json=copy.deepcopy(DESCRIPTION))
        return httpx.Response(
            403,
            json={"code": "forbidden", "detail": "synthetic permission failure", "request_id": "offline-request-1"},
            headers={"x-request-id": "offline-request-1"},
        )
