import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401
from sklearn.decomposition import PCA
from common import load_iris, FEATURES, CLASSES, COLORS, MEDIA

os.makedirs(MEDIA, exist_ok=True)
X, y = load_iris()

plt.rcParams.update({"font.family": ["Arial", "DejaVu Sans"], "font.size": 11})

# PCA on the centered data (sklearn centers internally, no scaling)
pca = PCA(n_components=4)
Z = pca.fit_transform(X)

np.set_printoptions(precision=4, suppress=True)
print("feature means (subtracted by PCA):", pca.mean_)
print()
print("PCA axes (rows of components_, each has norm 1):")
for k in range(4):
    print("  PC%d:" % (k + 1), pca.components_[k],
          " norm: %.4f" % np.linalg.norm(pca.components_[k]))
print()
print("variance along each PC (explained_variance_):", pca.explained_variance_)
print()
print("check, PCs orthogonal (W W^T should be identity):")
print(np.round(pca.components_ @ pca.components_.T, 6) + 0.0)


def save(fig, name):
    path = os.path.join(MEDIA, name)
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    print("saved", path)


# Fig 4: top 1 axis
fig, ax = plt.subplots(figsize=(6.5, 4))
bins = np.linspace(Z[:, 0].min(), Z[:, 0].max(), 21)
for c in range(3):
    ax.hist(Z[y == c, 0], bins=bins, alpha=0.6, color=COLORS[c],
            label=CLASSES[c], edgecolor="white")
ax.set_xlabel("PC1")
ax.set_ylabel("count")
ax.legend(frameon=False, loc="upper right")
fig.tight_layout()
save(fig, "p3_fig4_pc1_histogram.png")

# Fig 5: top 2 axes
fig, ax = plt.subplots(figsize=(6.5, 5))
for c in range(3):
    ax.scatter(Z[y == c, 0], Z[y == c, 1], s=22, color=COLORS[c],
               alpha=0.8, label=CLASSES[c])
ax.set_xlabel("PC1")
ax.set_ylabel("PC2")
ax.grid(alpha=0.25)
ax.legend(frameon=False, loc="lower right")
fig.tight_layout()
save(fig, "p3_fig5_pc1_pc2_scatter.png")

# Fig 6: top 3 axes
fig = plt.figure(figsize=(8, 6.5))
ax = fig.add_subplot(111, projection="3d")
for c in range(3):
    ax.scatter(Z[y == c, 0], Z[y == c, 1], Z[y == c, 2], s=22,
               color=COLORS[c], alpha=0.8, label=CLASSES[c])
ax.set_xlabel("PC1", labelpad=8)
ax.set_ylabel("PC2", labelpad=8)
ax.text2D(1.1, 0.5, "PC3", transform=ax.transAxes, rotation=90,
          va="center", ha="left")
ax.view_init(elev=20, azim=-60)
ax.legend(frameon=False, loc="upper left")
fig.subplots_adjust(left=0.0, right=0.86, bottom=0.05, top=0.98)
save(fig, "p3_fig6_pc1_pc2_pc3_scatter.png")
