import sys
import os
import requests

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import TDS_Fabric as TDS


def getBaseUrl():
    ToschAFASMember = "83164"   # AFAS online member id is required for the api url.
    base_url = f'https://{ToschAFASMember}.rest.afas.online/ProfitRestServices/'
    return base_url

def autenticeerServicemelding(key_vault,client_id_name, client_secret_name):
    key_vault = "kv-afasservicemelding"
    ToschAFASMember = "83164"   # AFAS online member id is required for the api url.

    # Configuratie
    base_url = getBaseUrl()    

    CLIENT_ID =  TDS.utils.getSecret(client_id_name, keyvaultName=key_vault)
    CLIENT_SECRET = TDS.utils.getSecret(client_secret_name, keyvaultName=key_vault)
    TOKEN_URL = f"https://{ToschAFASMember}.rest.afas.online/ProfitRestServices/oauth/token"

    data = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": "afas"  # required by AFAS
    }

    response = requests.post(TOKEN_URL, data=data)
    access_token = response.json()["access_token"]
    try:
        access_token = access_token
        header = {'Authorization': f'Bearer {access_token}'}
        return header
    except Exception as e:
        print(f"Fout bij het verkrijgen van het access token: {e}")
        raise



def verstuurServicemelding(
    titel: str | None = None,
    context: str | None = None,
    pipelineName: str = "B_DailyRefresh",
    workspace: str = None,
    pipeline: str = "87e52f09-a490-4bdc-bea2-4472142eca56",
    pipelineRunID: str = "f145ef9f-3e1a-41d1-839e-952775b84358",
    fabricItems: str = "Copy Actie",
    fabricItemsType: str = "Notebooks",
    key_vault: str = "kv-afasservicemelding",
    client_id_name: str = "afas-servicemelding-clientid",
    client_secret_name: str = "afas-servicemelding-clientsecret",
    MonitoringMessage: str = None
) -> None:
    """
    Verstuur een servicemelding (bijv. naar AFAS) met context over een pipeline run.

    Args:
        titel: Korte titel van de melding.
        context: Extra details / foutmelding / stacktrace.
        pipelineName: Naam van de Fabric pipeline.
        workspace: Workspace-id (GUID) waarin de pipeline draait.
        pipeline: Pipeline-id (GUID).
        pipelineRunID: Run-id (GUID) van de specifieke uitvoering.
        fabricItems: Map/label waar notebooks staan (optioneel).
        key_vault: Azure Key Vault naam met secrets voor authenticatie.
        client_id_name: Secret-naam in Key Vault voor de client-id.
        client_secret_name: Secret-naam in Key Vault voor de client-secret.

    Returns:
        dossierItem_id: ID van de aangemaakte servicemelding in AFAS.
    """
    headers = autenticeerServicemelding(key_vault=key_vault, client_id_name=client_id_name, client_secret_name=client_secret_name   )
    verkooprelatie_id = TDS._AFAS_Verkooprelatie
    instuurder = "83164.zz"

    if workspace is None:
        workspace = TDS.workspaceName

    if titel is None:
        titel = "Alert: " + pipelineName + " is gefaald."

    if context is None:
        context = f"De melding laat het volgende zien: \n\n {MonitoringMessage}"

    monitoring_url = f"https://app.powerbi.com/workloads/data-pipeline/artifactAuthor/workspaces/{workspace}/pipelines/{pipeline}/{pipelineRunID}?experience=power-bi"
    
    if checkServicemeldingExist(pipeline):
        print("Servicemelding bestaat al")
        return
    

    payload = {
        "KnSubject": {
            "Element": {
                "Fields": {
                    "StId": 21,
                    "Ds":  titel,
                    "SbTx": context,
                    "UsId": instuurder,
                    #"EmId": verantwoordelijke,
                    "ViPr": "L",
                    "FvF1": 256
                },
                "Objects": [
                    {
                        "KnSubjectLink": {
                            "Element": {
                                "Fields": {
                                    "ToSR": True,
                                    "SfTp": 4,
                                    "SfId": verkooprelatie_id
                                }
                            }
                        }
                    },
                    {
                        "KnS01": {
                            "Element": {
                                "Fields": {
                                    "U82630274481AD0D5BEBEE5998D00F4A2": "08",
                                    "UB8F9A9A16617425CBC02FD0023AD021A": monitoring_url,
                                    "U7C069BA078A54B3284F9332FE701896A": pipeline,
                                    "U4EEE081D389B4714A5F5A2A3015604E8": workspace,
                                    "UB1F2ED1A9EE646BFA44245BBB703891D": fabricItems,
                                    "U63DBF3E1B9CF4583915C5E9819BD24C0": fabricItemsType,
                                    "UD0F6675DDF574BFD976DC7568D00F0F9": MonitoringMessage

                                }
                            }
                        }
                    }
                ]
            }
        }
    }
    base_url =getBaseUrl()   
    url = f"{base_url}/connectors/KnSubject"
    response = requests.post(url, json=payload, headers=headers)
    
    if response.status_code == 201:
        responseJson = response.json()
        dossierItem_id = responseJson["results"]["KnSubject"]["SbId"]
        return dossierItem_id
    else:
        raise Exception(f"Status: {response.status_code}, Response: {response.text}")
    
    return response     

def checkServicemeldingExist(pipeline):
    return False



def logRun():
    pass

def process():
    pass