"""Site-level contribution summaries."""

from __future__ import annotations

import numpy as np
import pandas as pd


def summarize_site_contributions(
    site_scores: np.ndarray,
    top_n: int = 10,
    window: int = 10,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    x = np.asarray(site_scores, dtype=float)
    if x.ndim != 1:
        raise ValueError("site_scores must be 1D")

    standardized = (x - np.mean(x)) / (np.std(x, ddof=1) + 1e-12)
    site_df = pd.DataFrame(
        {
            "site": np.arange(1, len(x) + 1),
            "contribution": x,
            "standardized": standardized,
        }
    )

    top_df = site_df.sort_values("contribution", ascending=False).head(top_n).copy()

    if len(x) >= window:
        starts = np.arange(0, len(x) - window + 1)
        window_mean = np.array([float(np.mean(x[s : s + window])) for s in starts])
        win_df = pd.DataFrame(
            {
                "window_start": starts + 1,
                "window_end": starts + window,
                "window_mean_contribution": window_mean,
            }
        )
    else:
        win_df = pd.DataFrame(
            {
                "window_start": [1],
                "window_end": [len(x)],
                "window_mean_contribution": [float(np.mean(x))],
            }
        )

    return top_df, win_df
