#!/usr/bin/env python3
"""
If you're reading this, you found the breadcrumb.

Usage:
    python decode.py <image.png> <password>

Output:
    bundle.zip in the current directory, containing:
      - payload.txt  (the flex)
      - Bilik_Resume_v11_2026-04-18.docx  (the resume)

Requires: Pillow, numpy  (pip install pillow numpy)
"""
import sys, struct, hashlib, zipfile
from pathlib import Path

try:
    from PIL import Image
    import numpy as np
except ImportError:
    print("Install requirements:  pip install pillow numpy")
    sys.exit(1)

MAGIC = b'STEG'

def keystream(password: str, n: int) -> bytes:
    out = b''
    counter = 0
    while len(out) < n:
        out += hashlib.sha256(password.encode() + counter.to_bytes(8, 'big')).digest()
        counter += 1
    return out[:n]

def decode(image_path: str, password: str, out_zip: str = 'bundle.zip') -> None:
    img = Image.open(image_path).convert('RGB')
    flat = np.array(img, dtype=np.uint8).flatten()

    # Read 8-byte header
    header_bits = flat[:64] & 1
    header_enc = np.packbits(header_bits).tobytes()
    header = bytes(a ^ b for a, b in zip(header_enc, keystream(password, 8)))

    if header[:4] != MAGIC:
        print("No payload found — wrong password, or this PNG has been re-encoded.")
        sys.exit(2)

    length = struct.unpack('>I', header[4:8])[0]
    total = 8 + length
    blob_bits = flat[:total * 8] & 1
    blob_enc = np.packbits(blob_bits).tobytes()
    blob = bytes(a ^ b for a, b in zip(blob_enc, keystream(password, total)))

    Path(out_zip).write_bytes(blob[8:])
    with zipfile.ZipFile(out_zip) as z:
        print(f"Extracted {length} bytes -> {out_zip}")
        print("Contents:")
        for name in z.namelist():
            print(f"  {name}")
        print()
        print(f"Unzip it:  python -m zipfile -e {out_zip} .")

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print(__doc__)
        sys.exit(1)
    decode(sys.argv[1], sys.argv[2])
