#!/usr/bin/env python3
"""Extract FULL 0x4002 commands (which carry the actual LED control bytes)."""
import struct
from datetime import datetime
from collections import defaultdict

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:
                # The full LED payload is in data[8:] after the 8-byte wrapper
                # Pattern: 02 40 00 <len> 00 6a 00 04 00 52 52 00 <LED data>
                # Or: 02 40 00 <len> 00 6a 00 04 00 52 52 00 0e 45 00...
                # Let me just print all of it
                writes.append({'ts': ts_sec, 'data': data})

print(f"Total 0x4002 writes: {len(writes)}")
print()
for i, w in enumerate(writes):
    ts_str = datetime.fromtimestamp(w['ts']).strftime('%H:%M:%S.%f')[:-3]
    print(f"[{i:3d}] {ts_str} ({len(w['data']):2d}B) {w['data'].hex()}")

# Group by payload
print("\n=== Unique payloads (grouped) ===")
by_pl = defaultdict(list)
for w in writes:
    by_pl[w['data'].hex()].append(w['ts'])
for pl, tss in sorted(by_pl.items(), key=lambda x: x[1][0]):
    ts_str = datetime.fromtimestamp(tss[0]).strftime('%H:%M:%S.%f')[:-3]
    print(f"  {ts_str} ({len(tss):3d}x) {pl}")
