import requests
import msal
from credential import USERNAME, PASSWORD

APP_ID = '<APP ID (CLIENT ID)>'
TENANT_ID = '<TENANT ID)'
SECRET_VALUE = '<CLIENT SECRET>'
authority = f'https://login.microsoftonline.com/{TENANT_ID}'
scopes = ["https://analysis.windows.net/powerbi/api/.default"]

app = msal.ConfidentialClientApplication(APP_ID, authority=authority, client_credential=SECRET_VALUE)

result = None
# result = app.acquire_token_for_client(scopes=scopes)
result = app.acquire_token_by_username_password(USERNAME, PASSWORD, scopes)

if not "access_token" in result:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))
    raise Exception("Failed to get access token")

url_group_list = 'https://api.powerbi.com/v1.0/myorg/groups'
headers = {
    'Authorization': 'Bearer ' + result['access_token']
}
response = requests.get(url_group_list, headers=headers)
# print(response)

workspace_list = response.json()['value']
for workspace in workspace_list:
    if 'windsor' in workspace['name'].lower():
        workspaice_id = workspace['id']
        url_group_delete = f'https://api.powerbi.com/v1.0/myorg/groups/{workspaice_id}'
        requests.delete(url_group_delete, headers=headers)
        print(workspace['name'], ' is deleted')