import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.linear_model import LinearRegression
from scipy.io.wavfile import read
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]

X_ = np.random.randn(10,784)
w = np.random.rand(10)
W = np.random.rand(784,10)

def cct_chain_validate(X, target, w, entropy_threshold=0.2):
    y = X
    path_entropy = []
    
    for i in range(10):
        # 1. Execute ODE Step (Pay Work)
        y_next = np.sin(w[i] * y)
        
        # 2. Logical Judgment (Entropy Check)
        # Check 1: Boundedness (Stationary Law)
        if np.any(np.abs(y_next) > 1.0):
            return False, "Violation: Unbounded"
        
        # Check 2: Signal Preservation (Probability)
        # If y collapses to ~0 too early, information is lost
        if np.mean(np.abs(y_next)) < 0.01 and i < 8:
            return False, "Violation: Signal Collapse"
        
        # Check 3: Stability (ODE-CCT)
        # Perturb w slightly to check sensitivity
        sensitivity = np.abs(np.sin((w[i] + 0.01) * y) - y_next)
        if np.mean(sensitivity) > 0.5:
            return False, "Violation: Chaotic Sensitivity"
            
        path_entropy.append(np.std(y_next)) # Track entropy
        y = y_next
    
    # 3. Final Target Check (Only if path was logical)
    error = np.mean((y - target) ** 2)
    
    if error < 0.1:
        return True, "Collapsed"
    else:
        return False, "Logical but Missed Target"

def adapt_w_cct(X, target, max_attempts=100):
    w = np.random.rand(10) * 2 * np.pi
    for attempt in range(max_attempts):
        # Sample Weights (Probability)
        
        
        # Validate Trajectory (Stationary Logic)
        valid, reason = cct_chain_validate(X, target, w)
        
        if valid == True:
            return w, "Success"
        elif reason == "Logical but Missed Target":
            # Minimal Bug Fixing: Only tweak final weights
            # Don't restart whole chain
            w[-1] += np.random.randn() * 0.1 
            continue
        else:
            # Reject Entire Chain (High Entropy)
            continue
            
    return None, "Failed to Collapse"
