"""Slide 6: per-pool deep dives (CRE, C&I, residential, consumer).

Pool codes are FFIEC call report parent codes. Sub-pool variants like
"01E1-Sub Not 1-4 Family Real Estate" are matched via parent-prefix rollup
in fetch_raw_pool_values.
"""
from __future__ import annotations
from pathlib import Path

import matplotlib.pyplot as plt

from .style import BC_BLUE, BC_GRAY, apply_style, n_label
from .data import fetch_raw_pool_values


# Featured pools for the webinar, chosen by observed bank adoption in the
# actual cohort data (1q26 had 230-267 banks per pool for these five).
FEATURED_POOLS = [
    ("1C2A", "1-4 Family Residential (1st lien)"),
    ("04A0", "Construction"),
    ("01E1", "Owner-Occupied CRE"),
    ("01E2", "Non-Owner-Occupied CRE"),
    ("06C0", "Consumer (Vehicles)"),
]


def plot_pool_box(shortqtr: str, out_dir: Path, pools: list[tuple[str, str]] | None = None) -> None:
    apply_style()
    pools = pools or FEATURED_POOLS
    fig, axes = plt.subplots(1, 2, figsize=(14, 7))
    titles = ["Forward-looking adjustment (bps)", "Custom factor adjustment (bps)"]
    metrics = ["qualadj_bps", "customfactors_bps"]

    for ax, metric, title in zip(axes, metrics, titles):
        data = []
        labels = []
        for code, name in pools:
            vals = fetch_raw_pool_values(shortqtr, metric, code)
            # bps conversion: qualadj/customfactors are stored as percentages
            # (e.g. 0.05 = 0.05% = 5 bps), so multiply by 100 to get bps.
            vals_bps = [v * 100 for v in vals]
            # Privacy: need at least N=10 for individual-point visibility.
            # Box plot aggregates so it's OK at N>=5. Suppress below 5.
            if len(vals_bps) >= 5:
                data.append(vals_bps)
                labels.append(f"{name}\n{n_label(len(vals_bps))}")
        if not data:
            ax.text(0.5, 0.5, "Insufficient data", ha="center", transform=ax.transAxes)
            continue
        ax.boxplot(data, labels=labels, showfliers=False,
                   boxprops={"color": BC_BLUE}, medianprops={"color": BC_BLUE, "linewidth": 2})
        ax.set_title(title)
        ax.set_ylabel("bps")
        ax.tick_params(axis="x", labelrotation=20)
        ax.grid(axis="y", alpha=0.3)

    fig.suptitle(f"Per-pool adjustments — {shortqtr.upper()}", fontsize=16)
    plt.tight_layout()
    out = out_dir / "06-pool-deep-dive.png"
    fig.savefig(out)
    plt.close(fig)
    print(f"  wrote {out}")
