# flake8: noqa T001, E501
# -*- coding: utf-8 -*-
"""
Quick Report Example

Demonstrates quick_report with auto content only, then with custom graphs/tables/images.
"""

from pathlib import Path

import BTAnalysisPyInterface as bta
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401

output_dir = Path(__file__).parent / "temp"
output_dir.mkdir(parents=True, exist_ok=True)


def build_custom_content(sources):
    # Custom graph: U vs Time
    graph = bta.add_graph(title="Voltage vs Time", xAxis="Time", y1Axis="U")
    for source in sources:
        graph.add_series(
            source.name(),
            source.get_column("Potentiostat measure", "Time"),
            source.get_column("Potentiostat measure", "U"),
        )

    # Custom image: 3D charge/discharge + pie chart
    source = sources[0]
    summary = source.get_summary(bta.SummaryType.PER_CYCLE)
    cycles = np.array(summary.get_column("Cycle number").get_values())
    q_dch = np.array(summary.get_column("Q discharge").get_values()) / 3.6
    q_ch = np.array(summary.get_column("Q charge").get_values()) / 3.6

    fig = plt.figure(figsize=(12, 5))
    fig.suptitle("Battery Analysis Overview", fontsize=13, fontweight="bold")

    # Left: 3D — charge vs discharge over cycles
    ax3d = fig.add_subplot(1, 2, 1, projection="3d")
    ax3d.plot(
        cycles,
        q_ch,
        np.zeros(len(cycles)),
        color="#2E86AB",
        linewidth=1.5,
        label="Charge",
    )
    ax3d.plot(
        cycles,
        q_dch,
        np.ones(len(cycles)),
        color="#A23B72",
        linewidth=1.5,
        label="Discharge",
    )
    ax3d.set_xlabel("Cycle", fontsize=8)
    ax3d.set_ylabel("Capacity (mA.h)", fontsize=8)
    ax3d.set_zticks([0, 1])
    ax3d.set_zticklabels(["Ch", "Dch"], fontsize=7)
    ax3d.set_title("Charge vs Discharge", fontsize=10)
    ax3d.legend(fontsize=8)

    # Right: pie chart — test time breakdown (fake illustrative data)
    ax_pie = fig.add_subplot(1, 2, 2)
    labels = ["Charge", "Discharge", "Rest", "CV phase"]
    values = [28, 35, 22, 15]
    colors = ["#2E86AB", "#A23B72", "#F18F01", "#3BB273"]
    ax_pie.pie(
        values,
        labels=labels,
        colors=colors,
        autopct="%1.0f%%",
        startangle=90,
        wedgeprops={"edgecolor": "white", "linewidth": 1.5},
    )
    ax_pie.set_title("Test Time Breakdown", fontsize=10)

    fig.subplots_adjust()

    img = bta.add_image("Battery Analysis Overview")
    img.set_from_matplotlib(fig)
    plt.close(fig)

    return graph, img


def main():

    # ── Report 1: fully automatic ─────────────────────────────────────────
    bta.print("Generating auto report...")
    bta.quick_report(
        filename=str(output_dir / "battery_report_auto.pdf"),
        logo=Path(__file__).parent / "biologic.png",
        title="Battery Test Report",
        company_name="My Company",
        footer_text="Generated with BT-Analysis Script Tool",
        primary_color="#5c81f7",
        secondary_color="#ff7854",
        tertiary_color="#ffcf00",
        auto_open=True,
    )
    bta.print("✓ Auto report done!")

    # ── Report 2: auto + custom content ───────────────────────────────────
    sources = bta.get_sources()
    graph, img = build_custom_content(sources)

    bta.print("Generating custom report...")
    bta.quick_report(
        filename=str(output_dir / "battery_report_custom.pdf"),
        logo=Path(__file__).parent / "biologic.png",
        sources=sources,
        graphs=[graph],
        images=[img],
        title="Battery Analysis – Custom Report",
        company_name="My Company",
        footer_text="Generated with BT-Analysis Script Tool",
        primary_color="#5c81f7",
        secondary_color="#ff7854",
        tertiary_color="#ffcf00",
        auto_open=True,
    )
    bta.print("✓ Custom report done!")
