import mido
import time
import os

print("PLEASE remember to venv in ~/ before you run this.")

# Path Handling for your rhythm file
filename = "/home/josh/Code/EXAMPLE 3.AC7"

PORT_NAME = 'CASIO USB-MIDI:CASIO USB-MIDI MIDI 1 24:0'

def casio_checksum(data):
    return (128 - (sum(data) % 128)) % 128

def nibbelize(data):
    encoded = []
    for byte in data:
        encoded.append((byte >> 4) & 0x0F)
        encoded.append(byte & 0x0F)
    return encoded

def upload_ac7():
    try:
        outport = mido.open_output(PORT_NAME)
        with open(filename, 'rb') as f:
            file_binary = f.read()

        # THE "RHYTHM" HEADER
        # Model 0x16, Sub 0x01 (16-bit), Dev 0x10
        # Command 0x11 (Data Write)
        # Category 0x30 (Rhythm - instead of 0x20 Song)
        # Slot 0x00 (Usually starts at rhythm 171 on CT-X700)
        header_base = [0x44, 0x16, 0x01, 0x10, 0x11, 0x30, 0x00, 0x00]
        header_msg = header_base + [casio_checksum(header_base)]

        print("Sending Rhythm Header...")
        outport.send(mido.Message('sysex', data=header_msg))
        time.sleep(0.5)

        # THE PAYLOAD
        payload = nibbelize(file_binary)
        chunk_size = 128
        for i in range(0, len(payload), chunk_size):
            chunk = payload[i : i + chunk_size]
            data_base = [0x44, 0x16, 0x01, 0x10, 0x12] + chunk
            outport.send(mido.Message('sysex', data=data_base + [casio_checksum(data_base)]))
            time.sleep(0.06)

        # THE FOOTER
        footer_base = [0x44, 0x16, 0x01, 0x10, 0x13, 0x30, 0x00, 0x00]
        outport.send(mido.Message('sysex', data=footer_base + [casio_checksum(footer_base)]))

        print("Transfer complete. Check Rhythm slots 171+!")
        outport.close()

    except Exception as e:
        print(f"Chaos: {e}")

if __name__ == "__main__":
    upload_ac7()
