import numpy as np
from PIL import Image

def get_G():
    img = Image.open("output2g.png").convert("L")
    P = (np.array(img) < 128).astype(np.uint8)
    return P

def simulate_competitive(P, num_errors):
    N_data = 16384
    N_parity = 2048
    
    error_idx = list(np.random.choice(N_data, num_errors, replace=False))
    synd = np.zeros(N_parity, dtype=np.uint8)
    for i in error_idx:
        synd ^= P[i]
    
    corrected = []
    print(f"Starting competitive flip for {num_errors} errors...")
    
    for iteration in range(num_errors + 5):
        if np.sum(synd) == 0:
            print("Syndrome is zero! All errors corrected.")
            return True
            
        # Calculate scores for all bits
        # Score = popcount(S & H_j) - 0.5 * popcount(H_j)?
        # Actually, let's use the correlation check.
        scores = []
        for i in range(N_data):
            # Intersection score
            score = np.sum(np.logical_and(synd, P[i]))
            scores.append(score)
            
        best_bit = np.argmax(scores)
        max_score = scores[best_bit]
        
        # Check if flipping best_bit reduces weight
        new_synd = synd ^ P[best_bit]
        if np.sum(new_synd) < np.sum(synd):
            synd = new_synd
            corrected.append(best_bit)
            print(f"  Iteration {iteration}: Flipped bit {best_bit} (Score {max_score}, Weight {np.sum(synd)})")
        else:
            print(f"  Iteration {iteration}: Best bit {best_bit} (Score {max_score}) DOES NOT reduce weight. Stopping.")
            break
            
    success = set(corrected) == set(error_idx)
    print(f"Final Success: {success}")
    return success

if __name__ == "__main__":
    P = get_G()
    simulate_competitive(P, 5)
