#!/usr/bin/env python3

# ========================================================
#    This code is for study only.
#    This code is not optimized.
#    This code is over simplified.
#    This code doesn't respect rules of good coding.
#    This code has duplicate codes: 
#        to understanding without complexity.
#    Some values -useless on code- will not be converted.
# ========================================================

import sys
import io

# Conversion en int
def to_int(length : bytes = b'') -> int:
    return int.from_bytes(length, byteorder='big')

if len(sys.argv) < 2:
    print("Usage: %s <mxf>" % sys.argv[0])
    sys.exit(1)

mxf_file = sys.argv[1]

with open(mxf_file, "rb") as file:

    while True:

        # Key : Universal Label
        key = file.read(16)

        # End of file
        if not key: 
            break

        # Length (BER format)
        length = to_int(file.read(4)[1:])  # BER format - read last 3 bytes

        # Value
        value = file.read(length)

        # Show each KLV
        if '-v' in sys.argv:
            print("{key} - {length:>6d} - {data}...".format(
                key = key.hex(),
                length = length,
                data = value[0:16].hex()
            ))

        # Filter 'Source Package'
        if key.hex() != "060e2b34025301010d01010101013700":
           continue

        # read Value
        value = io.BytesIO(value)

        # parse each items
        while True:
            item_key = value.read(2)
            item_length = value.read(2)
            item_size = to_int(item_length)
            item_value = value.read(item_size)

            # end of items
            if not item_key:
                break

            # Static LocalTag 'Package UID' (4401)
            if item_key.hex() == "4401":
                assetuuid = item_value[16:32]
                print("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}".format(*assetuuid))
                break

