"""RBFL detector helpers.

This module provides reproducible summaries for the current detector tables.
It does not alter the locked law.
"""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
import pandas as pd

from rbfl_math import event_band_score


def root_dir() -> Path:
    return Path(__file__).resolve().parents[1]


def load_lambda_results(root: Path | None = None) -> pd.DataFrame:
    root = root or root_dir()
    path = root / "data/current_detector/lambda_event_band/rbfl_lambda_band_detector_results.csv"
    return pd.read_csv(path)


def load_lambda_sweep(root: Path | None = None) -> pd.DataFrame:
    root = root or root_dir()
    path = root / "data/current_detector/lambda_event_band/rbfl_lambda_band_sweep_results.csv"
    return pd.read_csv(path)


def summarize_lambda_results(df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for split, group in df.groupby("split"):
        rows.append({
            "split": split,
            "galaxies": int(len(group)),
            "phase_match": float(group["match_lambda_band"].mean()),
            "velocity_pass_15pct": float(group["velocity_pass_15pct"].mean()),
            "combined_pass": float(group["combined_pass"].mean()),
            "median_mape_pct": float(group["MAPE_pct"].median()),
            "event_flags": int(group["lambda_event_flag_band"].sum()),
        })
    return pd.DataFrame(rows).sort_values("split").reset_index(drop=True)


def recompute_event_scores(df: pd.DataFrame, center=2.0, sigma=0.25) -> pd.DataFrame:
    out = df.copy()
    if "Lambda_phase_median" in out.columns:
        s1 = event_band_score(out["Lambda_phase_median"].values, center=center, sigma=sigma)
    else:
        s1 = np.zeros(len(out))
    if "Lambda_phase_outer_median" in out.columns:
        s2 = event_band_score(out["Lambda_phase_outer_median"].values, center=center, sigma=sigma)
    else:
        s2 = np.zeros(len(out))
    out["lambda_event_score_recomputed"] = np.maximum(s1, s2)
    out["lambda_event_flag_recomputed"] = (out["lambda_event_score_recomputed"] > 0.5).astype(int)
    return out


def write_json(obj, path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, indent=2)
