#!/usr/bin/env python3
"""Map ALL 0x4002 LED writes to actions.

The 0x4002 commands have a richer payload. Format appears to be:
  02 40 00 LL LL 00 04 00 52 52 00 <2-3 LED bytes> [00?]

When user touched:
  - 4:22:42 = first ON (paired)
  - 4:22:42.985 = open connection?
  - 4:24:32-37 = various color changes
  - 4:24:38+ = effect selections and pixel animations
  - 4:25:32+ = more color changes
  - 4:26:34+ = effects
"""
import struct
from datetime import datetime

with open('/tmp/FS/data/misc/bluetooth/logs/btsnooz_hci.log', 'rb') as f:
    f.read(16)
    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) >= 3:
            opcode = struct.unpack('<H', data[:2])[0]
            if opcode == 0x4002:
                # Try to extract LED bytes
                # The pattern 525200 0e 45 00 suggests bytes after 525200
                idx = data.find(b'\x52\x52\x00')
                if idx >= 0:
                    led = data[idx+3:]
                else:
                    led = b''
                writes.append({'ts': ts_sec, 'led': led.hex(), 'data': data.hex()})

print(f"Total 0x4002 writes: {len(writes)}")
print()
print("=== Each 0x4002 write (chronological) ===")
prev_ts = None
for w in writes:
    ts_str = datetime.fromtimestamp(w['ts']).strftime('%H:%M:%S.%f')[:-3]
    gap = ""
    if prev_ts is not None:
        gap_ms = int((w['ts'] - prev_ts) * 1000)
        if gap_ms > 500:
            gap = f" [GAP {gap_ms}ms]"
    print(f"  {ts_str}{gap} {w['led']}")
    prev_ts = w['ts']
