import sqlite3

import pandas as pd

from storai.core.pipeline import run_pipeline


def test_pipeline_returns_display_data_source_sql_and_reasons():
    rows = []

    # May baseline.
    for day in range(1, 31):
        visits = 100
        rows.append(
            {
                "service_date": f"2025-05-{day:02d}",
                "visit_count": visits,
                "payment": visits * 10,
            }
        )

    # June dip with two weak days to drive a reason.
    for day in range(1, 31):
        visits = 80
        if day in (13, 23):
            visits = 20
        rows.append(
            {
                "service_date": f"2025-06-{day:02d}",
                "visit_count": visits,
                "payment": visits * 10,
            }
        )

    source_df = pd.DataFrame(rows)
    source_df["service_date"] = pd.to_datetime(source_df["service_date"])

    summary_df = (
        source_df.assign(
            report_date=source_df["service_date"].dt.to_period("M").dt.to_timestamp()
        )
        .groupby("report_date", as_index=False)
        .agg(payment=("payment", "sum"), visit_count=("visit_count", "sum"))
    )

    source_sql = "select * from source_daily"
    conn = sqlite3.connect(":memory:")
    source_df.to_sql("source_daily", conn, index=False, if_exists="replace")

    result = run_pipeline(summary_df, source_sql=source_sql, db_engine=conn)

    assert "display_df" in result
    assert "display_rows" in result
    assert "source_sql" in result
    assert "insights" in result
    assert "ml_findings" in result

    assert result["source_sql"] == source_sql
    assert result["insights"], "Expected at least one generated insight."

    first = result["insights"][0]
    assert "insight" in first
    assert "reason" in first
    assert first["reason"], "Expected a non-empty root-cause reason."
    assert "13th" in first["reason"]
    assert "23rd" in first["reason"]
