#!/usr/bin/env python3
"""
Extract all MOSI bytes (commands from master to RFID reader)
"""
import csv

print("[*] Extracting all MOSI bytes from export.csv...")

all_mosi = []

with open('export.csv', 'r') as f:
    reader = csv.DictReader(f)
    
    for row in reader:
        if row['type'] == 'result' and row['mosi']:
            if row['mosi'].startswith('0x'):
                mosi_byte = int(row['mosi'], 16)
                all_mosi.append(mosi_byte)

print(f"[+] Extracted {len(all_mosi)} MOSI bytes")

# Show first 512 bytes
print("\n[*] First 512 MOSI bytes:")
for i in range(0, min(512, len(all_mosi)), 16):
    chunk = all_mosi[i:i+16]
    hex_str = ' '.join(f'{b:02x}' for b in chunk)
    ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in chunk)
    print(f"  {i:04x}: {hex_str:<48} {ascii_str}")

# Search for 'teptast'
print("\n[*] Searching for 'teptast' (74 65 70 74 61 73 74)...")
target = [0x74, 0x65, 0x70, 0x74, 0x61, 0x73, 0x74]

found_any = False
for i in range(len(all_mosi) - 6):
    if all_mosi[i:i+7] == target:
        found_any = True
        print(f"\n[+++] FOUND 'teptast' at offset {i} (0x{i:x})!")
        
        # Extract the 16-byte block containing teptast
        block_start = (i // 16) * 16
        sector_8 = all_mosi[block_start:block_start+16]
        
        print(f"\n{'='*70}")
        print(f"SECTOR 8 (Username):")
        hex_str = ''.join(f'{b:02x}' for b in sector_8)
        print(f"  {hex_str}")
        print(f"{'='*70}")
        
        # Next blocks are likely sectors 22 and 34  
        for idx in range(1, 5):
            offset = block_start + (idx * 16)
            if offset + 16 <= len(all_mosi):
                block = all_mosi[offset:offset+16]
                
                # Skip boring blocks
                if all(b == 0 for b in block) or all(b == 0xff for b in block) or all(b == 0x45 for b in block):
                    continue
                    
                hex_str = ''.join(f'{b:02x}' for b in block)
                ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in block)
                unique = len(set(block))
                
                if unique >= 3:  # Interesting data
                    print(f"\nBlock +{idx} (offset {offset:06x}):")
                    print(f"  {hex_str}")
                    print(f"  ASCII: '{ascii_str}'")
                    
                    if idx == 1:
                        print(f"  >>> POSSIBLY SECTOR 22 (Authorization Code)")
                    elif idx == 2:
                        print(f"  >>> POSSIBLY SECTOR 34 (Access Level)")

if not found_any:
    print("\n[-] 'teptast' pattern not found in MOSI data either")
    print("\n[*] Showing unique byte patterns to understand the data...")
    
    # Show bytes that aren't 0x00, 0x45, 0x88, 0xFF
    interesting = []
    for i, b in enumerate(all_mosi):
        if b not in [0x00, 0x45, 0x88, 0xFF]:
            interesting.append((i, b))
    
    print(f"\n[*] Found {len(interesting)} interesting bytes (not 00/45/88/FF):")
    for i, b in interesting[:50]:  # Show first 50
        context_start = max(0, i - 8)
        context_end = min(len(all_mosi), i + 8)
        context = all_mosi[context_start:context_end]
        hex_context = ' '.join(f'{x:02x}' for x in context)
        print(f"  Offset {i:06x}: ...{hex_context}... (interesting byte: 0x{b:02x})")
