"""
Happy Frog - Xiao RP2040 Device Template

This template provides a foundation for running Happy Frog Scripts
on a Seeed Studio Xiao RP2040 microcontroller with CircuitPython.

Hardware Requirements:
- Seeed Studio Xiao RP2040
- USB-C cable for programming and power
- CircuitPython firmware installed

Setup Instructions:
1. Install CircuitPython on your Xiao RP2040
2. Install required libraries via CircuitPython Library Manager:
   - adafruit_hid
3. Copy this template to your device as code.py
4. Replace the main() function with your generated code

Author: ZeroDumb
License: GNU GPLv3
"""

import time

# Conditional imports for CircuitPython modules
try:
    import usb_hid
    from adafruit_hid.keyboard import Keyboard
    from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
    from adafruit_hid.keycode import Keycode
    
    # Initialize HID devices
    # This creates a virtual keyboard that the computer recognizes
    keyboard = Keyboard(usb_hid.devices)
    keyboard_layout = KeyboardLayoutUS(keyboard)
    
    CIRCUITPYTHON_AVAILABLE = True
except ImportError:
    # These modules are only available on CircuitPython devices
    # When running on host systems, we provide mock implementations
    CIRCUITPYTHON_AVAILABLE = False
    
    class MockKeyboard:
        def press(self, key):
            print(f"[MOCK] Pressed key: {key}")
        
        def release(self, key):
            print(f"[MOCK] Released key: {key}")
        
        def release_all(self):
            print("[MOCK] Released all keys")
    
    class MockKeyboardLayout:
        def write(self, text):
            print(f"[MOCK] Typed: {text}")
    
    keyboard = MockKeyboard()
    keyboard_layout = MockKeyboardLayout()

# Educational note: The usb_hid.devices list contains all available
# HID devices. The Keyboard class uses the first available device
# that supports keyboard functionality.


def main():
    """
    Main execution function.
    
    Replace this function with the code generated by Happy Frog.
    The generated code will include all the Ducky Script commands
    converted to CircuitPython equivalents.
    
    Educational Notes:
    - Always include delays to allow the system to recognize the device
    - Test in controlled environments only
    - Consider the timing of commands for reliable execution
    """
    
    # Wait for system to recognize the device
    # This is crucial for reliable operation
    print("Happy Frog - Educational HID Emulation")
    print("Waiting for system recognition...")
    time.sleep(2)
    
    # Example code - replace with your generated code
    print("Starting HID emulation...")
    
    # Type a simple message
    keyboard_layout.write("Hello from Happy Frog!")
    time.sleep(0.5)
    
    # Press Enter
    keyboard.press(Keycode.ENTER)
    keyboard.release(Keycode.ENTER)
    time.sleep(0.5)
    
    # Type educational message
    keyboard_layout.write("This is for educational purposes only!")
    time.sleep(0.5)
    
    # Press Enter again
    keyboard.press(Keycode.ENTER)
    keyboard.release(Keycode.ENTER)
    
    print("HID emulation completed.")


def test_basic_functionality():
    """
    Test function to verify basic HID functionality.
    
    This function can be used to test that your device is working
    correctly before running more complex scripts.
    """
    print("Testing basic HID functionality...")
    
    # Wait for device recognition
    time.sleep(2)
    
    # Test typing
    keyboard_layout.write("HID Test - ")
    
    # Test key presses
    keyboard.press(Keycode.CONTROL)
    keyboard.press(Keycode.C)
    keyboard.release(Keycode.C)
    keyboard.release(Keycode.CONTROL)
    
    time.sleep(0.5)
    
    # Test arrow keys
    keyboard.press(Keycode.LEFT_ARROW)
    keyboard.release(Keycode.LEFT_ARROW)
    
    print("Basic functionality test completed.")


def emergency_stop():
    """
    Emergency stop function.
    
    This function can be called to immediately stop all HID operations.
    Useful for testing and safety purposes.
    """
    print("Emergency stop activated!")
    # Release all keys that might be held down
    keyboard.release_all()


# Educational safety features
def setup_safety_features():
    """
    Setup safety features for educational use.
    
    This function demonstrates how to implement safety measures
    in HID emulation scripts.
    """
    print("Setting up safety features...")
    
    # Add a startup delay to prevent accidental execution
    print("Press any key within 5 seconds to continue...")
    time.sleep(5)
    
    # Check if we should continue
    # In a real implementation, you might check for a button press
    # or other input method to confirm execution
    
    print("Safety check passed. Proceeding with execution.")


# Main execution block
if __name__ == "__main__":
    """
    Main execution block.
    
    This is where the script starts when the device boots up.
    You can modify this section to add safety features, testing,
    or other initialization code.
    """
    
    try:
        # Optional: Setup safety features
        # setup_safety_features()
        
        # Optional: Test basic functionality first
        # test_basic_functionality()
        
        # Run the main function
        main()
        
    except KeyboardInterrupt:
        # Handle interruption gracefully
        print("Execution interrupted by user.")
        emergency_stop()
        
    except Exception as e:
        # Handle errors gracefully
        print(f"Error during execution: {e}")
        emergency_stop()
        
    finally:
        # Cleanup
        print("Happy Frog execution completed.")
        print("Remember: Use responsibly and ethically! 🐸")


"""
Educational Notes:

1. HID Emulation Basics:
   - HID (Human Interface Device) emulation allows microcontrollers
     to appear as keyboards, mice, or other input devices
   - This is the same technology used by legitimate input devices
   - Understanding this helps in defending against HID attacks

2. Security Implications:
   - HID attacks can bypass many security measures
   - They work at the input level, before most security software
   - This is why physical security is crucial

3. Defensive Measures:
   - Disable USB ports when not in use
   - Use USB port locks
   - Monitor for unexpected input devices
   - Implement input validation and rate limiting

4. Ethical Use:
   - Only test on systems you own or have permission to test
   - Use in controlled lab environments
   - Document all testing activities
   - Report vulnerabilities responsibly

For more information, visit: https://github.com/ZeroDumb/happy-frog
""" 