"""Compare filed and expected EPS, then check whether the latest reported short position increased.

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 pandas as pd

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


def fetch(qj):
    return {
        "short": qj.domains.call("equity.shorting.get_short_interest", provider="finra", symbol="AAPL"),
        "income": qj.domains.call(
            "equity.fundamentals.get_income_statement", provider="fmp", symbol="AAPL", period="annual", limit=5
        ),
        "filings": qj.domains.call(
            "regulatory.filings.get_company_filings", provider="sec", symbol="AAPL", form_type="10-K", limit=12
        ),
        "estimates": qj.fmp.get_analyst_estimates(symbol="AAPL", period="annual", limit=8),
    }


def analyze(raw):
    actual = verified_income(raw)
    actual = actual.loc[actual["accepted"].dt.date <= AS_OF]
    estimates = frame(raw["estimates"])
    future = estimates.loc[estimates["date"].dt.date > AS_OF].copy()
    if actual.empty or future.empty:
        raise ValueError("Need verified actual EPS and future analyst estimates")
    baseline = decimal(actual.iloc[-1]["eps"])
    actual["EPS index"] = actual["eps"].map(lambda x: 100 * ratio(x, baseline))
    future["EPS index"] = future["epsAvg"].map(lambda x: 100 * ratio(x, baseline))
    fig, (ax, bottom) = canvas(
        "AAPL · expectations and short positioning", "Latest verified annual EPS = 100", panels=2
    )
    ax.plot(actual["date"], actual["EPS index"], marker="o", label="Filed annual EPS")
    ax.plot(future["date"], future["EPS index"], marker="o", linestyle="--", label="Future consensus EPS")
    ax.axhline(100, color="#afc1dc", lw=0.8)
    legend(ax)
    result = pd.concat(
        [
            actual[["date", "EPS index"]].assign(Observation="Filed"),
            future[["date", "EPS index"]].assign(Observation="Estimate"),
        ]
    )
    short = frame(raw["short"], "settlement_date").iloc[-1]
    short_index = 100 * ratio(short["current_short_position"], short["previous_short_position"])
    bottom.bar(
        ["Prior reported position", "Current reported position"], [100, short_index], color=[BLUE, PINK], width=0.5
    )
    bottom.set_ylabel("Short-position index · prior = 100")
    bottom.set_title("FINRA settlement · " + short["settlement_date"].strftime("%Y-%m-%d"), fontsize=10)
    result["Latest / prior short position %"] = short_index
    return result, 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 verified_income(raw):
    income = frame(raw["income"])
    filings = frame(raw["filings"], "reportDate")
    filings = filings[["reportDate", "acceptanceDateTime", "filingDate"]].copy()
    filings["accepted"] = pd.to_datetime(filings["acceptanceDateTime"], utc=True)
    return income.merge(
        filings[["reportDate", "accepted"]],
        left_on="date",
        right_on="reportDate",
        validate="one_to_one",
    ).sort_values("date")


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()


OUTPUT = "sdk_expectations.png"

if __name__ == "__main__":
    run()
