#!/usr/bin/env python3
import sys


def compute_checksum(data: bytes) -> int:
    # PSA checksum excludes first 4 bytes ("MEL\0")
    relevant = data[4:]
    total = sum(relevant)
    folded = (total & 0xFF) + (total >> 8)
    return (~folded) & 0xFF


def interactive_mode():
    print("PSA Checksum Generator (Melody 0x3001 packets)")
    print("Paste the hex payload WITHOUT the checksum byte. Type 'exit' to quit.")
    while True:
        user_input = input("Payload> ").strip()
        if user_input.lower() in ("exit", "quit"):
            break
        try:
            data = bytes.fromhex(user_input)
            checksum = compute_checksum(data)
            completed = data + bytes([checksum])
            print("Checksum: {:02X}".format(checksum))
            print("Full Packet: {}".format(completed.hex()))
        except ValueError:
            print("Invalid hex input. Try again.")


if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] == "--batch":
        print("Batch mode not implemented. Run without arguments for interactive mode.")
    else:
        interactive_mode()
