import os
import traceback as tb
from modelling_utils import (
    Scale,
    Units,
    stof,
)
from pandas import (
    read_csv,
    DataFrame,
)


def readSignals(file_path: str = None) -> DataFrame:
    """_summary_
    Reads a time series table data into a pandas DataFrame and returns it.
    Args:
        file_path (str, optional): The file path of the Comma Separated Values (.CSV) file generated by Cadence (or other EDA software).
                                    Defaults to None.
        time_col (bool, optional): If True, the csv file is assume to have a time column. Otherwise, time column is discarded.
    Returns:
        DataFrame: the pandas DataFrame containing the time series data with all the correspondant signals.
    """
    time_col = "t"
    if file_path is None:
        raise ValueError("The file path was not provided.")
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"File {file_path} not found.")
    signals = None
    try:
        signals = read_csv(file_path, header=0)
    except Exception as e:
        tb.format_exc()
        return None
    # preprocess the headers of the data - search for the time column
    possible_time_cols = ["time", "t", "Time", "T", "TIME"]
    ordered = False
    signals_columns_order = signals.columns.tolist()
    for column in list(signals.columns):
        tokens = column.split(" ")
        for token in tokens:
            if token in possible_time_cols + [
                Units.TIME.value,
                f"[{Units.TIME.value}]",
                f"({Units.TIME.value})",
            ]:
                # place the time column in the first column of the DataFrame
                signals_columns_order = [column] + list(
                    signals.drop(columns=[column]).columns
                )
                ordered = True
                break
        if ordered:
            break
    if ordered:
        return signals[signals_columns_order].set_index(signals_columns_order[0])
    else:
        return signals
