"""Join regulatory bank financials to policy rates and inflation, then distinguish deposit growth from purchasing-power growth.

Research example. Live observations can change.
"""

from datetime import UTC, datetime
from decimal import Decimal
from textwrap import fill

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

AS_OF = datetime.now(UTC).date()
NAVY, BLUE, PINK = "#132244", "#8fb9ff", "#e7a2cc"


def fetch(qj):
    return {
        "fdic_bank": qj.domains.call(
            "regulatory.banking.get_institutions", provider="fdic", filters="CERT:628", limit=1
        ),
        "fdic_history": qj.domains.call(
            "regulatory.banking.get_financials",
            provider="fdic",
            filters="CERT:628 AND REPDTE:[20200101 TO 20251231]",
            limit=30,
            sort_by="REPDTE",
            sort_order="ASC",
        ),
        "funds": qj.domains.call(
            "macro.indicators.get_fred_data_series_by_id",
            provider="fred",
            search_id="DFF",
            start="2020-01-01",
            end="2025-12-31",
        ),
        "bls_cpi": qj.domains.call(
            "macro.us.get_cpi", provider="bls", start_year=2020, end_year=2025, category="all", seasonally_adjusted=True
        ),
    }


def analyze(raw):
    institution = frame(raw["fdic_bank"], date=None).iloc[0]
    if int(institution["CERT"]) != 628:
        raise ValueError("Institution identity does not match the bank financials")
    reports = frame(raw["fdic_history"], date=None)
    reports.index = pd.to_datetime(reports["REPDTE"], format="%Y%m%d", utc=True)
    reports = reports.sort_index()
    rates, cpi = macro(raw["funds"], "DFF"), bls_cpi(raw["bls_cpi"])
    rows = []
    for end, report in reports.iterrows():
        start = end - pd.DateOffset(months=3)
        quarter_rates = rates.loc[(rates.index > start) & (rates.index <= end)]
        quarter_cpi = cpi.loc[(cpi.index > start) & (cpi.index <= end)]
        if quarter_rates.empty or len(quarter_cpi) != 3:
            continue
        rows.append(
            {
                "Report date": end,
                "NIM %": float(report["NIMY"]),
                "Policy rate %": quarter_rates.mean(),
                "Real deposits": decimal(report["DEP"]) / decimal(str(quarter_cpi.mean())),
            }
        )
    data = pd.DataFrame(rows).set_index("Report date")
    if len(data) < 8:
        raise ValueError("Need at least eight matched quarterly reports")
    # Require the exact prior-year quarter rather than shifting across gaps.
    previous = data["Real deposits"].reindex(data.index - pd.DateOffset(years=1))
    data["Real deposit growth %"] = [
        100 * (ratio(now, old) - 1) if pd.notna(old) else np.nan
        for now, old in zip(data["Real deposits"], previous, strict=True)
    ]
    fig, (top, bottom) = canvas("FDIC bank 628 · " + str(institution["NAMEHCR"]), "%", panels=2)
    top.plot(data.index, data["NIM %"], label="FDIC NIMY")
    top.plot(data.index, data["Policy rate %"], label="Effective Fed funds · quarter mean")
    legend(top)
    bottom.bar(data.index, data["Real deposit growth %"], width=55, color=PINK)
    bottom.set_ylabel("CPI-adjusted deposit growth · YoY %")
    bottom.axhline(0, color="#afc1dc", lw=0.8)
    from matplotlib.dates import DateFormatter, YearLocator

    for axis in [top, bottom]:
        axis.set_xlim(data.index.min() - pd.Timedelta(days=50), data.index.max() + pd.Timedelta(days=50))
        axis.xaxis.set_major_locator(YearLocator())
        axis.xaxis.set_major_formatter(DateFormatter("%Y"))
    return data.drop(columns="Real deposits").reset_index(), fig


def payload(response):
    if hasattr(response, "to_dict"):
        response = response.to_dict()
    while isinstance(response, dict):
        if response.get("error") or response.get("error_code") or response.get("success") is False:
            raise ValueError("Provider request failed")
        if "data" in response:
            response = response["data"]
        elif "value" in response:
            response = response["value"]
        else:
            break
    return response


def frame(response, date="date"):
    rows = payload(response)
    if not isinstance(rows, list) or not rows:
        raise ValueError("No provider observations returned")
    result = pd.DataFrame(rows)
    if date:
        result[date] = pd.to_datetime(result[date], utc=True)
        result = result.sort_values(date)
    return result


def decimal(value):
    if pd.isna(value):
        raise ValueError("Required monetary value or quantity is missing")
    return Decimal(str(value))


def ratio(numerator, denominator):
    denominator = decimal(denominator)
    if denominator == 0:
        raise ValueError("Required denominator is zero")
    return float(decimal(numerator) / denominator)


def macro(response, column):
    values = frame(response).set_index("date")[column]
    values = pd.to_numeric(values, errors="coerce").dropna()
    if values.empty:
        raise ValueError(f"No numeric observations for {column}")
    return values


def canvas(title, ylabel, panels=1):
    plt.rcParams.update(
        {
            "figure.facecolor": NAVY,
            "axes.facecolor": NAVY,
            "savefig.facecolor": NAVY,
            "text.color": "#e9eef8",
            "axes.labelcolor": "#afc1dc",
            "xtick.color": "#afc1dc",
            "ytick.color": "#afc1dc",
            "axes.edgecolor": "#34486b",
            "grid.color": "#34486b",
            "font.size": 10,
            "axes.prop_cycle": plt.cycler(color=[BLUE, PINK, "#ba9dea"]),
        }
    )
    fig, axes = plt.subplots(panels, 1, figsize=(9, 6.1), squeeze=False, layout="constrained")
    fig.suptitle(fill(title, width=58), fontsize=17, x=0.04, ha="left", weight="medium")
    for ax in axes.flat:
        ax.grid(axis="y", alpha=0.45)
        ax.set_axisbelow(True)
        ax.spines[["top", "right"]].set_visible(False)
    axes.flat[0].set_ylabel(ylabel)
    return fig, list(axes.flat)


def legend(ax):
    ax.legend(frameon=False, labelcolor="#e9eef8", fontsize=9)


def run():
    from quantjourney.sdk import QuantJourneyAPI

    qj = QuantJourneyAPI.from_env()
    raw = fetch(qj)
    table, fig = analyze(raw)
    print(table.to_string(index=False))
    fig.savefig(OUTPUT, dpi=180)
    plt.show()


def bls_cpi(response):
    return macro(response, "cpi_all")


OUTPUT = "sdk_bank_cycle.png"

if __name__ == "__main__":
    run()
