"""Deflate reported revenue with CPI averaged over the matching fiscal year, rather than comparing mismatched calendar dates.

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 {
        "income": qj.fmp.get_income_statement(symbol="AAPL", period="annual", limit=5),
        "bls_cpi": qj.bls.get_cpi(start_year=2020, end_year=2025, category="all", seasonally_adjusted=True),
    }


def analyze(raw):
    income, cpi = frame(raw["income"]), bls_cpi(raw["bls_cpi"])
    rows = []
    for row in income.to_dict("records"):
        end = row["date"]
        start = end - pd.DateOffset(years=1)
        observations = cpi.loc[(cpi.index > start) & (cpi.index <= end)]
        if len(observations) < 12:
            continue
        rows.append(
            {"Fiscal year": end.year, "Revenue": decimal(row["revenue"]), "CPI": decimal(str(observations.mean()))}
        )
    data = pd.DataFrame(rows).set_index("Fiscal year")
    data["Deflated revenue"] = data["Revenue"] / data["CPI"]
    data["Nominal growth %"] = 100 * change(data["Revenue"])
    data["CPI-adjusted growth %"] = 100 * change(data["Deflated revenue"])
    result = data[["Nominal growth %", "CPI-adjusted growth %"]].dropna()
    if result.empty:
        raise ValueError("Insufficient matching fiscal-year CPI coverage")
    fig, (ax,) = canvas("AAPL · growth after inflation", "Annual revenue growth %")
    x = np.arange(len(result))
    ax.bar(x - 0.18, result.iloc[:, 0], 0.36, label="Nominal")
    ax.bar(x + 0.18, result.iloc[:, 1], 0.36, label="CPI-adjusted")
    ax.set_xticks(x, result.index.astype(str))
    legend(ax)
    return result.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 change(values, periods=1):
    previous = values.shift(periods)
    return pd.Series(
        [ratio(x, y) - 1 if pd.notna(x) and pd.notna(y) else np.nan for x, y in zip(values, previous, strict=True)],
        index=values.index,
    )


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_real_growth.png"

if __name__ == "__main__":
    run()
