#
# This is a debug script to trace the Krux decryption process.
# It has been modified to be self-contained and avoid MicroPython-specific libraries.
#
import sys

# Add the source directory to the path to allow imports
sys.path.append('REFERENCE/krux/src')

from krux.baseconv import pure_python_base_decode

def unwrap_standalone(kef_bytes):
    """A self-contained version of kef.unwrap for debugging."""
    try:
        len_id = kef_bytes[0]
        if not (0 <= len_id <= 252):
             raise ValueError(f"Invalid label length: {len_id}")
        if len(kef_bytes) < (1 + len_id + 4):
            raise ValueError("KEF bytes too short for header")

        id_ = kef_bytes[1 : 1 + len_id]
        version = kef_bytes[1 + len_id]
        kef_iterations = int.from_bytes(kef_bytes[2 + len_id : 5 + len_id], "big")
        
        if kef_iterations <= 10000:
            iterations = kef_iterations * 10000
        else:
            iterations = kef_iterations
            
        payload = kef_bytes[len_id + 5 :]
        return (id_, version, iterations, payload)
    except Exception as e:
        raise ValueError(f"Failed to unwrap KEF envelope: {e}")


def debug_krux_decryption():
    # Test case from the user
    base43_string = "1334+HGXM$F8PPOIRNHX0.R*:SBMHK$X88LX$*/Y417R/6S1ZQOB2LHM-L+4T1YQVU:B*CKGXONP7:Y/R-B*:$R8FK"

    print("--- Krux Decryption Debug (Phase 1: Decoding & Unwrapping) ---")
    print(f"Input Base43: {base43_string}\n")

    # Step 1: Base43 Decode
    try:
        kef_envelope_bytes = pure_python_base_decode(base43_string, 43)
        print(f"[OK] Step 1: Base43 Decoded (KEF Envelope Hex):")
        print(kef_envelope_bytes.hex())
        print("-" * 20)
    except Exception as e:
        print(f"[FAIL] Step 1: Base43 Decoding failed: {e}")
        return

    # Step 2: Unwrap KEF Envelope
    try:
        label_bytes, version, iterations, payload = unwrap_standalone(kef_envelope_bytes)
        label = label_bytes.decode('utf-8', errors='ignore')
        print(f"[OK] Step 2: KEF Unwrapped")
        print(f"  - Label: '{label}'")
        print(f"  - Version: {version}")
        print(f"  - Iterations: {iterations}")
        print(f"  - Payload (Hex): {payload.hex()}")
        print("-" * 20)
        print("\n--- DEBUGGING COMPLETE ---")
        print("Please paste this entire output for analysis.")

    except Exception as e:
        print(f"[FAIL] Step 2: KEF Unwrapping failed: {e}")
        return

if __name__ == '__main__':
    debug_krux_decryption()
