from typing import Optional
import requests
import logging


def create_cluster(project_id: str, location: str, machine_type: str, node_count: int, accelerator: Optional[str], cluster_id: str, token: str, cluster_version: str) -> dict:
    """Creates a cluster in the Identity and Access Management API.

    Args:
        project_id: GCP project ID.
        location: Google Compute Engine zone.
        machine_type: Machine type.
        node_count: Initial node count.
        accelerator: Accelerator machine type.
        cluster_id: Cluster ID
        token: Access token from the Google Authorization Server.
        cluster_version: Cluster version.

    Returns:
        A dict containing the response body.
    """
    host = "https://container.googleapis.com"
    url = f"{host}/v1beta1/projects/{project_id}/locations/{location}/clusters"
    body = {
        "cluster": {
            "name": cluster_id,
            "nodePools": [
                {
                    "name": "default-pool",
                    "initialNodeCount": node_count - 1 if accelerator else node_count,
                    "config": {
                        "machineType": machine_type,
                    },
                },
            ],
            "initialClusterVersion": cluster_version,
        },
    }
    if accelerator:
        body["cluster"]["nodePools"].append({
            "name": "accelerator-pool",
            "initialNodeCount": 1,
            "config": {
                "machineType": machine_type,
                "accelerators": [{
                    "acceleratorCount": "1",
                    "acceleratorType": accelerator,
                }],
            },
        })
    resp = requests.post(url, json=body, headers={
        "Authorization": f"Bearer {token}"
    })
    try:
        resp.raise_for_status()
    except requests.exceptions.HTTPError as err:
        logging.error(err.response.text)
        raise err
    return resp.json()