# docs/examples/example_dqdv.py

"""
Example: Differential Capacity (dQ/dV) Analysis

This script demonstrates a more advanced analysis technique:
1.  Loading data from an XLSX file containing a CC-CV protocol.
2.  Computing the dQ/dV trace using the `dqdv_trace` function.
3.  Plotting the resulting dQ/dV curve against voltage.

Differential Capacity Analysis is a powerful method for identifying
electrochemical phase transitions and diagnosing battery degradation.
"""

import matplotlib.pyplot as plt
import pandas as pd

from batteryproc.formulas import dqdv_trace, normalize_inputs


def run_dqdv_example():
    """
    Loads CC-CV data and computes and plots the dQ/dV trace.
    """
    print("--- Running dQ/dV Analysis Example ---")

    # 1. Load data from an XLSX file
    try:
        df = pd.read_excel("docs/examples/sample_cccv.xlsx")
        print("Loaded sample_cccv.xlsx successfully.")
    except FileNotFoundError:
        print("Error: sample_cccv.xlsx not found. Make sure you are running from the repo root.")
        return

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

    # 3. Compute the dQ/dV trace
    # The `dqdv_trace` function handles the necessary smoothing, differentiation,
    # and filtering to produce a clean dQ/dV signal.
    # It automatically restricts the calculation to constant-current segments.
    dqdv_results = dqdv_trace(
        inputs,
        window_length=5,  # Smaller window for less data
        polyorder=2,
        current_tolerance=0.05,  # 5% tolerance for CC check
    )
    print("\nComputed dQ/dV Trace (first 5 rows):")
    print(dqdv_results.head())

    # 4. Plotting the results
    # Merge the dQ/dV results with the original inputs to get the current column
    plot_df = pd.concat([inputs.to_frame(), dqdv_results], axis=1)

    # We only plot the valid dQ/dV points.
    valid_dqdv = plot_df[plot_df["is_valid"]].copy()

    # Separate charge and discharge for plotting
    charge_dqdv = valid_dqdv[valid_dqdv["current_a"] > 0]
    discharge_dqdv = valid_dqdv[valid_dqdv["current_a"] < 0]

    plt.figure(figsize=(10, 6))
    plt.plot(charge_dqdv["voltage_v"], charge_dqdv["dqdv_mAh_per_V"], "b-", label="Charge dQ/dV")
    plt.plot(
        discharge_dqdv["voltage_v"], discharge_dqdv["dqdv_mAh_per_V"], "g-", label="Discharge dQ/dV"
    )
    plt.xlabel("Voltage (V)")
    plt.ylabel("dQ/dV (mAh/V)")
    plt.title("Differential Capacity (dQ/dV) vs. Voltage")
    plt.grid(True)
    plt.legend()

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


if __name__ == "__main__":
    run_dqdv_example()
