def decrypt_ten(buf: bytes, seed: int) -> bytes:
    key = seed & 0xff
    out = bytearray(len(buf))
    for i, c in enumerate(buf):
        b = (c - key) & 0xff
        out[i] = b
        signed_b = b if b < 128 else b - 256
        key = (key + signed_b) & 0xff
    return bytes(out)


def encrypt_ten(plain: bytes, seed: int) -> bytes:
    key = seed & 0xff
    out = bytearray(len(plain))
    for i, b in enumerate(plain):
        c = (b + key) & 0xff
        out[i] = c
        signed_b = b if b < 128 else b - 256
        key = (key + signed_b) & 0xff
    return bytes(out)


if __name__ == "__main__":
    orig = open(r"C:\Games\Karos\ServerList.ten", "rb").read()
    plain = decrypt_ten(orig, 0x3042)
    print("plaintext original:", plain)

    # roundtrip check
    re_enc = encrypt_ten(plain, 0x3042)
    print("roundtrip ok:", re_enc == orig)

    new_plain = b"127.0.0.1\r\n19999\r\n"
    new_enc = encrypt_ten(new_plain, 0x3042)
    print("novo decrypt check:", decrypt_ten(new_enc, 0x3042) == new_plain)

    with open(r"C:\Games\Karos\ServerList.ten.orig_backup", "wb") as f:
        f.write(orig)
    with open(r"C:\Games\Karos\ServerList.ten", "wb") as f:
        f.write(new_enc)
    print("ServerList.ten redirecionado pra 127.0.0.1:19999 (backup salvo)")
