#!/usr/bin/env python3
"""
Concatenate all MISO bytes and search for sectors
"""
import csv

print("[*] Extracting all MISO bytes from export.csv...")

all_miso = []

with open('export.csv', 'r') as f:
    reader = csv.DictReader(f)
    
    for row in reader:
        if row['type'] == 'result' and row['miso']:
            if row['miso'].startswith('0x'):
                miso_byte = int(row['miso'], 16)
                all_miso.append(miso_byte)

print(f"[+] Extracted {len(all_miso)} MISO bytes")

# Show first 256 bytes
print("\n[*] First 256 MISO bytes:")
for i in range(0, min(256, len(all_miso)), 16):
    chunk = all_miso[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]

for i in range(len(all_miso) - 6):
    if all_miso[i:i+7] == target:
        print(f"\n[+++] FOUND 'teptast' at offset {i} (0x{i:x})!")
        
        # Show surrounding context (64 bytes before and after)
        start = max(0, i - 64)
        end = min(len(all_miso), i + 64)
        
        print(f"\n[*] Context around match:")
        for j in range(start, end, 16):
            chunk = all_miso[j:j+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)
            marker = ' <<<' if j <= i < j + 16 else ''
            print(f"  {j:06x}: {hex_str:<48} {ascii_str}{marker}")
        
        # Extract the 16-byte block containing teptast
        block_start = (i // 16) * 16
        sector_8 = all_miso[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_miso):
                block = all_miso[offset:offset+16]
                
                # Skip boring blocks
                if all(b == 0 for b in block) or all(b == 0xff 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)
                
                print(f"\nBlock +{idx} (offset {offset:06x}):")
                print(f"  {hex_str}")
                print(f"  ASCII: '{ascii_str}'")
                
                if idx == 1:
                    print(f"  ^^^ SECTOR 22 (Authorization Code)")
                elif idx == 2:
                    print(f"  ^^^ SECTOR 34 (Access Level)")
        
        break
else:
    print("\n[-] 'teptast' pattern not found in MISO data")
    print("[*] Checking if data is inverted or needs different interpretation...")
