import pandas as pd


def format_dataframe(
    bess_soc_for_cycle, bess_data, load_profiles_since_start, swap_time
):
    """Formats the DataFrame for display in the dashboard."""
    # Create a DataFrame for sites
    # columns = ["Site Name", "MBESS Unit", "Current Load (kW)", "SoC (%)", "Predicted Swap Time"]

    status_df = pd.DataFrame(
        columns=[
            "Site Name",
            "MBESS Unit",
            "Current Load (kW)",
            "SoC (%)",
            "Predicted Swap Time",
            "Cycle Discharge Profile",
            "Load Profile Since Start",
        ]
    )

    for site in load_profiles_since_start.keys():
        index = next(i for i, d in enumerate(bess_data["units"]) if d["site"] == site)
        soc = bess_data["units"][index]["SoC"]
        current_load = bess_data["units"][index]["current_load_kW"]
        unit_name = bess_data["units"][index]["name"]
        predicted_swap_time = swap_time.get(unit_name, "N/A")
        # convert predicted_swap_time to a readable format
        if isinstance(predicted_swap_time, float):
            predicted_swap_time = pd.to_datetime(
                predicted_swap_time, unit="s"
            ).strftime("%Y-%m-%d %H:%M:%S")

        status_df = pd.concat(
            [
                status_df,
                pd.DataFrame(
                    [
                        {
                            "Site Name": site,
                            "MBESS Unit": unit_name,
                            "Current Load (kW)": current_load,
                            "SoC (%)": soc * 100,  # Convert to percentage
                            "Predicted Swap Time": predicted_swap_time,
                            "Cycle Discharge Profile": bess_soc_for_cycle[unit_name][
                                "SoC"
                            ].tolist(),
                            "Load Profile Since Start": load_profiles_since_start[
                                site
                            ].tolist(),
                        }
                    ]
                ),
            ],
            ignore_index=True,
        )

    return status_df
