import polars as pl


def run(tb_sales_master, options, contexts):

    # 1) order_date 를 Date 타입으로 변환
    df = tb_sales_master.with_columns(
        [
            pl.col("quantity").cast(pl.Float64, strict=False),
            pl.col("net_sales").cast(pl.Float64, strict=False),
        ]
    )

    # 3) order_id + order_date 기준 GroupBy
    result = df.group_by(
        ["order_date", "order_month", "order_month_name", "order_quarter", "order_year"]
    ).agg(
        [
            pl.col("customer_id").n_unique().alias("customer_count"),
            pl.col("customer_type").n_unique().alias("customer_type_count"),
            pl.col("material_id").n_unique().alias("material_count"),
            pl.col("order_id").n_unique().alias("order_count"),
            pl.col("quantity").sum().alias("total_quantity"),
        ]
    )

    return {"tb_sales_date_summary": result}
