#!/usr/bin/env python3
"""
Buzzer Test Script for reTerminal DM4
Tests various buzzer patterns and functions
"""

import subprocess
import time
import sys

BUZZER_PATH = '/sys/class/leds/usr-buzzer/brightness'

def buzzer_on():
    """Turn buzzer ON"""
    subprocess.run(['sudo', 'tee', BUZZER_PATH], 
                  input='1', text=True, 
                  stdout=subprocess.DEVNULL, 
                  stderr=subprocess.DEVNULL)

def buzzer_off():
    """Turn buzzer OFF"""
    subprocess.run(['sudo', 'tee', BUZZER_PATH], 
                  input='0', text=True, 
                  stdout=subprocess.DEVNULL, 
                  stderr=subprocess.DEVNULL)

def beep(duration=0.2):
    """Play a single beep"""
    buzzer_on()
    time.sleep(duration)
    buzzer_off()

def blink(count=3, on_time=0.1, off_time=0.1):
    """Blink buzzer multiple times"""
    for _ in range(count):
        buzzer_on()
        time.sleep(on_time)
        buzzer_off()
        time.sleep(off_time)

def get_status():
    """Get current buzzer status"""
    try:
        result = subprocess.run(['cat', BUZZER_PATH], 
                              capture_output=True, text=True, check=True)
        return 'ON' if result.stdout.strip() in ['1', '255'] else 'OFF'
    except:
        return 'UNKNOWN'

def main():
    print("=" * 50)
    print("  reTerminal DM4 Buzzer Test Script (Python)")
    print("=" * 50)
    print()
    
    # Test 1: Single beep
    print("Test 1: Single beep (0.2s)")
    beep(0.2)
    time.sleep(0.5)
    
    # Test 2: Double beep
    print("Test 2: Double beep")
    blink(2, 0.1, 0.1)
    time.sleep(0.5)
    
    # Test 3: Triple beep
    print("Test 3: Triple beep")
    blink(3, 0.1, 0.1)
    time.sleep(0.5)
    
    # Test 4: Long beep
    print("Test 4: Long beep (0.5s)")
    beep(0.5)
    time.sleep(0.5)
    
    # Test 5: Rapid beeps
    print("Test 5: Rapid beeps (5x)")
    blink(5, 0.05, 0.05)
    time.sleep(0.5)
    
    # Test 6: Slow beeps
    print("Test 6: Slow beeps (3x)")
    blink(3, 0.3, 0.3)
    time.sleep(0.5)
    
    # Test 7: Success pattern
    print("Test 7: Success pattern (2 short)")
    blink(2, 0.1, 0.1)
    time.sleep(0.5)
    
    # Test 8: Error pattern
    print("Test 8: Error pattern (3 fast)")
    blink(3, 0.05, 0.05)
    time.sleep(0.5)
    
    # Ensure buzzer is off
    buzzer_off()
    
    print()
    print("=" * 50)
    print("  Buzzer test complete!")
    print("=" * 50)
    print()
    print(f"Current buzzer status: {get_status()}")

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\n\nTest interrupted by user")
        buzzer_off()
        sys.exit(0)
    except Exception as e:
        print(f"\n\nError: {e}")
        buzzer_off()
        sys.exit(1)
