# flake8: noqa T001, E501
# -*- coding: utf-8 -*-
"""
Matplotlib Image Example

Create custom visualizations using matplotlib and display them in BT-Analysis.
"""
import BTAnalysisPyInterface as bta
import matplotlib.pyplot as plt
import numpy as np


def main():
    bta.print("Creating matplotlib visualization...")

    for source in bta.get_sources():
        # Get per-cycle summary data
        summary = source.get_summary(bta.SummaryType.PER_CYCLE)

        if summary.row_count == 0:
            bta.print("No cycle data found")
            continue

        # Get data
        cycles = summary.get_column("Cycle number").get_values()
        q_discharge = np.array(summary.get_column("Q discharge").get_values()) / 3.6
        efficiency = np.array(summary.get_column("Efficiency").get_values()) * 100

        # Create matplotlib figure
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
        fig.suptitle("Battery Cycle Analysis", fontsize=16, fontweight="bold")

        # Plot 1: Discharge capacity
        ax1.plot(cycles, q_discharge, "o-", color="#2E86AB", linewidth=2, markersize=6)
        ax1.set_xlabel("Cycle Number", fontsize=12)
        ax1.set_ylabel("Discharge Capacity (mA.h)", fontsize=12)
        ax1.set_title("Q discharge over cycles", fontsize=14)
        ax1.grid(True, alpha=0.3, linestyle="--")

        # Plot 2: Efficiency
        ax2.plot(cycles, efficiency, "s-", color="#A23B72", linewidth=2, markersize=6)
        ax2.set_xlabel("Cycle Number", fontsize=12)
        ax2.set_ylabel("Efficiency (%)", fontsize=12)
        ax2.set_title("Coulombic Efficiency", fontsize=14)
        ax2.grid(True, alpha=0.3, linestyle="--")
        ax2.axhline(y=100, color="gray", linestyle="--", alpha=0.5)

        plt.tight_layout()

        # Add to BT-Analysis
        image = bta.add_image("Cycle Analysis")
        image.set_from_matplotlib(fig)
        plt.close(fig)

        bta.print("✓ Matplotlib image created")
