"""Archiving utilities for compressing allure-results."""

import zipfile
import os
from pathlib import Path
from typing import Union
from .exceptions import ArchiveError


def create_zip_archive(source_dir: Union[str, Path], output_path: Union[str, Path]) -> Path:
    """
    Create a ZIP archive from a directory.
    
    This uses Python's built-in zipfile module for cross-platform compatibility
    (works on Windows, Linux, and macOS without external dependencies).
    
    Args:
        source_dir: Path to the directory to archive (e.g., allure-results)
        output_path: Path where the ZIP file should be created
        
    Returns:
        Path: Path to the created ZIP file
        
    Raises:
        ArchiveError: If archiving fails
    """
    source_dir = Path(source_dir)
    output_path = Path(output_path)
    
    # Validate source directory exists
    if not source_dir.exists():
        raise ArchiveError(f"Source directory does not exist: {source_dir}")
    
    if not source_dir.is_dir():
        raise ArchiveError(f"Source path is not a directory: {source_dir}")
    
    # Check if directory is empty
    if not any(source_dir.iterdir()):
        raise ArchiveError(f"Source directory is empty: {source_dir}")
    
    # Create parent directory for output if it doesn't exist
    output_path.parent.mkdir(parents=True, exist_ok=True)
    
    try:
        with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # Walk through the directory and add all files
            for root, dirs, files in os.walk(source_dir):
                for file in files:
                    file_path = Path(root) / file
                    # Calculate the archive name (relative path from source_dir)
                    arcname = file_path.relative_to(source_dir)
                    zipf.write(file_path, arcname)
        
        return output_path
        
    except Exception as e:
        raise ArchiveError(f"Failed to create ZIP archive: {e}") from e


def create_temp_zip_archive(source_dir: Union[str, Path]) -> Path:
    """
    Create a temporary ZIP archive from a directory.
    
    Args:
        source_dir: Path to the directory to archive
        
    Returns:
        Path: Path to the created temporary ZIP file
        
    Raises:
        ArchiveError: If archiving fails
    """
    import tempfile
    
    source_dir = Path(source_dir)
    temp_dir = Path(tempfile.gettempdir())
    output_path = temp_dir / f"allure-results-{os.getpid()}.zip"
    
    return create_zip_archive(source_dir, output_path)
