"""
04 — Cumulative POD variance explained vs number of modes.

Fits PCA up to min(n_samples, n_points) modes on the full dataset and
plots the cumulative explained variance curve.
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

from _utils import load_data, PLOTS_DIR


def main():
    _, fields, _, _ = load_data()

    max_modes = min(fields.shape[0], fields.shape[1])
    pca = PCA(n_components=max_modes).fit(fields)
    cumulative = np.cumsum(pca.explained_variance_ratio_)

    print(f"{'Modes':>6}  {'Cum Var (%)':>12}")
    for i in range(min(20, len(cumulative))):
        print(f"{i+1:>6}  {cumulative[i]*100:>12.4f}")

    modes = np.arange(1, len(cumulative) + 1)
    FS = 20
    fig, ax = plt.subplots(figsize=(9, 9))
    ax.plot(modes, cumulative * 100, "o-", color="tab:green",
            linewidth=2, markersize=6)
    ax.set_xlabel(r"Number of POD Modes, $r$", fontsize=FS)
    ax.set_ylabel(r"Cumulative Variance Explained, $\eta_r$ (%)", fontsize=FS)
    ax.tick_params(labelsize=FS - 4)
    ax.set_ylim(None, 101)
    ax.grid(True, alpha=0.3)

    idx_9999 = np.searchsorted(cumulative, 0.9999) + 1
    ax.set_xlim(0, min(idx_9999 + 5, len(cumulative)))

    plt.tight_layout()
    PLOTS_DIR.mkdir(parents=True, exist_ok=True)
    out = PLOTS_DIR / "pod_mode_variance.png"
    plt.savefig(out, dpi=300, bbox_inches="tight")
    print(f"Saved {out}")
    plt.close()


if __name__ == "__main__":
    main()
