"""Combine a common institutional filer’s three-stock holdings sample with report-date trading volume and peer ownership.

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):
    raw = {
        "book_prices": qj.eod.get_historical_prices(
            symbols=["AAPL", "MSFT", "NVDA"], start_date="2025-01-01", end_date="2025-12-31", frequency="1d"
        )
    }
    for symbol, key in [("AAPL", "holders"), ("MSFT", "holders_msft"), ("NVDA", "holders_nvda")]:
        raw[key] = qj.fmp.get_institutional_holders(symbol=symbol, year=2025, quarter=3, limit=100)
    return raw


def analyze(raw):
    result = selected_filing_book(raw).sort_values("Exit days at 10% ADV")
    fig, (top, bottom) = canvas("Crowding and exit liquidity · reported holdings", "", panels=2)
    top.barh(result["Symbol"], result["Exit days at 10% ADV"], color=BLUE)
    top.set_xlabel("Scenario days · position / (10% × trailing ADV)")
    top.set_title("Selected filer CIK " + result["CIK"].iloc[0], loc="left", color="#e9eef8", fontsize=11)
    bottom.barh(result["Symbol"], result["Reported peer shares / ADV"], color=PINK)
    bottom.set_xlabel("Other returned holders’ shares / trailing ADV")
    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 history(response, symbol, adjusted=True):
    values = payload(response)
    if not isinstance(values, dict) or symbol not in values:
        raise ValueError(f"No price coverage for {symbol}")
    result = frame(values[symbol]).set_index("date")
    field = "adjusted_close" if adjusted else "close"
    result["price"] = result[field].map(decimal)
    result["volume"] = result["volume"].map(decimal)
    if result.index.has_duplicates:
        raise ValueError("Duplicate trading dates")
    return result


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 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 selected_filing_book(raw):
    books = {}
    for symbol, key in [("AAPL", "holders"), ("MSFT", "holders_msft"), ("NVDA", "holders_nvda")]:
        book = frame(raw[key])
        book = book.loc[(book["sharesType"] == "SH") & (book["putCallShare"] == "Share")].copy()
        book["CIK"] = book["cik"].astype(str).str.zfill(10)
        book["filingDate"] = pd.to_datetime(book["filingDate"], utc=True)
        book = book.sort_values("filingDate").drop_duplicates(["CIK", "date"], keep="last")
        books[symbol] = book
    common = set.intersection(*(set(book["CIK"]) for book in books.values()))
    if not common:
        raise ValueError("No common filer across the three returned holdings samples")
    selected = min(common)
    rows = []
    for symbol, book in books.items():
        observations = book.loc[book["CIK"] == selected]
        if len(observations) != 1:
            raise ValueError("Ambiguous filing position")
        position = observations.iloc[0]
        prices = history(raw["book_prices"], symbol)
        volume = prices.loc[prices.index <= position["date"], "volume"].tail(20)
        if len(volume) != 20:
            raise ValueError("Need 20 sessions before the holdings date")
        adv = sum(volume, Decimal(0)) / Decimal(20)
        if adv <= 0:
            raise ValueError("Average volume must be positive")
        participation = Decimal("0.10")  # Explicit execution scenario, not observed trading capacity.
        rows.append(
            {
                "Symbol": symbol,
                "CIK": selected,
                "Holdings date": position["date"],
                "Filing date": position["filingDate"],
                "Exit days at 10% ADV": ratio(position["sharesNumber"], adv * participation),
                "Reported peer shares / ADV": ratio(
                    sum(book["sharesNumber"].map(decimal), Decimal(0)) - decimal(position["sharesNumber"]), adv
                ),
            }
        )
    result = pd.DataFrame(rows)
    if result["Holdings date"].nunique() != 1:
        raise ValueError("Holdings dates differ")
    return result


OUTPUT = "sdk_crowded_exit.png"

if __name__ == "__main__":
    run()
