# Include external libraries
import os
import sys
import RPi.GPIO as GPIO
from time import sleep


# Include custom files
# Add the parent directory to the module search path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from interface_board_pins import ( # pin / channel assignment
    GPIO_PWM1,  # RPI_PWM0
    GPIO_PWM2  # RPI_PWM0 too
)



# Config
BLINK_ONLY = False



# PWM Settings
FREQ = 1000  # PWM frequency in Hz
STEP = 2     # Step size for fading
DELAY = 0.03  # Delay between steps

try:
    print("Configuring PWM pins...")
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(GPIO_PWM1, GPIO.OUT)
    GPIO.setup(GPIO_PWM2, GPIO.OUT)


    if BLINK_ONLY:
        while True:
            print(f"PWM1 ON (GPIO {GPIO_PWM1})")
            GPIO.output(GPIO_PWM1, 1)
            sleep(2)
            print("PWM1 OFF")
            GPIO.output(GPIO_PWM1, 0)
            print(f"PWM2 ON (GPIO {GPIO_PWM2})")
            GPIO.output(GPIO_PWM2, 1)
            sleep(2)
            print("PWM2 OFF")
            GPIO.output(GPIO_PWM2, 0)


    # Initialize PWM on both pins
    pwm1 = GPIO.PWM(GPIO_PWM1, FREQ)
    pwm2 = GPIO.PWM(GPIO_PWM2, FREQ)
    
    pwm1.start(0)  # Start with 0% duty cycle
    pwm2.start(100)  # Start with 100% duty cycle

    print("Starting PWM fade effect...")
    while True:
        # Fade up PWM1 and fade down PWM2
        for duty in range(0, 101, STEP):  # Duty cycle from 0% to 100%
            pwm1.ChangeDutyCycle(duty)
            pwm2.ChangeDutyCycle(100 - duty)  # Opposite fade
            print(f"PWM1: {duty}%  |  PWM2: {100 - duty}%")
            sleep(DELAY)

        # Fade down PWM1 and fade up PWM2
        for duty in range(100, -1, -STEP):  # Duty cycle from 100% to 0%
            pwm1.ChangeDutyCycle(duty)
            pwm2.ChangeDutyCycle(100 - duty)  # Opposite fade
            print(f"PWM1: {duty}%  |  PWM2: {100 - duty}%")
            sleep(DELAY)

finally:
    print("Exiting, stopping PWM and cleaning up...")
    pwm1.stop()
    pwm2.stop()
    GPIO.cleanup()  # Clean up GPIO settings