import numpy as np
from scipy.io.wavfile import read, write
import ffmpegio
from time import sleep


# 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).flatten()
X_test = read('../X_test.wav')[1].reshape(-1, 784)
y_test = (read('../y_test.wav')[1] * 9).astype(int).flatten()
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)

# 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)

import numpy as np
from scipy.linalg import svdvals

def diagnostics(P):
    """Return a dict of diagnostic values for batch projection P (100x100)"""
    s = svdvals(P)
    cond = s.max() / (s.min() + 1e-12)
    rank = np.sum(s > 1e-8)
    det = np.linalg.det(P)
    col_sums = np.sum(P, axis=0)
    col_imbalance = np.std(col_sums) / (np.mean(col_sums) + 1e-12)
    row_sums = np.sum(P, axis=1)
    row_imbalance = np.std(row_sums) / (np.mean(row_sums) + 1e-12)
    diag_mean = np.mean(np.abs(np.diag(P)))
    return {
        'cond': cond, 'rank': rank, 'det': det,
        'col_imb': col_imbalance, 'row_imb': row_imbalance,
        'diag_mean': diag_mean
    }

# Running quantiles from recent history
history = {k: [] for k in ['cond','rank','det','col_imb','row_imb','diag_mean']}
low_q, high_q = 0.05, 0.95

i = 0
while True:
    idx = np.random.randint(0, 60000, 100)
    X = X_train[idx]
    yt = y_train[idx]
    P = X @ f.W1
    diag = diagnostics(P)
    
    # Store and update quantiles every 100 batches
    for k, v in diag.items():
        history[k].append(v)
    if i % 100 == 0 and len(history['cond']) > 100:
        quantiles = {k: (np.quantile(history[k][-1000:], low_q),
                         np.quantile(history[k][-1000:], high_q)) for k in history}
    else:
        quantiles = None
    
    # Train if any diagnostic is extreme
    train_this = False
    if quantiles is not None:
        for k, v in diag.items():
            low, high = quantiles[k]
            if v < low or v > high:
                train_this = True
                break
    else:
        train_this = True   # initial phase
    
    if train_this:
        print(i, f.score(X,yt), diag['cond'], diag['rank'])
        f.update(X, np.eye(10)[yt])
    i += 1
