"""API functions for interacting with peaked circuits on the BlueQubit backend."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING, Any

from bluequbit.exceptions import BQSDKUsageError

if TYPE_CHECKING:
    from bluequbit.backend_connection import BackendConnection


def get_peaked_circuit(
    _connection: BackendConnection, difficulty: int, circuit_id: int | None = None
) -> dict[str, Any]:
    """Fetch a single peaked circuit by ID from the backend.

    :param _connection: backend connection instance
    :param difficulty: difficulty of the circuit to fetch
    :param circuit_id: non-negative integer ID of the circuit to fetch. If ``None``,
                       a random circuit of the given difficulty will be returned.
    :return: dict with keys ``qasm_str``, ``key``, and ``metadata``
    :raises BQSDKUsageError: if circuit_id is not a non-negative integer
    """
    if circuit_id is not None and (not isinstance(circuit_id, int) or circuit_id < 0):
        raise BQSDKUsageError("circuit_id must be a non-negative integer")
    if difficulty is None or not isinstance(difficulty, int) or difficulty <= 0:
        raise BQSDKUsageError("difficulty must be a positive integer")
    if circuit_id is None:
        params = {"difficulty": difficulty}
    else:
        params = {"difficulty": difficulty, "id": circuit_id}
    response = _connection.send_request(
        req_type="GET", path="/peaked-circuits/file", params=params
    )
    return json.loads(response.text)
