#!/usr/bin/env python3
import os
import sys


def check_binary(file_path, patches):
    if not os.path.exists(file_path):
        return f"MISSING: {file_path}"

    with open(file_path, "rb") as f:
        data = f.read()

    results = []
    for name, offset, expected, patched in patches:
        if data[offset : offset + len(expected)] == expected:
            results.append(f"  [FAIL] {name}: UNPATCHED (found {expected.hex()})")
        elif data[offset : offset + len(patched)] == patched:
            results.append(f"  [PASS] {name}: PATCHED (found {patched.hex()})")
        else:
            found = data[offset : offset + max(len(expected), len(patched))].hex()
            results.append(
                f"  [ERR] {name}: UNKNOWN (expected {patched.hex()}, found {found})"
            )

    return "\n".join(results)


if __name__ == "__main__":
    PATCHED_DIR = "/home/sapient/Public/esp32-analysis/patched_binaries"

    ultra_patches = [
        ("UI Branch", 0xBA62D, bytes.fromhex("26153c"), bytes.fromhex("060f00")),
        (
            "Global Status (Round 2)",
            0xBA6AD,
            bytes.fromhex("040242"),
            bytes.fromhex("221000"),
        ),
    ]

    meshos_patches = [
        ("UI Branch", 0xB99ED, bytes.fromhex("26193c"), bytes.fromhex("060f00")),
        (
            "Global Status (Round 2)",
            0xB9A54,
            bytes.fromhex("84210040"),
            bytes.fromhex("22100040"),
        ),
    ]

    targets = [
        (
            "Ultra Standalone-MOD",
            os.path.join(PATCHED_DIR, "Ultra-TDeck-v9.2.patched.bin"),
            ultra_patches,
        ),
        (
            "Ultra Merged-MOD",
            os.path.join(PATCHED_DIR, "Ultra-TDeck-v9.2-merged.patched.bin"),
            [(n, o + 0x10000, e, p) for n, o, e, p in ultra_patches],
        ),
        (
            "MeshOS Standalone-MOD",
            os.path.join(PATCHED_DIR, "MeshOS-TDeck-1.1.8.patched.bin"),
            meshos_patches,
        ),
        (
            "MeshOS Merged-MOD",
            os.path.join(PATCHED_DIR, "MeshOS-TDeck-1.1.8-merged.patched.bin"),
            [(n, o + 0x10000, e, p) for n, o, e, p in meshos_patches],
        ),
    ]

    all_passed = True
    print("=== T-Deck-MOD Firmware Patch Verification Harness ===")
    for label, path, p in targets:
        print(f"\n{label}:")
        report = check_binary(path, p)
        print(report)
        if "[FAIL]" in report or "[ERR]" in report or "MISSING" in report:
            all_passed = False

    if all_passed:
        print("\n[COMPLETE] All binaries are fully patched.")
        sys.exit(0)
    else:
        print("\n[INCOMPLETE] Some patches are missing or invalid.")
        sys.exit(1)
