# -*- coding: utf-8 -*-


import pandas as pd

from ..aerosolalt import AerosolAlt
from .Common import detect_delimiter

###############################################################################


def Load_Aethalometer_file(file: str, extra_data: bool = False) -> AerosolAlt:
    """
    Load data from Aethalometer output files.

    This function reads data exported by an Aethalometer, extracting black carbon
    concentration components and optional metadata into an `Aerosolalt` object.

    Parameters
    ----------
    file : str
        Path to a .csv or .txt file generated by the Aethalometer.
    extra_data : bool, optional
        If True, stores all non-primary columns in `.extra_data`. Default is False.

    Returns
    -------
    Aethalometer : Aerosolalt
        Object containing:
        - 'Datetime', 'IR BCc', 'Biomass BCc', 'Fossil fuel BCc', and 'AAE' columns (in ng/m³)
        - Metadata including serial number and optical configuration

    Raises
    ------
    Exception
        If the data file is empty.
    """
    encoding, delimiter = detect_delimiter(file)

    df = pd.read_csv(
        file, delimiter=delimiter, encoding=encoding, header=0, decimal="."
    ).dropna()
    if df.empty:
        raise Exception("Empty data set")

    df = df.reset_index(drop=True)
    df.rename(
        columns={
            "Date / time local": "Datetime",
            "Biomass BCc  (ng/m^3)": "Biomass BCc",
            "Fossil fuel BCc  (ng/m^3)": "Fossil fuel BCc",
        },
        inplace=True,
    )

    df["Datetime"] = pd.to_datetime(df["Datetime"], format="%Y-%m-%dT%H:%M:%S")

    # Extract and store metadata
    meta = {
        "serial_number": df["Serial number"].iloc[0],
        "optical_config": df["Optical config"].iloc[0],
        "instrument": "Aethalometer",
        "unit": "ng/m³",
        "dtype": "dm",
    }

    # Drop non-measurement columns
    df.drop(columns=list(df.columns[:6]) + ["Optical config"], inplace=True)

    # Extract relevant data
    core_cols = ["Datetime", "IR BCc", "Biomass BCc", "Fossil fuel BCc", "AAE"]
    data = df[core_cols]

    # Load into Aerosolalt class
    aeth = AerosolAlt(data.copy())
    aeth._meta = meta

    if extra_data:
        extra_df = df.drop(columns=["IR BCc", "Biomass BCc", "Fossil fuel BCc", "AAE"])
        extra_df.set_index("Datetime", inplace=True)
        aeth._extra_data = extra_df

    return aeth
