# import os
from os import remove
from pathlib import Path
# from glob import glob
import shutil
import tarfile
import gzip

def prepare_file(tar_file, working_leo):
    root_out = Path(__file__).parent / f'L1_extract_{working_leo}'

    ztypes = ['podRx3', 'rcvOrb']

    # Extract tar files into root_out
    with tarfile.open(str(tar_file), 'r') as tar:
        tar.extractall(path=root_out)

    # Copy files from "gnomes/level1a/*" into root_out
    level1a_path = root_out / "gnomes" / "level1a"
    if level1a_path.exists():
        for item in level1a_path.glob("*"):
            if item.is_file():
                shutil.copy(item, root_out)
            elif item.is_dir():
                shutil.copytree(item, root_out / item.name, dirs_exist_ok=True)

    # Remove gnomes directory
    gnomes_path = root_out / "gnomes"
    if gnomes_path.exists():
        shutil.rmtree(gnomes_path)

    # Process gzipped files
    for zt in ztypes:
        for gzfile in (root_out / zt).glob("*.gz"):
            out_file = root_out / zt / gzfile.stem  # remove .gz
            with gzip.open(gzfile, 'rb') as f_in, open(out_file, 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)
            remove(gzfile)