import zipfile
from pathlib import Path

from flandre.utils.RfMeta import RfFrameMeta, RfSequenceMeta


class RfSequence:
    def __init__(self, path: Path | str):
        from flandre.utils.RfFrame import RfFrameFile
        path = Path(path)
        if not path.exists():
            raise FileNotFoundError()
        if path.is_dir():
            self.type = 'dir'
        elif path.suffix == '.zip':
            self.type = 'zip'
        self.path = path
        self.meta = RfSequenceMeta.from_name(path.stem)
        self._frames: list[RfFrameFile] | None = None

    @property
    def frames(self):
        from flandre.utils.RfFrame import RfFrameFile
        if self._frames is None:
            arr = []
            match self.type:
                case 'zip':
                    zip_file = zipfile.ZipFile(self.path)
                    max_idx = max([int(Path(item.filename).stem) for item in zip_file.infolist()])
                    for i in range(max_idx + 1):
                        meta = RfFrameMeta.from_name(zip_file.open(f'{i}.meta').read().decode())
                        arr.append(RfFrameFile(meta, seq=self, filename=f'{i}.zst'))
                case 'dir':
                    for f in self.path.glob('*.bin'):
                        meta = RfFrameMeta.from_name(f.stem)
                        arr.append(RfFrameFile(meta, seq=self, filename=f.name))
            self._frames = arr
        return self._frames

    @property
    def seq_id_minmax(self):
        mmin = 2 ** 32
        mmax = 0
        for f in self.frames:
            mmin = min(mmin, f.meta.sequence_id)
            mmax = max(mmax, f.meta.sequence_id)
        return mmin, mmax
