#!/usr/bin/env python3
"""Map LED writes to user actions based on btsnoop timestamps.

We asked user to do:
- ON (4:20:38)
- OFF (4:20:43)
- ON (4:20:45)
- Colors: Red (4:20:50), Green (4:20:53), Blue (4:20:57), White (4:21:00)
- Effect (4:21:09)
- Effect (4:21:11)
- Effect (4:21:13)
- Mic/etc (4:21:16, 4:21:19, 4:21:21, 4:21:23)
- Timing (4:21:27)
- Various (4:21:33)
- ON/OFF (4:21:41, 4:21:44)
- Color (4:21:52)
"""
import struct
from datetime import datetime

with open('/tmp/FS/data/misc/bluetooth/logs/btsnooz_hci.log', 'rb') as f:
    f.read(16)
    all_writes = []
    while True:
        pkt_hdr = f.read(24)
        if len(pkt_hdr) < 24: break
        orig_len, inc_len, flags, drops, ts = struct.unpack('>IIIIq', pkt_hdr)
        data = f.read(inc_len)
        if len(data) < inc_len: break
        pkt_type = flags & 0x0F
        ts_sec = ts / 1000000.0
        if pkt_type == 0 and len(data) >= 14:
            opcode = struct.unpack('<H', data[:2])[0]
            if opcode == 0x4202:
                led = data[11:14]
                all_writes.append({'ts': ts_sec, 'led': led})

# Group in 3s and show
print("LED commands (3 chunks per packet) with action context:")
for i in range(0, len(all_writes), 3):
    if i+3 > len(all_writes): break
    group = all_writes[i:i+3]
    full = b''.join(c['led'] for c in group)
    ts_str = datetime.fromtimestamp(group[0]['ts']).strftime('%H:%M:%S.%f')[:-3]
    print(f"  {ts_str} {full.hex(' ')}")
