from dku_utils.type_checking import DSSProject, check_object_is_project


def handle_project_pipelines(
    project: DSSProject,
    type_of_pipeline: str,
    enable_pipeline: bool = False,
    prune_before_merge: bool = True,
):
    """
    To activate or deactivate the data pipeline for a project

    :param project: DSSProject: A handle to interact with a project on the DSS instance.
    :param type_of_pipeline: str: 'SPARK' or 'SQL'. To select which pipeline for configuration.
    :param enable_pipeline: bool: To allow executing long data pipelines with multiple steps without always having to write the intermediate data and re-read it at the next steps.
    :param prune_before_merge: bool: To apply job pruning before merging.
    """
    check_object_is_project(project)
    assert type_of_pipeline in ["SPARK", "SQL"], ValueError(
        f"Expected 'type_of_pipeline' to have value 'SPARK' or 'SQL', but found {type_of_pipeline}"
    )

    project_settings = project.get_settings()

    if type_of_pipeline == "SPARK":
        project_settings.get_raw()["settings"]["flowBuildSettings"][
            "mergeSparkPipelines"
        ] = enable_pipeline
        project_settings.get_raw()["settings"]["flowBuildSettings"][
            "pruneBeforeSparkPipelines"
        ] = prune_before_merge

    else:
        project_settings.get_raw()["settings"]["flowBuildSettings"][
            "mergeSqlPipelines"
        ] = enable_pipeline
        project_settings.get_raw()["settings"]["flowBuildSettings"][
            "pruneBeforeSqlPipelines"
        ] = prune_before_merge

    project_settings.save()


def check_project_pipeline_is_enabled(
    project: DSSProject, type_of_pipeline: str, fail_if_not_enabled: bool = True
):
    """
    :param project: DSSProject: A handle to interact with a project on the DSS instance.
    :param type_of_pipeline: str: 'SPARK' or 'SQL'
    :param fail_if_not_enabled: bool: triggers an exception if the project pipelines are not enabled
    """
    check_object_is_project(project)
    project_settings = project.get_settings()
    assert type_of_pipeline in ["SPARK", "SQL"], ValueError(
        f"Expected 'type_of_pipeline' to have value 'SPARK' or 'SQL', but found {type_of_pipeline}"
    )

    if type_of_pipeline == "SPARK":
        pipeline_status = project_settings.get_raw()["settings"]["flowBuildSettings"][
            "mergeSparkPipelines"
        ]

        if fail_if_not_enabled:
            assert pipeline_status, "Spark pipeline is not yet enabled. To set the parameter at the project 'Settings/Flow build & Pipelines' or by the function dku_utils/projects/settings/pipeline.py/handle_project_pipelines."

    else:
        pipeline_status = project_settings.get_raw()["settings"]["flowBuildSettings"][
            "mergeSqlPipelines"
        ]

        if fail_if_not_enabled:
            assert pipeline_status, "SQL pipeline is not yet enabled"

    return pipeline_status
