import sys
import os
import sempy.fabric as fabric
import requests


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

import TDS_Fabric

def is_schema_enabled(spark):
    workspace_id = spark.conf.get("trident.workspace.id")
    lakehouse_id = spark.conf.get("trident.lakehouse.id")

    # GET /v1/workspaces/{workspaceId}/lakehouses/{lakehouseId}
    lh = fabric.FabricRestClient().get(
        f"/v1/workspaces/{workspace_id}/lakehouses/{lakehouse_id}"
    ).json()

    default_schema = lh.get("properties", {}).get("defaultSchema")  # only exists when schema-enabled
    return (default_schema is not None), (default_schema or None)

def modules(notebookutils, spark,AFAS_Verkooprelatie):
    TDS_Fabric._notebookutils = notebookutils
    TDS_Fabric._spark = spark
    TDS_Fabric._AFAS_Verkooprelatie = AFAS_Verkooprelatie
    TDS_Fabric._spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "false")
    TDS_Fabric._spark.conf.set("spark.sql.parquet.vorder.enabled", "true")
    TDS_Fabric._spark.conf.set("spark.microsoft.delta.optimizeWrite.enabled", "true")
    TDS_Fabric._spark.conf.set("spark.microsoft.delta.optimizeWrite.binSize", "134217728")
    TDS_Fabric._spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "false")
    TDS_Fabric.workspaceName = TDS_Fabric._spark.conf.get("trident.workspace.name", "")
    if TDS_Fabric._spark.conf.get("trident.lakehouse.name", "") != "":
        enabled, default_schema = is_schema_enabled(spark)
        print(enabled, default_schema)
        lakehouse(default_schema)


def lakehouse(schemaName = None):
    TDS_Fabric.schemaName = schemaName
    TDS_Fabric.workspaceName = workspaceName = TDS_Fabric._spark.conf.get("trident.workspace.name", "")
    TDS_Fabric.lakehouseName = lakehouseName = TDS_Fabric._spark.conf.get("trident.lakehouse.name", "")
    if schemaName is None:
        TDS_Fabric.tablesRootPath = f"abfss://{workspaceName}@onelake.dfs.fabric.microsoft.com/{lakehouseName}.Lakehouse/Tables/{schemaName}"
        fullNamespace = f"{workspaceName}.{lakehouseName}.{schemaName}"
        if fullNamespace in [row['namespace'] for row in TDS_Fabric._spark.sql("SHOW SCHEMAS").collect()]:
            TDS_Fabric._spark.sql(f"USE DATABASE {lakehouseName}.{schemaName}")
    else:
        TDS_Fabric.tablesRootPath = f"abfss://{workspaceName}@onelake.dfs.fabric.microsoft.com/{lakehouseName}.Lakehouse/Tables/"
        TDS_Fabric._spark.sql(f"USE DATABASE {lakehouseName}")

    

def keyvault(keyvaultName):
    TDS_Fabric.keyvaultName = keyvaultName
    TDS_Fabric.keyvaultUrl = f"https://{keyvaultName}.vault.azure.net/"