# flake8: noqa T001, E501
# -*- coding: utf-8 -*-
"""
Exporting Results Example

Demonstrates how to calculate statistics and export results to tables
for further analysis in Excel, MATLAB, etc.

Creates three tables:
    1. Overall statistics (avg, min, max voltage/current)
    2. Per-cycle summary
    3. Energy analysis with time integration

Also demonstrates CSV export with custom formatting options.
"""

import BTAnalysisPyInterface as bta

try:
    import numpy as np

    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False
    bta.print("NumPy not available, using Python built-ins")


def main():
    bta.print("Setting up export tables...")

    for source in bta.get_sources():

        # ========== OVERALL STATISTICS TABLE ==========
        stats_table = bta.add_table(
            columns=[
                "Avg_Voltage",
                "Max_Voltage",
                "Min_Voltage",
                "Avg_Current",
                "Max_Current",
                "Duration",
            ],
            title="Battery Statistics",
        )

        # Collect all data
        voltages = []
        currents = []
        times = []

        for point in source.data_points("Potentiostat measure", ["Time", "U", "I"]):
            times.append(point["Time"])
            voltages.append(point["U"])
            currents.append(point["I"])

        if voltages:
            # Calculate statistics
            if HAS_NUMPY:
                avg_voltage = float(np.mean(voltages))
                max_voltage = float(np.max(voltages))
                min_voltage = float(np.min(voltages))
                avg_current = float(np.mean(currents))
                max_current = float(np.max(currents))
            else:
                avg_voltage = sum(voltages) / len(voltages)
                max_voltage = max(voltages)
                min_voltage = min(voltages)
                avg_current = sum(currents) / len(currents)
                max_current = max(currents)

            total_time = times[-1] - times[0] if len(times) > 1 else 0

            # Export to table (single row with all stats)
            stats_table.add_row(
                {
                    "Avg_Voltage": avg_voltage,
                    "Max_Voltage": max_voltage,
                    "Min_Voltage": min_voltage,
                    "Avg_Current": avg_current,
                    "Max_Current": max_current,
                    "Duration": total_time,
                }
            )

            bta.print(f"Statistics calculated from {len(voltages)} samples:")
            bta.print(f"  Avg Voltage: {avg_voltage:.3f} V")
            bta.print(f"  Max Voltage: {max_voltage:.3f} V")
            bta.print(f"  Min Voltage: {min_voltage:.3f} V")
            bta.print(f"  Avg Current: {avg_current:.3f} A")
            bta.print(f"  Max Current: {max_current:.3f} A")
            bta.print(f"  Duration: {total_time:.1f} s")

            # Export to CSV with default options
            stats_table.export_to_csv("battery_statistics.csv")
            bta.print("Exported: battery_statistics.csv")

        # ========== PER-CYCLE SUMMARY TABLE ==========
        if source.has_column("Potentiostat measure", "Cycle number"):
            cycle_summary_table = bta.add_table(
                columns=["Cycle", "Avg_Voltage", "Avg_Current", "Duration"],
                title="Per-Cycle Summary",
            )

            # Group data by cycle
            cycle_data = {}

            for point in source.data_points(
                "Potentiostat measure", ["Time", "U", "I", "Cycle number"]
            ):
                cycle_num = int(point["Cycle number"])

                if cycle_num not in cycle_data:
                    cycle_data[cycle_num] = {
                        "voltages": [],
                        "currents": [],
                        "times": [],
                    }

                cycle_data[cycle_num]["voltages"].append(point["U"])
                cycle_data[cycle_num]["currents"].append(point["I"])
                cycle_data[cycle_num]["times"].append(point["Time"])

            # Calculate per-cycle metrics
            for cycle_num in sorted(cycle_data.keys()):
                data = cycle_data[cycle_num]

                if HAS_NUMPY:
                    avg_v = float(np.mean(data["voltages"]))
                    avg_i = float(np.mean(data["currents"]))
                else:
                    avg_v = sum(data["voltages"]) / len(data["voltages"])
                    avg_i = sum(data["currents"]) / len(data["currents"])

                duration = (
                    data["times"][-1] - data["times"][0]
                    if len(data["times"]) > 1
                    else 0
                )

                cycle_summary_table.add_row(
                    {
                        "Cycle": float(cycle_num),
                        "Avg_Voltage": avg_v,
                        "Avg_Current": avg_i,
                        "Duration": duration,
                    }
                )

            bta.print(f"Per-cycle summary: {len(cycle_data)} cycles")

            # Export with European format (semicolon, comma decimal)
            csv_options = bta.CsvExportOptions()
            csv_options.separator = ";"
            csv_options.decimal_point = ","
            csv_options.encoding = "utf-8-bom"
            cycle_summary_table.export_to_csv("cycle_summary_eu.csv", csv_options)
            bta.print("Exported: cycle_summary_eu.csv (European format)")

        else:
            bta.print("Skipped per-cycle summary (no cycle data)")

        # ========== ENERGY ANALYSIS TABLE ==========
        energy_table = bta.add_table(
            columns=["Time", "Voltage", "Current", "Power", "Energy"],
            title="Energy Analysis",
        )

        cumulative_energy = 0.0
        prev_time = None

        for point in source.data_points("Potentiostat measure", ["Time", "U", "I"]):
            time = point["Time"]
            voltage = point["U"]
            current = point["I"]
            power = voltage * current  # Watts

            # Integrate power over time
            if prev_time is not None:
                dt = time - prev_time  # seconds
                cumulative_energy += power * dt  # Watt-seconds (Joules)

            energy_table.add_row(
                {
                    "Time": time,
                    "Voltage": voltage,
                    "Current": current,
                    "Power": power,
                    "Energy": cumulative_energy,
                }
            )

            prev_time = time

        bta.print(f"Total energy: {cumulative_energy:.2f} J")

        # Export selected columns only
        csv_options_selected = bta.CsvExportOptions()
        csv_options_selected.columns = ["Time", "Power", "Energy"]
        csv_options_selected.decimal_places = 4
        energy_table.export_to_csv("energy_selected.csv", csv_options_selected)
        bta.print("Exported: energy_selected.csv (selected columns)")

    bta.print("Export tables complete!")
