"""Traffic channels as a matrix: PCA, correlation/determinant, and AHP-style ranking.

Usage: python analysis_slim.py   (expects traffic-data.csv in the same folder)
"""
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# ── Load data: 10 channels x 6 metrics ──
df = pd.read_csv('traffic-data.csv')
for col in ['Engagement rate', 'Session key event rate']:
    df[col] = df[col].str.rstrip('%').astype(float)

channels = df['Channel'].values
metrics = df.columns[1:].tolist()
X = df[metrics].values.astype(float)


# ── 1. PCA via eigenvalues & eigenvectors ──
Z = (X - X.mean(axis=0)) / X.std(axis=0)          # standardize
cov = np.cov(Z, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals, eigvecs = eigvals[order], eigvecs[:, order]

var_pct = eigvals / eigvals.sum() * 100
cum_pct = np.cumsum(var_pct)
scores = Z @ eigvecs[:, :2]                        # project onto PC1, PC2

print("Variance explained per PC:", np.round(var_pct, 1))
print(pd.DataFrame(eigvecs[:, :3], index=metrics, columns=['PC1', 'PC2', 'PC3']).round(2))

pcs = [f'PC{i+1}' for i in range(len(eigvals))]
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(pcs, var_pct, color='#4C72B0', edgecolor='black', label='Individual %')
ax.plot(pcs, cum_pct, 'ro-', label='Cumulative %')
for i, v in enumerate(var_pct):
    ax.text(i, v + 1, f'{v:.1f}%', ha='center', fontsize=9)
ax.set_ylabel('Variance Explained (%)')
ax.set_title('Scree Plot – Eigenvalue Variance Contribution')
ax.legend()
fig.savefig('pca_scree.png', dpi=150, bbox_inches='tight')
plt.close(fig)

fig, ax = plt.subplots(figsize=(10, 7))
ax.scatter(scores[:, 0], scores[:, 1], c=range(len(channels)), cmap='tab10', s=120, edgecolors='black', zorder=5)
for (x, y), ch in zip(scores, channels):
    ax.annotate(ch, (x, y), xytext=(5, 5), textcoords='offset points', fontsize=9)
for (lx, ly), m in zip(eigvecs[:, :2] * 2.5, metrics):
    ax.annotate('', xy=(lx, ly), xytext=(0, 0), arrowprops=dict(arrowstyle='->', color='red', lw=1.5))
    ax.text(lx * 1.12, ly * 1.12, m, color='red', fontsize=8, ha='center')
ax.axhline(0, color='gray', lw=0.5)
ax.axvline(0, color='gray', lw=0.5)
ax.set_xlabel(f'PC1 ({var_pct[0]:.1f}%)')
ax.set_ylabel(f'PC2 ({var_pct[1]:.1f}%)')
ax.set_title('PCA Biplot – Traffic Channels in Reduced Space')
ax.grid(alpha=0.3)
fig.savefig('pca_biplot.png', dpi=150, bbox_inches='tight')
plt.close(fig)


# ── 2. Correlation matrix, determinant, condition number ──
R = np.corrcoef(X, rowvar=False)
det_R = np.linalg.det(R)
r_eigvals = np.linalg.eigvalsh(R)
cond = r_eigvals.max() / r_eigvals[r_eigvals > 1e-10].min()

print(f"\ndet(R) = {det_R:.6f}   condition number = {cond:,.0f}")
pairs = [(metrics[i], metrics[j], R[i, j]) for i in range(len(metrics)) for j in range(i + 1, len(metrics))]
for a, b, r in sorted(pairs, key=lambda p: -abs(p[2]))[:3]:
    print(f"  {a} <-> {b}: r = {r:+.2f}")

labels = ['Sessions', 'Engaged\nSessions', 'Engagement\nRate', 'Avg Engage\nTime', 'Conversions', 'Key Event\nRate']
fig, ax = plt.subplots(figsize=(9, 7))
im = ax.imshow(R, cmap='RdBu_r', vmin=-1, vmax=1)
ax.set_xticks(range(len(labels)), labels, fontsize=8)
ax.set_yticks(range(len(labels)), labels, fontsize=8)
for i in range(len(R)):
    for j in range(len(R)):
        ax.text(j, i, f'{R[i, j]:.2f}', ha='center', va='center', fontsize=9,
                color='white' if abs(R[i, j]) > 0.5 else 'black')
fig.colorbar(im, ax=ax, shrink=0.8)
ax.set_title(f'Correlation Matrix Heatmap\ndet(R) = {det_R:.6f}')
fig.savefig('correlation_heatmap.png', dpi=150, bbox_inches='tight')
plt.close(fig)


# ── 3. AHP-style ranking via the dominant eigenvector ──
X_norm = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))

def compare(a, b):
    adv, disadv = np.maximum(a - b, 0).sum(), np.maximum(b - a, 0).sum()
    return 9.0 if disadv == 0 else np.clip(adv / disadv, 1 / 9, 9)

n = len(channels)
A = np.array([[1.0 if i == j else compare(X_norm[i], X_norm[j]) for j in range(n)] for i in range(n)])

vals, vecs = np.linalg.eig(A)
top = np.argmax(vals.real)
lam_max = vals.real[top]
weights = np.abs(vecs[:, top].real)
weights /= weights.sum()

CR = ((lam_max - n) / (n - 1)) / 1.49              # Saaty's random index for n = 10
print(f"\nlambda_max = {lam_max:.2f}   consistency ratio = {CR:.3f}")
ranking = pd.Series(weights * 100, index=channels).sort_values(ascending=False)
print(ranking.round(1).to_string())

fig, ax = plt.subplots(figsize=(10, 8))
im = ax.imshow(A, cmap='YlOrRd')
ax.set_xticks(range(n), channels, fontsize=7, rotation=45, ha='right')
ax.set_yticks(range(n), channels, fontsize=7)
for i in range(n):
    for j in range(n):
        ax.text(j, i, f'{A[i, j]:.1f}', ha='center', va='center', fontsize=7)
fig.colorbar(im, ax=ax, shrink=0.8)
ax.set_title(f'Pairwise Comparison Matrix\ndet(A) = {np.linalg.det(A):.4f}')
fig.savefig('comparison_matrix.png', dpi=150, bbox_inches='tight')
plt.close(fig)

fig, ax = plt.subplots(figsize=(10, 6))
asc = ranking.sort_values()
bars = ax.barh(asc.index, asc.values, color=plt.cm.viridis(np.linspace(0.2, 0.9, n)), edgecolor='black')
for bar, v in zip(bars, asc.values):
    ax.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height() / 2, f'{v:.2f}%', va='center', fontsize=9)
ax.set_xlabel('Priority Weight (%)')
ax.set_title('Channel Performance Ranking (Eigen-based AHP Scoring)')
ax.grid(axis='x', alpha=0.3)
fig.savefig('channel_ranking.png', dpi=150, bbox_inches='tight')
plt.close(fig)
