import numpy as np
from itertools import product

# Parameters
learning_rate = 0.1
max_iterations = 1000

# Activation function: Simple thresholding
def activation_function(weighted_sum, lower_threshold=0.8, upper_threshold=1.2):
    return 1 if lower_threshold < weighted_sum < upper_threshold else 0

# Inputs for the two-variable logic tables
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])

# Generate all 16 possible truth tables for 2 inputs
all_truth_tables = list(product([0, 1], repeat=4))  # 16 combinations of binary outputs

# Train the network for each truth table
for truth_table_idx, targets in enumerate(all_truth_tables):
    print(f"\nTraining for Truth Table {truth_table_idx + 1}: {targets}")

    # Initialize weights for fully connected network
    weights_N1_to_N3 = np.random.rand()  # Weight from N1 to N3
    weights_N2_to_N3 = np.random.rand()  # Weight from N2 to N3
    weights_N1_to_N4 = np.random.rand()  # Weight from N1 to N4
    weights_N2_to_N4 = np.random.rand()  # Weight from N2 to N4
    weights_N3_to_N4 = np.random.rand()  # Weight from N3 to N4

    epoch = 0
    network_trained = False

    while epoch < max_iterations:
        epoch += 1
        all_correct = True  # Flag to track if all outputs are correct

        for input_vector, target in zip(inputs, targets):
            N1, N2 = input_vector  # Input neurons

            # Forward pass
            N3_input = N1 * weights_N1_to_N3 + N2 * weights_N2_to_N3
            N3 = activation_function(N3_input)  # Output of N3

            N4_input = (N1 * weights_N1_to_N4 +
                        N2 * weights_N2_to_N4 +
                        N3 * weights_N3_to_N4)
            N4 = activation_function(N4_input)  # Output of N4 (final output)

            # Error calculation
            error = target - N4

            # Backpropagation and weight updates
            if error != 0:
                all_correct = False

                # Update weights connecting to N4
                weights_N1_to_N4 += learning_rate * error * N1
                weights_N2_to_N4 += learning_rate * error * N2
                weights_N3_to_N4 += learning_rate * error * N3

                # Update weights connecting to N3
                weights_N1_to_N3 += learning_rate * error * N1
                weights_N2_to_N3 += learning_rate * error * N2

        if all_correct:
            network_trained = True
            break  # Stop training if all outputs are correct

    # Print results for the truth table
    if network_trained:
        print(f"The network learned the truth table correctly after {epoch} iterations.")
    else:
        print(f"The network failed to learn the truth table after {epoch} iterations.")

    # Test the trained network
    print("\nTesting the trained network:")
    for input_vector, target in zip(inputs, targets):
        N1, N2 = input_vector

        # Forward pass
        N3_input = N1 * weights_N1_to_N3 + N2 * weights_N2_to_N3
        N3 = activation_function(N3_input)

        N4_input = (N1 * weights_N1_to_N4 +
                    N2 * weights_N2_to_N4 +
                    N3 * weights_N3_to_N4)
        N4 = activation_function(N4_input)

        print(f"Input: {input_vector}, Target: {target}, Output: {N4}")
    print("-----------------------------------------------------------")
