import board
import time
import digitalio
import neopixel
import busio
import adafruit_lis3dh

# Setup buttons
button_A_pin = digitalio.DigitalInOut(board.BUTTON_A)
button_A_pin.switch_to_input(digitalio.Pull.DOWN)

button_B_pin = digitalio.DigitalInOut(board.BUTTON_B)
button_B_pin.switch_to_input(digitalio.Pull.DOWN)

# Setup NeoPixels with lowered brightness
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.1, auto_write=True)
pixels.fill((0, 0, 0))

# Setup accelerometer
i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1)
accelerometer.range = adafruit_lis3dh.RANGE_8_G

# Variables for card counting and deck math
tally = 0
decks = 6
deck_input = 0
total_cards = 0
remaining_decks = decks

# Mode flags
deck_entry_mode = False

# Timing variables
last_tilt_check = 0
tilt_cooldown = 1.0  # seconds (tilt updates only every 1 second)
last_press_time = 0
press_cooldown = 0.25  # seconds (minimum time between button events)

# Visual parameters for tilt indicator
true_count_action_threshold = 2  # True count at or above which color is green
max_pixel_true_count = 10        # Scaling: maximum true count to map to all 10 pixels

# Button state tracking
prev_a = False
prev_b = False
a_press_time = None
b_press_time = None

# New flag for simultaneous press handling
simultaneous_handled = False

print("Card counting started! Default decks =", decks)

while True:
    now = time.monotonic()
    a = button_A_pin.value
    b = button_B_pin.value

    # Use a press cooldown to avoid rapid re-triggering
    if now - last_press_time < press_cooldown:
        time.sleep(0.01)
        prev_a = a
        prev_b = b
        continue

    # --- Tilt Detection with 1-sec Cooldown ---
    x, y, z = accelerometer.acceleration
    if now - last_tilt_check >= tilt_cooldown:
        if (abs(x) > 4 or abs(y) > 4):
            # Board is tilted
            if remaining_decks > 0:
                true_count = tally / remaining_decks
            else:
                true_count = 0  # avoid division by zero

            print(f"True Count = {true_count:.2f}. Current Tally = {tally}, Remaining Decks = {remaining_decks:.2f}")

            # Clear and update NeoPixels
            pixels.fill((0, 0, 0))
            if true_count >= true_count_action_threshold:
                pixel_color = (0, 255, 0)  # Green: action
            elif true_count >= 0:
                pixel_color = (255, 255, 0)  # Yellow: neutral/small positive
            else:
                pixel_color = (255, 0, 0)    # Red: negative count

            # Map the magnitude of the true count (scaled to max_pixel_true_count) to number of lit pixels (up to 10)
            true_count_magnitude = abs(true_count)
            num_pixels_on = min(10, max(1, int((true_count_magnitude / max_pixel_true_count) * 10)))
            for i in range(num_pixels_on):
                pixels[i] = pixel_color
        else:
            # Board is not tilted: turn off the NeoPixels if they were on
            pixels.fill((0, 0, 0))
        last_tilt_check = now

    # --- DECK ENTRY MODE (only via Button A long hold) ---
    if deck_entry_mode:
        if a:
            press_start = time.monotonic()
            while button_A_pin.value:
                if time.monotonic() - press_start >= 3:
                    decks = deck_input if deck_input > 0 else 6
                    remaining_decks = decks
                    print(f"Deck entry complete. Decks set to: {decks}")
                    pixels.fill((0, 0, 0))
                    for i in range(min(decks, 10)):
                        pixels[i] = (0, 255, 0)
                    time.sleep(1)
                    pixels.fill((0, 0, 0))
                    deck_entry_mode = False
                    deck_input = 0
                    break
            else:
                deck_input += 1
                print(f"Deck count input: {deck_input}")
        # Skip the normal tally handling while in deck entry mode.
        continue

    # --- Button Event Handling (only if not in deck entry mode) ---
    # First, check for simultaneous press (both buttons pressed at the same time)
    if a and b:
        if not simultaneous_handled:
            # Process simultaneous event for -1:
            tally -= 1
            total_cards += 1
            message = "Both pressed: -1"
            remaining_cards = (decks * 52) - total_cards
            remaining_decks = remaining_cards / 52
            print(f"{message}, tally = {tally}, total cards = {total_cards}, remaining decks = {remaining_decks:.2f}")
            last_press_time = now
            simultaneous_handled = True
        # When both are held, do nothing else.
    else:
        # Reset the simultaneous handling flag when not both pressed.
        simultaneous_handled = False

        # Process individual Button A events
        if a and not prev_a:
            a_press_time = now
        elif not a and prev_a:
            if a_press_time:
                duration = now - a_press_time
                if duration >= 3:
                    print("Entering deck entry mode via Button A")
                    deck_entry_mode = True
                    deck_input = 0
                else:
                    # Only process A if B is not pressed (if B were pressed, simultaneous event would have been handled)
                    if not b:
                        tally += 1
                        total_cards += 1
                        message = "A pressed: +1"
                        remaining_cards = (decks * 52) - total_cards
                        remaining_decks = remaining_cards / 52
                        print(f"{message}, tally = {tally}, total cards = {total_cards}, remaining decks = {remaining_decks:.2f}")
                        last_press_time = now
            a_press_time = None

        # Process individual Button B events
        if b and not prev_b:
            b_press_time = now
        elif not b and prev_b:
            if b_press_time:
                duration = now - b_press_time
                if duration >= 3:
                    tally = 0
                    decks = 6
                    deck_input = 0
                    total_cards = 0
                    remaining_decks = decks
                    print("Button B held: tally reset, decks set to 6, total cards = 0, remaining decks = 6.00")
                else:
                    if not a:
                        total_cards += 1
                        remaining_cards = (decks * 52) - total_cards
                        remaining_decks = remaining_cards / 52
                        print(f"B pressed: +0, tally = {tally}, total cards = {total_cards}, remaining decks = {remaining_decks:.2f}")
                last_press_time = now
            b_press_time = None

    prev_a = a
    prev_b = b
    time.sleep(0.01)

