import requests
from requests.auth import HTTPBasicAuth
import json
import pandas as pd
from io import StringIO
 
 
# Stuff you need for API Access
sac_base_url = "https://nutramaxlabs.us10.hcs.cloud.sap/api/v1/"
token_url = "https://nutramaxlabs.authentication.us10.hana.ondemand.com/oauth/token"
xcsrf_url = sac_base_url + "csrf"
client_id =
client_secret =
 
 
model_id = 'Cep2am08imk6i49upfn6f46l12' # Web Customer Model
 
api_endpoint = sac_base_url + f"dataexport/providers/sac/{model_id}/MasterData"
 
 
# Step 1: Get the OAuth token
def get_oauth_token(client_id, client_secret, token_url):
 
    session = requests.Session()
    client_credentials = f"{client_id}:{client_secret}"
 
    headers = {
        'Authorization' : f'Basic {client_credentials}'
    }
    payload = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'client_credentials'
    }
   
    response = session.post(token_url, data=payload)
    # Print the response for debugging
    print("Token URL Response Status Code:", response.status_code)
    print("Token URL Response Text:", response.text)
   
    if response.status_code == 200:
        return session, response.json().get('access_token')
    else:
        raise Exception("Failed to get OAuth token: " + response.text)
   
 
 
 
# Step 2: Get XCSRF token
def get_xcsrf_token(session, xcsrf_url, token):
    headers = {
        "x-csrf-token": "fetch",
        "x-sap-sac-custom-auth": "true",
        "Authorization": f"Bearer {token}"
    }
 
    response = session.get(xcsrf_url, headers=headers)
   
    # Print the response for debugging
    print("CSRF Token Response Status Code:", response.status_code)
    print("CSRF Token Response Headers:", response.headers)
 
    # Check if the request was successful
    if response.status_code == 200:
        csrf_token = response.headers.get("x-csrf-token")
        return csrf_token
    else:
        response.raise_for_status()
 
 
 
 
# Step 3: Action time
def access_SAC(session, token, api_endpoint, xcsrf_token):
    headers = {
        'Authorization' : f'Bearer {token}',
        'x-sap-sac-custom-auth' : 'true',
        'Content-Type' : 'application/json',
        'x-csrf-token' : xcsrf_token
    }
 
    filter_params = (
        f"EMAILADDRESS___ID eq 'BRAWA.CGREER@GMAIL.COM' and BPIDENTIFICATIONNUMBER___ID eq '147582'" 
    )
 
    format_params = "text/csv"
 
    params = {
        #'$select':select_params, Can only select measures, must keep all dimensions
        '$filter':filter_params,
        '$format':format_params
    }
 
    response = session.get(api_endpoint, headers=headers, params=params)
 
    print('RESPONSE HEADERS: ', response.headers)
    print('RESPONSE STATUS CODE: ', response.status_code)
 
    csv_data = response.text
 
    df = pd.read_csv(StringIO(csv_data))
    #df = pd.json_normalize(value_data)
    print('DATAFRAME:\n', df)
 
    df.to_excel(fr"I:\SAP\SAP\Exports\API Exports\Web Customer Model Query.xlsx", index=False)
 
 
 
 
 
# Main function to execute the script
if __name__ == "__main__":
    try:
        session, token = get_oauth_token(client_id, client_secret, token_url)
        xcsrf_token = get_xcsrf_token(session, xcsrf_url, token)
        the_get = access_SAC(session, token, api_endpoint, xcsrf_token)
       
 
    except Exception as e:
        print("An error occurred:", str(e))