import struct
import dataclasses
import sys
import os
from PIL import Image

@dataclasses.dataclass
class MVFile:
    Width: int
    Height: int
    DataSize: int
    Frames: int
    RGBAData: bytes

def readFile(file : str) -> MVFile:
    try:
        with open(file, 'rb') as f:
            #Read the header
            headerBytes = f.read(20)
            #skip to the data section
            f.seek(32, 0)
            headerArr = struct.unpack(">IIQI", headerBytes)
            return MVFile(
                Width=headerArr[0],
                Height=headerArr[1],
                DataSize=headerArr[2],
                Frames=headerArr[3],
                RGBAData=f.read(headerArr[2] - 32)
            )
            return ret
    except FileNotFoundError:
        print(f"File {file} not found.")

def saveFrames(mv: MVFile, outputDir: str):
    frame_size = mv.Width * mv.Height * 4
    for i in range(mv.Frames):
        offset = i * frame_size
        frame_bytes = mv.RGBAData[offset:offset + frame_size]
        img = Image.frombytes('RGBA', (mv.Width, mv.Height), frame_bytes)
        img = img.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
        img.save(rf"{outputDir}\frame_{i}.tif")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python IS1GraphicsDecoder.py <input_file> <output_directory>")
        sys.exit(1)
    input_file = sys.argv[1]
    output_dir = sys.argv[2]
    #make sure the output directory exists
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    mv = readFile(input_file)
    if mv:
        print(f"Width: {mv.Width}, Height: {mv.Height}, DataSize: {mv.DataSize}, Frames: {mv.Frames}")
        # Save individual frames
        saveFrames(mv, output_dir)
        print("Frames saved as individual images.")