"""Line chart block implementation."""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import pandas as pd

from yera.events.blocks.base import _ChartBlockFactory
from yera.events.blocks.base.chart import _ChartConversionData
from yera.events.models import LineChartData
from yera.events.stream import push_output


class _LineChartBlockFactory(_ChartBlockFactory):
    """Factory for creating line chart blocks, matching Streamlit's st.line_chart API."""

    def __init__(self):
        super().__init__("line_chart")

    def _create_chart_data_from_conversion(
        self,
        conversion_data: _ChartConversionData,
        chart_specific_params: dict,
    ) -> LineChartData:
        """Convert intermediate data to LineChartData."""
        if len(chart_specific_params) > 0:
            raise ValueError("Line charts don't have specific parameters")

        # LineChartData omits x_ticks and x_label when x parameter was not provided
        x_ticks = (
            conversion_data.x_categories
            if conversion_data.x_label is not None
            else None
        )
        x_label = conversion_data.x_label

        return LineChartData(
            x_label=x_label,
            x_ticks=x_ticks,
            y_label=conversion_data.y_label,
            y_values=conversion_data.y_values,
            colour_label=conversion_data.colour_label,
            colour_series=conversion_data.colour_categories,
            colour_values=conversion_data.colour_values,
        )

    def __call__(
        self,
        data: pd.DataFrame,
        *,
        x: str | None = None,
        y: str | Sequence[str] | None = None,
        colour: str | Sequence[str] | None = None,
    ) -> None:
        """Create a line chart block, matching Streamlit's st.line_chart() signature.

        Args:
            data: DataFrame to plot
            x: Column name for x-axis (None = use index, or omit x_ticks if y is specified)
            y: Column name(s) for y-axis (None = use all columns)
            colour: Column name for colour grouping, or list of colors

        Returns:
            None (informational block)

        """
        if x is None and y is None:
            conversion_data = self._convert_default_format(data)
        elif x is not None and isinstance(y, str):
            conversion_data = self._convert_long_format(data, x, y, colour)
        elif isinstance(y, Sequence) and not isinstance(y, str):
            # Wide format: y is a sequence, x may be None or a string
            conversion_data = self._convert_wide_format(data, x, y, colour)
        else:
            raise ValueError(
                f"Unsupported line_chart parameter combination: x={x}, y={y}"
            )

        chart_data = self._create_chart_data_from_conversion(
            conversion_data,
            {},  # Line charts don't have chart-specific params
        )

        event = self._create_block_output_event(
            chart_data, message_type="informational"
        )
        push_output(event)
        return


# Create the line_chart callable
line_chart = _LineChartBlockFactory()

__all__ = ["line_chart"]
