#!/usr/bin/env python3
"""
Foxmail .box File Format Analyzer
Dumps structure info for analysis
"""

import os
import sys

def analyze_box_file(filepath):
    """Analyze Foxmail .box file structure"""
    
    print(f"Analyzing: {filepath}")
    print(f"Size: {os.path.getsize(filepath)} bytes\n")
    
    with open(filepath, 'rb') as f:
        # Read header
        header = f.read(256)
        
        print("=== First 256 bytes (hex) ===")
        for i in range(0, len(header), 16):
            hex_part = ' '.join(f'{b:02x}' for b in header[i:i+16])
            ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in header[i:i+16])
            print(f"{i:04x}: {hex_part:<48} {ascii_part}")
        
        # Read more content
        f.seek(0)
        content = f.read(4096)
        
        print("\n=== Searching for email patterns ===")
        
        # Try to find From: patterns
        text = content.decode('utf-8', errors='ignore')
        
        # Look for common patterns
        patterns = ['From:', 'Subject:', 'Date:', 'To:', 'From ', '\x01\x01\x01\x01']
        for pattern in patterns:
            count = content.count(pattern.encode('utf-8'))
            print(f"'{pattern}': {count} occurrences")
        
        print("\n=== Trying different decodings ===")
        for encoding in ['utf-8', 'gb2312', 'gbk', 'latin-1']:
            try:
                decoded = content.decode(encoding, errors='ignore')
                from_count = decoded.count('From:')
                print(f"{encoding}: {from_count} 'From:' found")
            except:
                print(f"{encoding}: failed")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 analyze_foxmail.py <box_file>")
    else:
        analyze_box_file(sys.argv[1])
