"""Few modules for importing and exporting from https://voc-qc.nilu.no/

Note that the export and import functions are the opposite of the
import/export feature from the website.
(We export data from this programm, which is imported to the site.)
(We import data into this programm, which was exported from the site.)
"""

import logging
from pathlib import Path

import pandas as pd


from tucavoc.additional_data import AdditionalData
from tucavoc.additional_data.station import StationInformation

from avoca.bindings.qa_tool import export_EmpaQATool as avoca_export_qatool


def export_EmpaQATool(
    df: pd.DataFrame,
    df_substances: pd.DataFrame,
    export_path: Path,
    additional_data: dict[type, AdditionalData] = {},
):
    """Export to the EmpaQATool format.

    The exported file from the program can then be imported to
    the tool on https://voc-qc.nilu.no/Import
    The specs fro that file can be found in
    https://voc-qc.nilu.no/doc/CSVImport_FormatSpecifications.pdf

    This will add the additional data from the dataframe.

    :arg df: Calculation dataframe
    :arg df_substances: Substances dataframe
    :arg export_path: Path to export the file
    :arg additional_data: Additional data to add to the export
    :arg substances: List of substances to export. You can also specify group names.
        If not specified, this will use the substances from `df_substances`.

    """

    df = df.copy()

    logger = logging.getLogger(__name__)

    logger.error(f"Called export qa tool with {df_substances=}")

    if StationInformation in additional_data:
        station_info: StationInformation = additional_data[StationInformation]
        station = station_info.get_station()

        abbreviation = station.abbreviation

    elif "station_abbreviation" in additional_data:
        abbreviation = additional_data["station_abbreviation"]

    else:
        logger.warning(
            "No station information found, using default values. "
            "This might not be correct."
        )
        abbreviation = "XXX"

    for state in ["start", "end"]:
        col_additonal = ("StartEndOffsets", f"datetime_{state}")
        df[("-", f"datetime_{state}")] = df[col_additonal]
        df = df.drop(columns=[col_additonal])

    out_filepath = avoca_export_qatool(
        df=df,
        df_substances=df_substances,
        export_path=export_path,
        station=abbreviation,
    )

    logger.info(f"Exported to `{out_filepath}`")

    return out_filepath
