"""Shared helpers for the course "Introduction to Mathematical Statistics", which follows
Larsen, R. J. and Marx, M. L. (2018), An Introduction to Mathematical Statistics and Its Applications,
6th edition, Pearson. Every chapter module (chNN_<topic>.py) imports this file for
* book_data(): data tables typed in from the book, stored in code/data/ (JSON or CSV);
* a common plotting style and colour palette;
* savefig(), which writes ../img/chNN/figN-k.{png,svg,pdf} next to the lecture notes;
* run(), a small command-line driver: python ch05_estimation.py --fig 5.2.1
Figures go to ../img (set MSTAT_OUT, or pass --out, to change this). Python only (no R).
"""
import argparse
import logging
import os
import sys
import time

import numpy as np
import matplotlib

matplotlib.use("Agg")
# fontTools (used to embed fonts in the PDFs) logs a harmless note about font timestamps
logging.getLogger("fontTools").setLevel(logging.ERROR)
import matplotlib.pyplot as plt  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(HERE, "data")
OUT_DIR = os.environ.get("MSTAT_OUT", os.path.normpath(os.path.join(HERE, "..", "img")))

# Colours used throughout, chosen to match the book's red / blue / green figures.
RED = "#d62728"
BLUE = "#1f5fbf"
GREEN = "#2ca02c"
MAGENTA = "#c2185b"
CYAN = "#17becf"
ORANGE = "#ff7f0e"
PURPLE = "#7b4fbf"
GREY = "#7f7f7f"
CLASS_COLOURS = (RED, BLUE, GREEN)


# --------------------------------------------------------------------------- style
def setup_style():
    """A clean, book-like matplotlib style (white background, boxed axes)."""
    plt.rcParams.update({
        "figure.dpi": 100,
        "savefig.dpi": 130,
        "font.size": 10,
        "axes.titlesize": 10.5,
        "axes.labelsize": 10,
        "legend.fontsize": 9,
        "xtick.labelsize": 9,
        "ytick.labelsize": 9,
        "axes.linewidth": 0.8,
        "lines.linewidth": 1.6,
        "figure.facecolor": "white",
        "axes.facecolor": "white",
        "savefig.facecolor": "white",
        "savefig.bbox": "tight",
        "savefig.pad_inches": 0.06,
        "mathtext.fontset": "cm",
        "svg.hashsalt": "mstat-repro",   # stable ids, so re-running gives identical SVG files
        "pdf.fonttype": 42,             # embed TrueType fonts: the PDFs stay editable in Illustrator/Inkscape
    })


setup_style()


def panel_grid(nrows, ncols, size=(2.6, 2.4), **kw):
    """fig, axes for a grid of equally sized panels (axes is always 2-D)."""
    fig, axes = plt.subplots(nrows, ncols, figsize=(size[0] * ncols, size[1] * nrows), squeeze=False, **kw)
    return fig, axes


def panel_label(ax, label, loc="upper left"):
    """Write (a), (b), ... inside a panel, as in the book."""
    x, ha = (0.03, "left") if "left" in loc else (0.97, "right")
    y, va = (0.97, "top") if "upper" in loc else (0.03, "bottom")
    ax.text(x, y, "(%s)" % label, transform=ax.transAxes, ha=ha, va=va, fontsize=10,
            bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=0.8))


def savefig(fig, chapter, name, out_dir=None, formats=("png", "svg", "pdf")):
    """Save fig as <out_dir>/chNN/<name>.png, .svg and .pdf and return the PNG path.

    name is the figure id in the book with a dash, e.g. 'fig3-8' for Figure 3.8.
    The SVG is what the web pages show (sharp at any zoom); the PDF is for slides
    and papers; the PNG is a light fallback and the thumbnail in the code gallery.
    """
    out = os.path.join(out_dir or OUT_DIR, "ch%02d" % int(chapter))
    os.makedirs(out, exist_ok=True)
    paths = {}
    for ext in formats:
        path = os.path.join(out, name + "." + ext)
        meta = {"Date": None} if ext in ("svg", "pdf") else None   # no timestamps: reproducible files
        if ext == "pdf":
            meta["CreationDate"] = None
            del meta["Date"]
        fig.savefig(path, metadata=meta)
        paths[ext] = path
    plt.close(fig)
    print("wrote", os.path.relpath(paths.get("png", next(iter(paths.values()))), os.getcwd()), "(+ " + ", ".join(e for e in formats if e != "png") + ")")
    return paths.get("png")


# --------------------------------------------------------------------------- data
def book_data(name):
    """Load a data table typed in from the book (Larsen and Marx 2018 prints its data in the text).

    Tables live in code/data/<name>.json (a dict or list) or code/data/<name>.csv (pandas DataFrame).
    Typing a table in is fine (data are facts); cite the book's case study or example number where it is used.
    """
    j = os.path.join(DATA_DIR, name + ".json")
    if os.path.exists(j):
        import json
        with open(j, encoding="utf-8") as f:
            return json.load(f)
    import pandas as pd
    return pd.read_csv(os.path.join(DATA_DIR, name + ".csv"))


def logsumexp(a, axis=None, keepdims=False):
    a = np.asarray(a, dtype=float)
    m = np.max(a, axis=axis, keepdims=True)
    m = np.where(np.isfinite(m), m, 0.0)
    s = np.log(np.sum(np.exp(a - m), axis=axis, keepdims=True)) + m
    return s if keepdims else np.squeeze(s, axis=axis) if axis is not None else s.item()


def gauss_logpdf(X, mu, Sigma):
    """log N(x | mu, Sigma) for each row of X."""
    X = np.atleast_2d(X)
    D = X.shape[1]
    L = np.linalg.cholesky(Sigma)
    Z = np.linalg.solve(L, (X - mu).T)
    return -0.5 * (D * np.log(2 * np.pi) + 2 * np.log(np.diag(L)).sum() + (Z ** 2).sum(0))


def ellipse_xy(mu, Sigma, nsd=1.0, n=200):
    """Points on the nsd-standard-deviation contour of N(mu, Sigma) in 2-D."""
    vals, vecs = np.linalg.eigh(Sigma)
    t = np.linspace(0, 2 * np.pi, n)
    circ = np.stack([np.cos(t), np.sin(t)])
    pts = vecs @ (np.sqrt(np.maximum(vals, 0))[:, None] * circ) * nsd
    return pts[0] + mu[0], pts[1] + mu[1]


def sigmoid(a):
    return 0.5 * (1.0 + np.tanh(0.5 * np.asarray(a, dtype=float)))



# --------------------------------------------------------------------------- PyTorch
# --------------------------------------------------------------------------- driver
def run(figures, chapter, argv=None):
    """Command-line driver shared by the chapter modules.

    figures maps the book's figure number ('3.8') to a function f(out_dir) that
    builds and saves that figure. With no --fig option every figure is made.
    """
    p = argparse.ArgumentParser(description="Reproduce Larsen and Marx (2018) Chapter %d figures." % chapter)
    p.add_argument("--fig", nargs="*", help="figure numbers, e.g. 3.8 3.10 (default: all)")
    p.add_argument("--out", default=None, help="output folder (default: ../img)")
    p.add_argument("--list", action="store_true", help="list the reproducible figures")
    a = p.parse_args(argv)
    if a.list:
        for k, f in figures.items():
            print(k, "-", (f.__doc__ or "").strip().split("\n")[0])
        return
    keys = a.fig or list(figures)
    for k in keys:
        if k not in figures:
            sys.exit("unknown figure %s; use --list" % k)
        t0 = time.time()
        figures[k](a.out)
        print("  Figure %s done in %.1f s" % (k, time.time() - t0))
