import logging
import os
from nemo_library.features.config import Config
from nemo_library.features.projects import LoadReport, getProjectList
from nemo_library.utils.migmanutils import (
    get_local_project_directory,
    get_multi_projects,
    get_proALPHA_project_status_file,
    get_projects,
    getNEMOStepsFrompAMigrationStatusFile,
    getProjectName,
    load_database,
)
from nemo_library.utils.utils import log_error

__all__ = ["MigManExportData"]


def MigManExportData(config: Config) -> None:

    # get configuration
    local_project_directory = get_local_project_directory()
    multi_projects = get_multi_projects()

    # if there is a status file given, we ignore the given projects and get the project list from the status file
    proALPHA_project_status_file = get_proALPHA_project_status_file()
    if proALPHA_project_status_file:
        projects = getNEMOStepsFrompAMigrationStatusFile(proALPHA_project_status_file)
    else:
        projects = get_projects()

    project_list_nemo = getProjectList(config)["displayName"].to_list()
    
    dbdf = load_database()
    for project in projects:

        # check for project in database
        filtereddbdf = dbdf[dbdf["project_name"] == project]
        if filtereddbdf.empty:
            log_error(f"project '{project}' not found in database")

        # get list of postfixes
        postfixes = filtereddbdf["postfix"].unique().tolist()

        # init project
        multi_projects_list = (
            (multi_projects[project] if project in multi_projects else None)
            if multi_projects
            else None
        )
        if multi_projects_list:
            for addon in multi_projects_list:
                for postfix in postfixes:
                    _export_data(config,local_project_directory,project_list_nemo,project, addon, postfix)
        else:
            for postfix in postfixes:
                _export_data(config,local_project_directory,project_list_nemo,project, None, postfix)


def _export_data(
    config: Config,
    local_project_directory: str,
    project_list_nemo : list[str],
    project: str,
    addon: str,
    postfix: str,
) -> None:

    # export reports
    data = [
        ("to_customer", "_with_messages", "(Customer) All records with message"),
        ("to_proalpha", "", "(MigMan) All records with no message"),
    ]
    project_name = getProjectName(project, addon, postfix)

    if project_name not in project_list_nemo:
        logging.info(f"Project '{project_name}' not available in NEMO. No data exported")
        return

    for folder, file_postfix, report_name in data:

        file_name = os.path.join(
            local_project_directory,
            folder,
            f"{project_name}{file_postfix}.csv",
        )
        df = LoadReport(
            config=config,
            projectname=project_name,
            report_name=report_name,
        )
        df.to_csv(
            file_name,
            index=False,
            sep=";",
            encoding="UTF-8",
        )

        logging.info(
            f"File '{file_name}' for '{project}', addon '{addon}', postfix '{postfix}' exported '{report_name}'"
        )
