"""
This file is generated by the openapi-python-client tool via the generate_api_client.py script

It is a customized template from the openapi-python-client tool's default template:
https://github.com/openapi-generators/openapi-python-client/blob/861ef5622f10fc96d240dc9becb0edf94e61446c/openapi_python_client/templates/errors.py.jinja

The main change is:
- Returning the appropriate python exception for Orca API's error responses
"""

import httpx


def get_error_for_response(response: httpx.Response):
    """Raise an appropriate exception based on the response status code and content"""
    if response.status_code == 401:
        return ValueError("Invalid API key")
    elif response.status_code == 403:
        return PermissionError(response.json()["reason"])
    elif response.status_code == 404:
        resource = response.json()["resource"]
        if resource is not None:
            return LookupError(f"The {resource} you are looking for does not exist")
        else:
            return RuntimeError(f"Unknown API route: {response.url}")
    elif response.status_code == 405:
        return RuntimeError(f"Unknown method {response.request.method} for API route: {response.url}")
    elif response.status_code == 409:
        return RuntimeError(response.json()["constraint"])
    elif response.status_code == 422:
        issues = [f"{issue['loc'][-1]}: {issue['msg']}" for issue in response.json()["validation_issues"]]
        return ValueError("Invalid input:\n\t" + "\n\t".join(issues))
    elif response.status_code == 500:
        return RuntimeError(f"Unexpected server error: {response.json()['message']}")
    elif response.status_code == 503:
        return RuntimeError("Orca API is currently unavailable, please try again later")
    else:
        return RuntimeError(f"Unexpected status code: {response.status_code}")
