import numpy as np
from scipy.io.wavfile import read
from sklearn.cluster import KMeans
from scipy.stats import entropy

# Load training and test data
X_train = read('../X_train.wav')[1].reshape(-1, 784)
y_train = (read('../y_train.wav')[1] * 9).astype(int)
X_test = read('../X_test.wav')[1].reshape(-1, 784)
y_test = (read('../y_test.wav')[1] * 9).astype(int)
X20 = X_test[:1000]
yt20 = y_test[:1000]

# Define the MLP Classifier
class MLPClassifier:
    def __init__(self, input_size, hidden_size, output_size, learning_rate=np.random.rand(4)):
        self.W1 = np.random.randn(input_size, hidden_size) * 0.01
        self.b1 = np.zeros((1, hidden_size))
        self.W2 = np.random.randn(hidden_size, output_size) * 0.01
        self.b2 = np.zeros((1, output_size))
        self.learning_rate = learning_rate
    
    def relu(self, x):
        return np.maximum(0, x)
    
    def relu_derivative(self, x):
        return np.where(x > 0, 1, 0)
    
    def softmax(self, x):
        exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
        return exp_x / np.sum(exp_x, axis=1, keepdims=True)
    
    def forward(self, X):
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = self.relu(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        output = self.softmax(self.z2)
        return output
    
    def compute_loss(self, y_true, y_pred):
        m = y_true.shape[0]
        loss = -np.sum(y_true * np.log(y_pred + 1e-9)) / m
        return loss
    
    def backward(self, X, y_true, y_pred):
        m = y_true.shape[0]
        dz2 = y_pred - y_true
        dW2 = np.dot(self.a1.T, dz2) / m
        db2 = np.sum(dz2, axis=0, keepdims=True) / m
        da1 = np.dot(dz2, self.W2.T)
        dz1 = da1 * self.relu_derivative(self.z1)
        dW1 = np.dot(X.T, dz1) / m
        db1 = np.sum(dz1, axis=0, keepdims=True) / m
        return dW1, db1, dW2, db2
    
    def update(self, X, y_true):
        y_pred = self.forward(X)
        dW1, db1, dW2, db2 = self.backward(X, y_true, y_pred)
        self.W1 -= self.learning_rate[0] * dW1
        self.b1 -= self.learning_rate[1] * db1
        self.W2 -= self.learning_rate[2] * dW2
        self.b2 -= self.learning_rate[3] * db2
    
    def predict(self, X):
        probabilities = self.forward(X)
        return np.argmax(probabilities, axis=1)

    def score(self, X, y_true):
        y = self.predict(X)
        return np.mean(y == y_true)


def sample_signature(x, W, n_ref=5):
    """Return a compact diagnostic signature for a single sample x (1,784)"""
    p = x @ W   # (100,)
    norm_p = np.linalg.norm(p)
    softmax_p = np.exp(p - p.max()) / np.sum(np.exp(p - p.max()))
    ent = entropy(softmax_p)
    mean_p = np.mean(p)
    std_p = np.std(p)
    # reference projections (random vectors fixed after initialization)
    if not hasattr(sample_signature, "refs"):
        sample_signature.refs = np.random.randn(n_ref, 100)
        sample_signature.refs /= np.linalg.norm(sample_signature.refs, axis=1, keepdims=True)
    ref_dots = sample_signature.refs @ p   # (n_ref,)
    return np.array([norm_p, ent, mean_p, std_p] + list(ref_dots))

# Initialize and train the MLP Classifier
learning_rate = np.random.rand(4)
f = MLPClassifier(input_size=784, hidden_size=100, output_size=10, learning_rate=learning_rate)

# --- Initial clustering ---
signatures = np.array([sample_signature(X_train[i], f.W1) for i in range(60000)])
kmeans = KMeans(n_clusters=20, random_state=0).fit(signatures)
cluster_labels = kmeans.labels_

# --- Training loop ---
i = 0
while True:
    # Pick a random cluster (or cycle through them)
    cluster_id = np.random.randint(0, 20)
    # Get all indices in that cluster
    cluster_indices = np.where(cluster_labels == cluster_id)[0]
    # Sample 100 samples from this cluster
    idx = np.random.choice(cluster_indices, 100, replace=False)
    X_batch = X_train[idx]
    y_batch = y_train[idx]
    
    # Optional: recompute diagnostics for this batch (the cluster ensures similarity)
    P = X_batch @ f.W1
    det_val = np.linalg.det(P)
    cond_val = np.linalg.cond(P)
    
    print(i, f"cluster={cluster_id}", f"det={det_val:.3e}", f"cond={cond_val:.2f}")
    f.update(X_batch, np.eye(10)[y_batch])
    i += 1
    
    # Every N iterations, re‑cluster (because W changes)
    if i % 1000 == 0:
        print("Re‑clustering...")
        signatures = np.array([sample_signature(X_train[i], f.W1) for i in range(60000)])
        kmeans = KMeans(n_clusters=20, random_state=0).fit(signatures)
        cluster_labels = kmeans.labels_
