# flake8: noqa T001, E501
# -*- coding: utf-8 -*-
"""
Power Computation Example

Calculate and display power (P = U × I) from voltage and current.
Creates both a graph and a table showing power calculations.

Outputs:
    - Graph: Power vs Time (entire dataset)
    - Table: Power values for time range 50-600s
"""

import BTAnalysisPyInterface as bta


def main():
    bta.print("Setting up power analysis...")

    for source in bta.get_sources():
        # Create power graph
        power_graph = bta.add_graph(
            title="Power vs Time", xAxis="Time", y1Axis="Power", y1_unit="W"
        )

        # Create power table for specific time range
        power_table = bta.add_table(
            columns=["Time", "Power"],
            title="Power Analysis (50-600s)",
            units=["s", "W"],
        )

        # Process data in one loop
        row_count = 0
        total_power = 0.0

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

            power = voltage * current

            # Add to graph (all data)
            power_graph.add_point(time, power)

            # Add to table (only time range 50-600s)
            if 50 <= time <= 600:
                power_table.add_row({"Time": time, "Power": power})
                row_count += 1
                total_power += power

        # Display statistics
        if row_count > 0:
            avg_power = total_power / row_count
            bta.print(f"Power table: {row_count} rows, Avg = {avg_power:.3f}W")
        else:
            bta.print("Power table: No data in range 50-600s")

        bta.print("Power analysis complete!")
