# docs/examples/example_energy_efficiency.py

"""
Example: Energy and Efficiency Calculation

This script builds on the basic example to demonstrate how to:
1.  Compute the cumulative energy for a given dataset.
2.  Calculate the per-cycle energy efficiency.
3.  Compute and report specific energy (Wh/kg) if a cell weight is known.
"""

import matplotlib.pyplot as plt
import pandas as pd

from batteryproc.formulas import (
    cumulative_energy_mWh,
    energy_efficiency_per_cycle,
    normalize_inputs,
    specific_energy_mWh_per_mass,
)


def run_energy_efficiency_example():
    """
    Loads sample data, computes per-cycle energy metrics, and prints a summary.
    """
    print("--- Running Energy Efficiency Example ---")

    # 1. Load data from a CSV file
    try:
        df = pd.read_csv("docs/examples/sample_3cycles.csv")
        print("Loaded sample_3cycles.csv successfully.")
    except FileNotFoundError:
        print("Error: sample_3cycles.csv not found. Make sure you are running from the repo root.")
        return

    # 2. Normalize inputs for the formula engine
    inputs = normalize_inputs(df)
    print("Inputs normalized for the formula engine.")

    # 3. Compute per-cycle energy summary
    # The `energy_efficiency_per_cycle` function calculates charge/discharge
    # energy and the resulting efficiency.
    summary = energy_efficiency_per_cycle(inputs)

    # To get specific energy, we first compute the cumulative energy,
    # then call `specific_energy_mWh_per_mass`.
    weight_kg = 0.125  # Example cell weight in kilograms
    energy_mwh = cumulative_energy_mWh(inputs)
    specific_energy_df = specific_energy_mWh_per_mass(
        inputs, energy_mwh=energy_mwh, weight_kg=weight_kg
    )

    # We can now join this back to our main summary. For simplicity, we'll just show the max value per cycle.
    df_full = pd.concat([inputs.to_frame(), specific_energy_df], axis=1)
    specific_energy_summary = (
        df_full.groupby("cycle_index")["specific_energy_mWh_per_kg"].max().reset_index()
    )

    summary = pd.merge(summary, specific_energy_summary, on="cycle_index")

    print("\nComputed Per-Cycle Energy Summary:")
    print(summary)

    # 4. Plotting the results
    fig, ax1 = plt.subplots(figsize=(10, 6))

    ax1.plot(
        summary["cycle_index"],
        summary["charge_mWh"],
        "o-",
        color="blue",
        label="Charge Energy (mWh)",
    )
    ax1.plot(
        summary["cycle_index"],
        summary["discharge_mWh"],
        "o-",
        color="green",
        label="Discharge Energy (mWh)",
    )
    ax1.set_xlabel("Cycle Index")
    ax1.set_ylabel("Energy (mWh)", color="blue")
    ax1.tick_params(axis="y", labelcolor="blue")
    ax1.grid(True)

    # Create a second y-axis for Energy Efficiency
    ax2 = ax1.twinx()
    ax2.plot(
        summary["cycle_index"],
        summary["energy_efficiency_percent"],
        "s--",
        color="red",
        label="Energy Efficiency (%)",
    )
    ax2.set_ylabel("Energy Efficiency (%)", color="red")
    ax2.tick_params(axis="y", labelcolor="red")
    ax2.set_ylim(80, 105)

    fig.tight_layout()
    plt.title("Per-Cycle Energy and Efficiency")
    fig.legend(loc="upper right", bbox_to_anchor=(0.9, 0.9))

    # Save the plot
    output_path = "docs/examples/energy_efficiency_plot.png"
    plt.savefig(output_path)
    print(f"\nPlot saved to {output_path}")
    # plt.show()


if __name__ == "__main__":
    run_energy_efficiency_example()
