"""Utility functions for py-xmind16."""

import os
import shutil
import uuid
import zipfile
from typing import Optional


def generate_id() -> str:
    """Generate a unique ID for XMind elements.
    
    Returns:
        A unique identifier string.
    """
    return str(uuid.uuid4()).replace("-", "")


def create_zip_archive(source_dir: str, output_path: str) -> None:
    """Create a ZIP archive from a directory.
    
    Args:
        source_dir: The directory to archive.
        output_path: The path for the output ZIP file.
    """
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(source_dir):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, source_dir)
                zipf.write(file_path, arcname)


def extract_zip_archive(zip_path: str, target_dir: str) -> None:
    """Extract a ZIP archive to a directory.
    
    Args:
        zip_path: The path to the ZIP file.
        target_dir: The directory to extract to.
    """
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        zipf.extractall(target_dir)


def ensure_dir(directory: str) -> None:
    """Ensure a directory exists, creating it if necessary.
    
    Args:
        directory: The directory path.
    """
    os.makedirs(directory, exist_ok=True)


def remove_dir(directory: str) -> None:
    """Remove a directory and all its contents.
    
    Args:
        directory: The directory path.
    """
    if os.path.exists(directory):
        shutil.rmtree(directory)
