from machine import Pin
import time

# Define button pins (GPIO 34 and 35 are good input pins)
entrance_button = Pin(34, Pin.IN, Pin.PULL_DOWN)  # GPIO 34 with pull-down
exit_button = Pin(35, Pin.IN, Pin.PULL_DOWN)      # GPIO 35 with pull-down

# Define LED pins (using recommended stable digital output pins)
led_pins = [2, 4, 5, 13, 14, 16, 17, 18]
leds = [Pin(pin, Pin.OUT) for pin in led_pins]

# Initialize car counter
car_count = 0
max_cars = 8

# Button state tracking
entrance_last_state = 0
exit_last_state = 0
last_entrance_time = 0
last_exit_time = 0
debounce_time = 300  # milliseconds

def update_leds():
    """Update LEDs to show current car count"""
    print(f"Updating LEDs - Car count: {car_count}")
    for i in range(8):
        if i < car_count:
            leds[i].on()
            print(f"LED {i+1} ON")
        else:
            leds[i].off()
            print(f"LED {i+1} OFF")

def handle_entrance():
    """Handle entrance button press"""
    global car_count
    if car_count < max_cars:
        car_count += 1
        print(f"🚗 Car entered! Current count: {car_count}")
        update_leds()
    else:
        print("🚫 Parking full! Cannot add more cars.")

def handle_exit():
    """Handle exit button press"""
    global car_count
    if car_count > 0:
        car_count -= 1
        print(f"🚗 Car exited! Current count: {car_count}")
        update_leds()
    else:
        print("❌ No cars to exit! Count is already 0.")

# Initialize system
print("🚦 Traffic Monitoring System Started")
print("📍 Entrance button: GPIO 34 (Green)")
print("📍 Exit button: GPIO 35 (Red)")
print("💡 8 LEDs will show car count")
print("-" * 40)

# Initialize LEDs (all off)
update_leds()
print(f"🔢 Initial car count: {car_count}")
print("✅ System ready! Press buttons to test...")

# Main loop
while True:
    current_time = time.ticks_ms()
    
    # Read current button states
    entrance_current = entrance_button.value()
    exit_current = exit_button.value()
    
    # Debug: Print button states every 2 seconds
    if current_time % 2000 < 50:  # Print roughly every 2 seconds
        print(f"🔍 Debug - Entrance: {entrance_current}, Exit: {exit_current}")
    
    # Handle entrance button (detect rising edge)
    if entrance_current == 1 and entrance_last_state == 0:
        if time.ticks_diff(current_time, last_entrance_time) > debounce_time:
            print("🟢 Entrance button pressed!")
            handle_entrance()
            last_entrance_time = current_time
    
    # Handle exit button (detect rising edge)
    if exit_current == 1 and exit_last_state == 0:
        if time.ticks_diff(current_time, last_exit_time) > debounce_time:
            print("🔴 Exit button pressed!")
            handle_exit()
            last_exit_time = current_time
    
    # Update button states
    entrance_last_state = entrance_current
    exit_last_state = exit_current
    
    # Small delay
    time.sleep_ms(50)