import numpy as np
from scipy.io.wavfile import read

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

class AtomicMLPClassifier:
    def __init__(self, input_size, shell_size, core_size, output_size, learning_rate=None):
        if learning_rate is None:
            self.learning_rate = np.random.rand(6) # Extended for 6 parameters (3 weights, 3 biases)
        else:
            self.learning_rate = learning_rate
            
        # 1. Surface to Outer Shell
        self.W_shell = np.random.randn(input_size, shell_size) * 0.01
        self.b_shell = np.zeros((1, shell_size))
        
        # 2. Outer Shell to Core (Inward collapse)
        self.W_core = np.random.randn(shell_size, core_size) * 0.01
        self.b_core = np.zeros((1, core_size))
        
        # 3. Core back to Outer Shell (Outward radiation) / Output
        self.W_out = np.random.randn(core_size, output_size) * 0.01
        self.b_out = np.zeros((1, output_size))
    
    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):
        # Step 1: Input touches the outer shell
        self.z_shell = np.dot(X, self.W_shell) + self.b_shell
        self.a_shell = self.relu(self.z_shell)
        
        # Step 2: Moves into the core
        self.z_core = np.dot(self.a_shell, self.W_core) + self.b_core
        self.a_core = self.relu(self.z_core)
        
        # Step 3: Radiates back out to calculate probabilities
        self.z_out = np.dot(self.a_core, self.W_out) + self.b_out
        output = self.softmax(self.z_out)
        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]
        
        # Output Layer Gradients
        dz_out = y_pred - y_true
        dW_out = np.dot(self.a_core.T, dz_out) / m
        db_out = np.sum(dz_out, axis=0, keepdims=True) / m
        
        # Backprop through Core
        da_core = np.dot(dz_out, self.W_out.T)
        dz_core = da_core * self.relu_derivative(self.z_core)
        dW_core = np.dot(self.a_shell.T, dz_core) / m
        db_core = np.sum(dz_core, axis=0, keepdims=True) / m
        
        # Backprop through Shell
        da_shell = np.dot(dz_core, self.W_core.T)
        dz_shell = da_shell * self.relu_derivative(self.z_shell)
        dW_shell = np.dot(X.T, dz_shell) / m
        db_shell = np.sum(dz_shell, axis=0, keepdims=True) / m
        
        return dW_shell, db_shell, dW_core, db_core, dW_out, db_out
    
    def update(self, X, y_true):
        y_pred = self.forward(X)
        dW_shell, db_shell, dW_core, db_core, dW_out, db_out = self.backward(X, y_true, y_pred)
        
        # Gradient descent using our independent parameter learning rates
        self.W_shell -= self.learning_rate[0] * dW_shell
        self.b_shell -= self.learning_rate[1] * db_shell
        self.W_core  -= self.learning_rate[2] * dW_core
        self.b_core  -= self.learning_rate[3] * db_core
        self.W_out   -= self.learning_rate[4] * dW_out
        self.b_out   -= self.learning_rate[5] * db_out
    
    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 Atomic Classifier
if __name__ == "__main__":
    learning_rate = np.random.rand(6)
    
    # input_size=784 (pixels/features)
    # shell_size=128 (the electron valence boundary layer)
    # core_size=32   (the compressed processing nucleus)
    # output_size=10 (the classification target)
    f = AtomicMLPClassifier(input_size=784, shell_size=128, core_size=32, output_size=10, learning_rate=learning_rate)

    i = 0
    while True:
        idx = np.random.randint(0, 60000, 100)
        X = X_train[idx]
        yt = y_train[idx]
        print(f"Iteration {i} | Train Accuracy: {f.score(X, yt):.4f}")
        f.update(X, np.eye(10)[yt])
        i += 1