import json, os, requests, time
from getpass import getpass

# Before you begin, get your API key from https://cloud.ionq.com/settings/keys

# If your API key is stored as "IONQ_API_KEY" in your local environment, this
# should find it. Otherwise you'll be prompted to enter your API key manually.

api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ')

def submit_job(headers, data):
    url = "https://api.ionq.co/v0.3/jobs"
    response = requests.post(url, headers=headers, data=data)
    response_json = response.json()
    assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
    return response_json["id"]

def query_job(job_id, headers):
    url = f"https://api.ionq.co/v0.3/jobs/{job_id}"
    response = requests.get(url, headers=headers)
    response_json = response.json()
    assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
    return response_json["status"]

def get_job_results(job_id, headers):
    url = f"https://api.ionq.co/v0.3/jobs/{job_id}/results"
    response = requests.get(url, headers=headers)
    response_json = response.json()
    assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
    return response_json

headers = {
    "Authorization": f"apiKey {api_key}",
    "Content-Type": "application/json",
}

data = {
    "name": "API Example Circuit",
    "shots": 100,
    "target": "simulator",
    "input": {
        "format": "ionq.circuit.v0",
        "gateset": "qis",
        "qubits": 2,
        "circuit": [
            {
                "gate": "h",
                "target": 0
            },
            {
                "gate": "cnot",
                "control": 0,
                "target": 1
            }
        ]
    }
}



# Now we'll send the job to our backend for processing.

job_id = submit_job(headers, json.dumps(data))

# And wait for the job to be run.

status = "ready"
while status != "completed":
    time.sleep(1)  # wait for 1 second before querying again
    status = query_job(job_id, headers)

# And once the job has run, we can plot the results.

results = get_job_results(job_id, headers)
print(results)