import pygame

# Initialize pygame joystick module
pygame.init()
pygame.joystick.init()

# Check how many controllers are connected
joystick_count = pygame.joystick.get_count()
if joystick_count == 0:
    print("No controller detected!")
    exit()

# Initialize the first joystick
joystick = pygame.joystick.Joystick(0)
joystick.init()

print(f"Detected Controller: {joystick.get_name()}")

try:
    while True:
        pygame.event.pump()  # Process event queue

        # Read axis (joystick) values
        left_stick_x = joystick.get_axis(0)  # Left stick X-axis
        left_stick_y = joystick.get_axis(1)  # Left stick Y-axis
        right_stick_x = joystick.get_axis(2)  # Right stick X-axis
        right_stick_y = joystick.get_axis(3)  # Right stick Y-axis

        # Read button presses
        button_A = joystick.get_button(0)  # A button
        button_B = joystick.get_button(1)  # B button
        button_X = joystick.get_button(2)  # X button
        button_Y = joystick.get_button(3)  # Y button

        print(f"Left Stick: ({left_stick_x:.2f}, {left_stick_y:.2f}) | "
              f"Right Stick: ({right_stick_x:.2f}, {right_stick_y:.2f}) | "
              f"A: {button_A}, B: {button_B}, X: {button_X}, Y: {button_Y}")

except KeyboardInterrupt:
    print("\nExiting...")
    pygame.quit()
