"""Static matplotlib pie chart of SPX 11 GICS sectors.

Use this when you need a PNG (e.g. for a slide deck or PDF report).
For interactive use, the web dashboard at web/sectors.html is richer.

Reuses SECTORS / _live_trailing_pe from web.generate_sectors_data so
weights and reference forward P/Es stay in one place.

Outputs:
  - output/sector_breakdown/spx_sector_pie.png
  - output/sector_breakdown/spx_sector_table.csv
"""

from __future__ import annotations

from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

from .generate_sectors_data import SECTORS, _live_trailing_pe


REPO_ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = REPO_ROOT / "output" / "sector_breakdown"


def build_table() -> pd.DataFrame:
    rows = []
    for s in SECTORS:
        trailing_pe = _live_trailing_pe(s["etf"])
        rows.append(
            {
                "sector": s["sector"],
                "etf": s["etf"],
                "weight_pct": s["weight_pct"],
                "trailing_pe": trailing_pe,
                "forward_pe": s["forward_pe"],
                "industries": " | ".join(name for name, _pct in s["industries"]),
            }
        )
    return pd.DataFrame(rows).sort_values("weight_pct", ascending=False).reset_index(drop=True)


def plot_pie(df: pd.DataFrame, out_path: Path) -> None:
    fig, ax = plt.subplots(figsize=(13, 9))
    palette = plt.get_cmap("tab20").colors[: len(df)]

    wedges, _texts, _autotexts = ax.pie(
        df["weight_pct"],
        labels=None,
        colors=palette,
        startangle=90,
        counterclock=False,
        autopct=lambda p: f"{p:.1f}%" if p >= 3.0 else "",
        pctdistance=0.72,
        wedgeprops={"edgecolor": "white", "linewidth": 1.2},
        textprops={"fontsize": 10, "color": "white", "weight": "bold"},
    )

    legend_labels = [
        f"{r['sector']:<24s}  {r['etf']:<5s}  weight {r['weight_pct']:>5.1f}%   fwd P/E {r['forward_pe']:>5.1f}"
        for _, r in df.iterrows()
    ]
    ax.legend(
        wedges,
        legend_labels,
        title="GICS Sector  /  ETF  /  weight  /  forward P/E",
        loc="center left",
        bbox_to_anchor=(1.02, 0.5),
        fontsize=10,
        title_fontsize=11,
        frameon=False,
        prop={"family": "monospace"},
    )
    ax.set_title(
        "S&P 500 - GICS Sector Weights & Forward P/E\n"
        "(weights: 2026-Q1 SPX snapshot;  trailing P/E live from yfinance;  "
        "fwd P/E from Yardeni / FactSet 2026-Q1 public releases)",
        fontsize=12,
        pad=18,
    )
    plt.tight_layout()
    plt.savefig(out_path, dpi=140, bbox_inches="tight")
    plt.close(fig)


def main() -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    df = build_table()

    csv_path = OUT_DIR / "spx_sector_table.csv"
    df.to_csv(csv_path, index=False)

    png_path = OUT_DIR / "spx_sector_pie.png"
    plot_pie(df, png_path)

    print("=" * 100)
    print("S&P 500 - GICS Sectors (2026-Q1 snapshot)")
    print("=" * 100)
    show = df[["sector", "etf", "weight_pct", "trailing_pe", "forward_pe"]].copy()
    show.columns = ["sector", "etf", "weight%", "trailing_PE", "forward_PE"]
    print(show.to_string(index=False, float_format=lambda x: f"{x:.2f}"))
    print()
    print(f"saved: {png_path}")
    print(f"saved: {csv_path}")


if __name__ == "__main__":
    main()
