#!/usr/bin/env python3
"""Analyze what patches are in the current patched files."""
import sys

def analyze():
    # 1. Check mcu_app_patched.hex
    try:
        with open('/Users/admin/workspace/jyq/update/mcu_app_patched.hex') as f:
            content = f.read()
        lines = content.splitlines()
        print(f"=== mcu_app_patched.hex ===")
        print(f"  Lines: {len(lines)}, Size: {len(content)} bytes")
        
        # Parse records
        data_records = [l for l in lines if l and l[0] == ':' and l[7:9] == '00']
        ext_records = [l for l in lines if l and l[0] == ':' and l[7:9] == '04']
        eof = [l for l in lines if l and l[0] == ':' and l[7:9] == '01']
        print(f"  Data records: {len(data_records)}")
        print(f"  Extended addr records: {len(ext_records)}")
        print(f"  EOF records: {len(eof)}")
        
        # Check if it has Extended Linear Address records (Intel HEX format)
        if ext_records:
            print(f"  Format: Intel HEX (with extended address records)")
        else:
            print(f"  Format: Possibly raw/linear (no extended address records)")
            
        # Check patches at key addresses
        patches_to_check = [
            (0x125B4, "CAN init -> return success"),
            (0x124E8, "cbz -> nop (caller)"),
            (0x125D4, "cbz -> nop (search fail)"),
            (0x125DE, "beq -> nop (init fail)"),
            (0x125FC, "beq -> nop (final fail)"),
            (0x1A37C, "bne -> b (queue check)"),
            (0x1A466, "cbz -> b (status check)"),
        ]
        
        data = {}
        ext_addr = 0
        for line in lines:
            line = line.strip()
            if not line or line[0] != ':':
                continue
            bc = int(line[1:3], 16)
            addr = int(line[3:7], 16)
            rt = int(line[7:9], 16)
            payload = bytes.fromhex(line[9:9+bc*2])
            if rt == 4:
                ext_addr = int.from_bytes(payload[:2], 'big') << 16
            elif rt == 0:
                start = ext_addr + addr
                data[start] = payload
        
        print(f"\n  Total parsed data bytes: {sum(len(v) for v in data.values())}")
        print(f"\n  Patch verification:")
        for addr, desc in patches_to_check:
            found = False
            for rec_addr, rec_data in data.items():
                if rec_addr <= addr < rec_addr + len(rec_data):
                    offset = addr - rec_addr
                    actual = rec_data[offset:offset+2]
                    if len(actual) == 2:
                        is_patched = actual[0] == 0x00 and actual[1] == 0xBF
                        # For 0x125B4 check for movs r0,#1; bx lr
                        if addr == 0x125B4 and len(rec_data) >= offset+4:
                            is_patched = rec_data[offset:offset+4] == bytes([0x20, 0x01, 0x70, 0x47])
                            actual_str = rec_data[offset:offset+4].hex()
                        else:
                            actual_str = actual.hex()
                        status = "PATCHED" if is_patched else "NOT PATCHED"
                        print(f"    0x{addr:05X} ({desc}): {actual_str} [{status}]")
                    found = True
                    break
            if not found:
                print(f"    0x{addr:05X} ({desc}): ADDRESS NOT FOUND IN DATA")
    except Exception as e:
        print(f"Error reading mcu_app_patched.hex: {e}")
    
    # 2. Check mcu_app_patched_inplace.hex
    try:
        with open('/Users/admin/workspace/jyq/update/mcu_app_patched_inplace.hex') as f:
            content = f.read()
        lines = content.splitlines()
        print(f"\n=== mcu_app_patched_inplace.hex ===")
        print(f"  Lines: {len(lines)}, Size: {len(content)} bytes")
        
        data = {}
        ext_addr = 0
        for line in lines:
            line = line.strip()
            if not line or line[0] != ':':
                continue
            bc = int(line[1:3], 16)
            addr = int(line[3:7], 16)
            rt = int(line[7:9], 16)
            payload = bytes.fromhex(line[9:9+bc*2])
            if rt == 4:
                ext_addr = int.from_bytes(payload[:2], 'big') << 16
            elif rt == 0:
                start = ext_addr + addr
                data[start] = payload
        
        print(f"  Patch verification:")
        for addr, desc in patches_to_check:
            found = False
            for rec_addr, rec_data in data.items():
                if rec_addr <= addr < rec_addr + len(rec_data):
                    offset = addr - rec_addr
                    actual = rec_data[offset:offset+2]
                    if len(actual) == 2:
                        is_patched = actual[0] == 0x00 and actual[1] == 0xBF
                        if addr == 0x125B4 and len(rec_data) >= offset+4:
                            is_patched = rec_data[offset:offset+4] == bytes([0x20, 0x01, 0x70, 0x47])
                            actual_str = rec_data[offset:offset+4].hex()
                        else:
                            actual_str = actual.hex()
                        status = "PATCHED" if is_patched else "NOT PATCHED"
                        print(f"    0x{addr:05X} ({desc}): {actual_str} [{status}]")
                    found = True
                    break
            if not found:
                print(f"    0x{addr:05X} ({desc}): ADDRESS NOT FOUND IN DATA")
    except Exception as e:
        print(f"Error reading mcu_app_patched_inplace.hex: {e}")

    # 3. Check original hex
    try:
        with open('/Users/admin/workspace/jyq/mcubin/mcu_app.hex') as f:
            content = f.read()
        lines = content.splitlines()
        print(f"\n=== ORIGINAL mcu_app.hex ===")
        print(f"  Lines: {len(lines)}, Size: {len(content)} bytes")
        
        data = {}
        ext_addr = 0
        for line in lines:
            line = line.strip()
            if not line or line[0] != ':':
                continue
            bc = int(line[1:3], 16)
            addr = int(line[3:7], 16)
            rt = int(line[7:9], 16)
            payload = bytes.fromhex(line[9:9+bc*2])
            if rt == 4:
                ext_addr = int.from_bytes(payload[:2], 'big') << 16
            elif rt == 0:
                start = ext_addr + addr
                data[start] = payload
        
        print(f"  Original bytes at patch addresses:")
        for addr, desc in patches_to_check:
            found = False
            for rec_addr, rec_data in data.items():
                if rec_addr <= addr < rec_addr + len(rec_data):
                    offset = addr - rec_addr
                    actual = rec_data[offset:offset+2]
                    if len(actual) == 2:
                        print(f"    0x{addr:05X} ({desc}): {actual.hex()}")
                    found = True
                    break
            if not found:
                print(f"    0x{addr:05X} ({desc}): ADDRESS NOT FOUND")
    except Exception as e:
        print(f"Error reading original hex: {e}")

if __name__ == '__main__':
    analyze()
