import tinytuya

# Connect to Tuya Cloud platform
c = tinytuya.Cloud(
    apiRegion="CN",
    apiKey="kwtq4njngadghsqesk9r",
    apiSecret="6e6ad62b96234ef7b6f740780a9bd766",
    apiDeviceID="p1737359153517997k5h"
)

# Get the device list
devices = c.getdevices()
print("Device list: %r" % devices)

# Define multiple device IDs to operate on
device_ids = ["6c7deff7d53d4172fa8vbc", "6c83e981bce4efcdfdtq4p", "another_device_id_2"]

for device_id in device_ids:
    print(f"\n{'='*30}\nProcessing device {device_id}...")

    # Get the current status of the device
    status_response = c.getstatus(device_id)
    print("Original status response:", status_response)

    # Parse the status data
    if isinstance(status_response, dict) and status_response.get('success'):
        status_list = status_response.get('result', [])
    elif isinstance(status_response, list):
        status_list = status_response
    else:
        print(f"Device {device_id} has an abnormal response format")
        continue

    # Dynamically detect the switch code ----------------------------
    # Try to detect switch_1 first, then switch if it doesn't exist
    switch_code = None
    current_state = None

    # List of possible switch codes (sorted by priority)
    possible_codes = ['switch_1', 'switch', 'switch_2']

    for code in possible_codes:
        for item in status_list:
            if isinstance(item, dict) and item.get('code') == code:
                switch_code = code
                current_state = item.get('value')
                break
        if switch_code:  # Stop searching after finding a valid code
            break

    if not switch_code:
        print(f"Error: Switch status not found for device {device_id}. Available status codes:")
        print([item.get('code') for item in status_list if isinstance(item, dict)])
        continue
    # -------------------------------------------

    # Construct the switching command (using the detected switch code)
    commands = {
        "commands": [
            {"code": switch_code, "value": not current_state},  # Use the dynamically obtained switch code
            {"code": "countdown_1", "value": 0}
        ]
    }

    # Send the switching command
    action = "Turn on" if not current_state else "Turn off"
    print(f"{action} device {device_id} (using control code {switch_code})...")
    result = c.sendcommand(device_id, commands)
    print(f"Operation result for device {device_id}:\n", result)

    # Verify the new status
    new_status = c.getstatus(device_id)
    print(f"New status of device {device_id}:")
    if isinstance(new_status, dict) and new_status.get('success'):
        print(new_status.get('result', 'No status information'))
    else:
        print(new_status)