# -*- coding: utf-8 -*-
import sys
import zlib
from pathlib import Path

def main():
    if len(sys.argv) < 3:
        print("Usage: pad_bin.py <input.bin> <output_padded.bin> [align] [output_info.txt]")
        sys.exit(1)

    input_path = Path(sys.argv[1])
    output_path = Path(sys.argv[2])
    align = int(sys.argv[3], 16) if len(sys.argv) > 3 else 0x100
    info_txt_path = Path(sys.argv[4]) if len(sys.argv) > 4 else output_path.with_suffix(".txt")

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

    pad_len = (align - (len(data) % align)) % align
    data_padded = data + b'\xFF' * pad_len
    crc32_val = zlib.crc32(data_padded) & 0xFFFFFFFF

    with output_path.open("wb") as f:
        f.write(data_padded)
    
    size_hex = f"{len(data_padded):08X}"
    size_formatted = ' '.join([size_hex[i:i+2] for i in range(0, len(size_hex), 2)])
    crc_hex = f"{crc32_val:08X}"
    crc_formatted = ' '.join([crc_hex[i:i+2] for i in range(0, len(crc_hex), 2)])

    with info_txt_path.open("w") as f:
        f.write(f"Size: 0x{len(data_padded):08X}\n")
        f.write(f"CRC32: 0x{crc32_val:08X}\n")
        f.write(size_formatted +' '+ crc_formatted + '\n')



    print(f"Padded BIN written to: {output_path}")
    print(f"Size: {len(data_padded)} bytes")
    print(f"CRC32: 0x{crc32_val:08X}")
    print(size_formatted +' '+ crc_formatted)
    print(f"Info saved to: {info_txt_path}")

if __name__ == "__main__":
    main()
