"""
{{ display_name }} - Analyze node.

This module handles statistical analysis and output generation.
"""

import json

import pandas as pd

from torivers_sdk.automation.output import JsonDataBlock, build_output_data

from state import {{ class_name }}State


async def analyze(state: {{ class_name }}State) -> dict:
    """Analyze the transformed data and generate statistics.

    Args:
        state: Current pipeline state.

    Returns:
        Dictionary with state updates including statistics and output.
    """
    context = state["context"]

    context.log_progress("Analyzing", "Computing statistics...")

    # Load dataframe from JSON
    df = pd.DataFrame(json.loads(state["dataframe_json"]))

    # Compute statistics for numeric columns
    numeric_df = df.select_dtypes(include=["number"])
    statistics = {}

    if not numeric_df.empty:
        describe = numeric_df.describe()
        statistics = {
            "summary": describe.to_dict(),
            "correlations": numeric_df.corr().to_dict()
            if len(numeric_df.columns) > 1
            else {},
        }

    # Prepare output data
    processed_data = df.to_dict(orient="records")

    context.log_success("Analysis complete", f"Generated statistics for {len(df)} rows")

    return {
        "current_step": "completed",
        "statistics": statistics,
        "processed_data": processed_data,
        "output_data": build_output_data(
            JsonDataBlock(
                label="Pipeline Results",
                data={
                    "row_count": state["row_count"],
                    "column_count": state["column_count"],
                    "statistics": statistics,
                    "processed_data": processed_data,
                },
                display_hint="table",
            ),
        ),
    }
