import requests
from urllib.parse import quote_plus

GSHEET_ID = "1Rxdqyo9KPnqgcMzbB9Xl-ITelIpzZSzVfKeSe_Q71cI"
GSHEET_KEY = "AIzaSyC_wP19S_k0q3T0muYUqN0jRDxwvbsQMQQ"

def sheets_get_tab(tab):
    """
    Fetches data from a Google Sheet tab and returns it as a list of dictionaries.

    Args:
        tab (str): The name of the sheet tab to fetch.

    Returns:
        list: A list of dictionaries where each dictionary represents a row with headers as keys.
              Returns an empty list if the request fails or data is invalid.
    """
    url = f"https://sheets.googleapis.com/v4/spreadsheets/{quote_plus(GSHEET_ID)}/values/{quote_plus(tab)}?key={quote_plus(GSHEET_KEY)}"
    
    try:
        response = requests.get(url, timeout=6)
        response.raise_for_status()  # Raises HTTPError for bad responses (4xx, 5xx)
        data = response.json()
    except (requests.exceptions.RequestException, ValueError):
        return []
    
    rows = data.get('values', [])
    if len(rows) < 2:
        return []
    
    headers = [h.strip() for h in rows[0]]
    out = []
    for row in rows[1:]:
        n = len(headers)
        padded_row = (row + [''] * n)[:n]  # Pad or truncate to match header length
        out.append(dict(zip(headers, padded_row)))
    
    return out

d= sheets_get_tab("users")
print(d)