"""Dual X-axis cursor logic.

Provides interpolation and value readout at two user-selected time points
across all plotted channels.
"""

from __future__ import annotations

from typing import Any

import numpy as np
import pandas as pd

from impakt.channel.model import Channel
from impakt.plot.spec import CursorValues


def compute_cursor_values(
    channels: list[tuple[str, Channel]],
    x1: float,
    x2: float,
) -> CursorValues:
    """Compute interpolated values at two X positions for all channels.

    Args:
        channels: List of (label, channel) tuples.
        x1: First cursor time position.
        x2: Second cursor time position.

    Returns:
        CursorValues with per-channel interpolated values and deltas.
    """
    values = []
    for label, ch in channels:
        v1 = float(np.interp(x1, ch.time, ch.data))
        v2 = float(np.interp(x2, ch.time, ch.data))
        values.append(
            {
                "label": label,
                "value_at_x1": v1,
                "value_at_x2": v2,
                "delta": v2 - v1,
                "unit": ch.unit,
                "channel_name": ch.name,
            }
        )

    return CursorValues(x1=x1, x2=x2, values=values)


def cursor_values_to_dataframe(cv: CursorValues) -> pd.DataFrame:
    """Convert CursorValues to a pandas DataFrame."""
    return pd.DataFrame(cv.values)
