#!/usr/bin/env python3
"""
Three-Way Traffic Light Controller (Sequential Operation)
=========================================================
Controls traffic lights where each direction gets its own
dedicated green phase in sequence: A → B → C → repeat

Circuit:
--------
Direction A: Red=GPIO2, Amber=GPIO3, Green=GPIO4
Direction B: Red=GPIO17, Amber=GPIO27, Green=GPIO22
Direction C: Red=GPIO10, Amber=GPIO9, Green=GPIO11

Logic:
------
- Each direction gets exclusive green time
- Others remain red during each phase
- All-red safety buffers between all changes
- Useful for complex junctions or when turning movements conflict

Author: Based on gpiozero documentation
"""

from gpiozero import TrafficLights
from time import sleep

# Define the three sets of traffic lights
lights_a = TrafficLights(2, 3, 4)     # Direction A
lights_b = TrafficLights(17, 27, 22)  # Direction B
lights_c = TrafficLights(10, 9, 11)   # Direction C

# Timing constants (in seconds)
GREEN_TIME = 8
AMBER_TIME = 3
ALL_RED_TIME = 2
RED_AMBER_TIME = 2

def set_lights(lights, red=False, amber=False, green=False):
    """
    Set the state of a traffic light set.
    
    Args:
        lights: TrafficLights object
        red: Boolean for red light
        amber: Boolean for amber light
        green: Boolean for green light
    """
    lights.red.value = red
    lights.amber.value = amber
    lights.green.value = green

def give_green_to(direction_name, active_lights, other_lights_list):
    """
    Give green light to one direction while keeping others red.
    
    Args:
        direction_name: String name for logging
        active_lights: TrafficLights object to give green
        other_lights_list: List of other TrafficLights to keep red
    """
    # Red+Amber phase
    print(f"Phase: {direction_name}=Red+Amber, Others=Red")
    set_lights(active_lights, red=True, amber=True)
    for lights in other_lights_list:
        set_lights(lights, red=True)
    sleep(RED_AMBER_TIME)
    
    # Green phase
    print(f"Phase: {direction_name}=Green, Others=Red")
    set_lights(active_lights, green=True)
    for lights in other_lights_list:
        set_lights(lights, red=True)
    sleep(GREEN_TIME)
    
    # Amber phase
    print(f"Phase: {direction_name}=Amber, Others=Red")
    set_lights(active_lights, amber=True)
    for lights in other_lights_list:
        set_lights(lights, red=True)
    sleep(AMBER_TIME)
    
    # All red phase (safety buffer)
    print(f"Phase: All=Red (safety buffer)")
    set_lights(active_lights, red=True)
    for lights in other_lights_list:
        set_lights(lights, red=True)
    sleep(ALL_RED_TIME)

def main():
    """
    Main traffic light control loop for three-way sequential operation.
    """
    print("Three-Way Traffic Light Controller (Sequential Operation)")
    print("=========================================================")
    print("Press Ctrl+C to stop")
    print()
    print("Sequence: A → B → C → repeat")
    print("Each direction gets exclusive green time")
    print()
    
    # Initialize: All red
    set_lights(lights_a, red=True)
    set_lights(lights_b, red=True)
    set_lights(lights_c, red=True)
    sleep(2)
    
    try:
        cycle = 0
        while True:
            cycle += 1
            print(f"\n{'=' * 50}")
            print(f"CYCLE {cycle}")
            print('=' * 50)
            
            # Direction A gets green
            print("\n[Direction A Phase]")
            give_green_to("A", lights_a, [lights_b, lights_c])
            
            # Direction B gets green
            print("\n[Direction B Phase]")
            give_green_to("B", lights_b, [lights_a, lights_c])
            
            # Direction C gets green
            print("\n[Direction C Phase]")
            give_green_to("C", lights_c, [lights_a, lights_b])
    
    except KeyboardInterrupt:
        print("\n\nShutting down...")
        # Turn all lights off
        lights_a.off()
        lights_b.off()
        lights_c.off()
        print("All lights off. Goodbye!")

if __name__ == "__main__":
    main()
