import os
import py7zr
import sys

def create_empty_files_from_7z(archive_path, output_dir):
    """
    Extracts the file names from a 7z archive and creates corresponding
    empty (zero-byte) files in the output directory, preserving the original
    directory structure.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    try:
        with py7zr.SevenZipFile(archive_path, mode='r') as archive:
            all_files_and_dirs = archive.getnames()
            print("getnames finished")
            all_files_and_dirs = sorted(all_files_and_dirs)
            print("getnames sorted (1)")
            all_files_and_dirs = sorted(all_files_and_dirs, key=lambda s: (0 if archive.getinfo(s).is_directory == True else 1))
            print("getnames sorted (2)")

            for member_name in all_files_and_dirs:
                output_path = os.path.join(output_dir, member_name)

                if archive.getinfo(member_name).is_directory == True:
                    if not os.path.exists(output_path):
                        os.makedirs(output_path, exist_ok=True)
                        print(f"Created directory: {output_path}")
                    else:
                        print(f"Exists already: {output_path}")
                else:
                    parent_dir = os.path.dirname(output_path)
                    if parent_dir and not os.path.exists(parent_dir):
                        os.makedirs(parent_dir, exist_ok=True)

                    with open(output_path, 'w') as empty_file:
                        pass
                    print(f"Created empty file: {output_path}")

    except py7zr.Bad7zFile as e:
        print(f"Error: The archive file is corrupted or not a valid 7z file. {e}")
    except FileNotFoundError as e:
        print(f"Error: The archive file was not found. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")



create_empty_files_from_7z(sys.argv[1], sys.argv[1] + "_browse")
