import os
from great_expectations.data_context.types.base import DataContextConfig, DatasourceConfig, S3StoreBackendDefaults, FilesystemStoreBackendDefaults
from great_expectations.data_context import BaseDataContext
from psi_great_expectations import log_it

@log_it
def build_data_context_config(datasource_name: str, s3_bucket_name: str = None, s3_prefix: str = None, file_type: str = 'json'):
    '''
    builds and returns a data context object for profilers and validators, 
    it defines where the produced files from either are written.
    '''
    connectors = {
        "default_runtime_data_connector_name": {
            "class_name": "RuntimeDataConnector",
            "batch_identifiers": ["default_identifier_name"]
        }
    }

    if s3_bucket_name:

        connectors['default_inferred_data_connector_name'] = {
            "class_name": "InferredAssetS3DataConnector",
            "bucket": s3_bucket_name,
            "prefix": s3_prefix,
            "default_regex": {
                "pattern": f"(.*)\.{file_type}",
                "group_names": ["data_asset_name"]
            }
        }

        backend = S3StoreBackendDefaults(
            default_bucket_name = s3_bucket_name,
            expectations_store_prefix = "great_expectations/expectations",
            validations_store_prefix = "great_expectations/validations",
            data_docs_prefix = "great_expectations/data_docs",
            checkpoint_store_prefix = "great_expectations/checkpoints",
            profiler_store_prefix = "profilers",
            expectations_store_name = "expectations_S3_store",
            validations_store_name = "validations_S3_store",
            evaluation_parameter_store_name = "evaluation_parameter_store",
            checkpoint_store_name = "checkpoint_S3_store",
            profiler_store_name = "profiler_S3_store"
        )

    else:
        connectors['default_inferred_data_connector_name'] = {
            "class_name": "InferredAssetFilesystemDataConnector",
            "base_directory": f"{os.getcwd()}/ge_to_profile/",
            "glob_directive": f"*.{file_type}",
            "default_regex": {
                "pattern": f"(.*)\.{file_type}", #TODO: needs to target the desired file f"/^{datasource_name}_to_profile.{file_type}$/"#
                "group_names": ["data_asset_name"]
            }
        }

        backend = FilesystemStoreBackendDefaults(root_directory=f"{os.getcwd()}/great_expectations")

    data_context_config = DataContextConfig(
        datasources={
            datasource_name: DatasourceConfig(
                class_name="Datasource",
                execution_engine={
                    "class_name": "PandasExecutionEngine"
                },
                data_connectors=connectors
            )
        },
        store_backend_defaults=backend
        
    )
    return BaseDataContext(project_config=data_context_config)