"""Census API wrapper."""

import requests
import pycen

def census_api_call(url, params):
    '''
    Make Census API call.

    Parameters
    ----------
    url : str
        API endpoint URL
    params : dict
        Query parameters

    Returns
    -------
    dict
        JSON response

    Raises
    ------
    ValueError
        If API error (including rate limits)
    '''
    api_key = pycen.get_api_key()

    if api_key:
        params = params.copy()
        params['key'] = api_key

    response = requests.get(url, params=params)

    if response.status_code != 200:
        error_msg = f"Census API error: {response.status_code} - {response.text}"

        # Rate limit hit
        if response.status_code == 429 or "rate limit" in response.text.lower():
            error_msg += "\n\nRate limit exceeded. Get a free API key at: https://api.census.gov/data/key_signup.html"
            error_msg += "\nThen set it with: pycen.set_api_key('YOUR_KEY')"

        raise ValueError(error_msg)

    try:
        return response.json()
    except ValueError:
        snippet = response.text.strip().replace("\n", " ")
        snippet = snippet[:500] + ("..." if len(snippet) > 500 else "")
        raise ValueError(
            f"Census API returned non-JSON response. Response snippet: {snippet}"
        )
