#!/usr/bin/env python3
"""Reconstruct full LED commands by grouping 3-byte chunks from 0x4202 writes."""
import struct
from datetime import datetime
from collections import defaultdict

# Looking at data:
# Format: 02 42 00 10 00 0c 00 04 00 52 1a 00 [3 LED bytes]
# So LED bytes are at data[11:14]

# And the long sequences with 0x4202:
# e.g. seq 0: 17 packets, all 0x4202 - this is the GATT service discovery
# But the LED bytes extracted are: 00 ff ff 02 00 ff ff 00 ff ff ...
# Each "chunk" gives us 3 bytes: byte0 byte1 byte2
# So a 9-byte LED packet would be 3 chunks of 3 bytes

# Let me group them in 3s
all_chunks = []
with open('/tmp/FS/data/misc/bluetooth/logs/btsnooz_hci.log', 'rb') as f:
    f.read(16)
    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_chunks.append({'ts': ts_sec, 'led': led, 'full': data.hex()})

# Group in 3s
print(f"Total 0x4202 chunks: {len(all_chunks)}")
print()
print("=== LED commands (3 chunks per packet) ===")
for i in range(0, len(all_chunks), 3):
    if i+3 > len(all_chunks): break
    group = all_chunks[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"[{i:3d}] {ts_str} {full.hex(' ')}")
