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

# Pattern A: 0x4202 - direct LED write (3 bytes per packet)
# Format: 02 42 00 10 00 0c 00 04 00 52 1a 00 <3 LED bytes>
# Pattern B: 0x4002 - longer LED write (3 bytes per packet)
# Format: 02 40 00 ?? ?? 00 04 00 52 52 00 <seq?> <2 LED bytes>
#                  or
# Format: 02 40 00 ?? ?? 00 04 00 52 52 00 0e <2 LED bytes> 00 <1 LED byte>
# Actually looking more carefully:
#   02 40 00 6e 00 6a 00 04 00 52 52 00 0e 45 00
#   The 3 LED bytes here would be 0e 45 00 (with 00 being padding?)
# Or maybe: <handle> <1 byte LED> <padding>
# Hmm

# Let me look at this differently - find LED writes to FFE1 (the LED control char)
# and group them by sequence

writes_by_time = []
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) >= 3:
            opcode = struct.unpack('<H', data[:2])[0]
            if opcode in (0x4202, 0x4002):
                # Extract the LED control bytes (after the header)
                # For 0x4202: skip 11 bytes, get 3
                # For 0x4002: skip varying bytes, get rest
                if opcode == 0x4202:
                    led_bytes = data[11:14] if len(data) > 11 else b''
                else:  # 0x4002
                    # Try different offsets
                    # The pattern 525200 appears in the data
                    idx = data.find(b'\x52\x52\x00')
                    if idx >= 0:
                        led_bytes = data[idx+3:idx+6] if len(data) >= idx+6 else b''
                    else:
                        led_bytes = b''
                writes_by_time.append({'ts': ts_sec, 'op': opcode, 'led': led_bytes.hex(), 'data': data.hex()})

print(f"Total LED writes: {len(writes_by_time)}")
print()

# Group writes by time (within 500ms of each other) to find multi-chunk sequences
sequences = []
current_seq = []
for w in writes_by_time:
    if current_seq and (w['ts'] - current_seq[-1]['ts']) > 0.5:
        if current_seq:
            sequences.append(current_seq)
        current_seq = []
    current_seq.append(w)
if current_seq:
    sequences.append(current_seq)

print(f"Total sequences: {len(sequences)}")
print()
print("=== Sequences (concatenated LED bytes) ===")
for i, seq in enumerate(sequences[:50]):
    ts_str = datetime.fromtimestamp(seq[0]['ts']).strftime('%H:%M:%S.%f')[:-3]
    full = ''.join(w['led'] for w in seq)
    # Format as 9 bytes if possible
    bytes_list = [full[j:j+2] for j in range(0, len(full), 2)]
    formatted = ' '.join(bytes_list[:20])
    opcodes = '/'.join(f'0x{w["op"]:04x}' for w in seq)
    print(f"[{i:3d}] {ts_str} ({len(seq)} pkts, {opcodes}) {formatted}")
