#!/usr/bin/env python3
"""
Create a ZIP archive from CPAP SD card data and encode it to base64.

This script helps prepare CPAP data for upload to the MCP server.

Usage:
    python create_archive.py /path/to/sdcard/data
    python create_archive.py /path/to/sdcard/data --output my_cpap_data.zip
"""

import argparse
import base64
import zipfile
import sys
from pathlib import Path


def create_cpap_archive(source_dir: Path, output_file: Path = None) -> Path:
    """
    Create a ZIP archive from CPAP SD card data.
    
    Args:
        source_dir: Path to the SD card data directory
        output_file: Optional output file path (default: cpap_data.zip)
    
    Returns:
        Path to the created ZIP file
    """
    if not source_dir.exists():
        raise ValueError(f"Source directory does not exist: {source_dir}")
    
    if not source_dir.is_dir():
        raise ValueError(f"Source path is not a directory: {source_dir}")
    
    # Default output file
    if output_file is None:
        output_file = Path("cpap_data.zip")
    
    # Create ZIP archive
    print(f"Creating ZIP archive from: {source_dir}")
    file_count = 0
    
    with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
        # Walk through source directory
        for file_path in source_dir.rglob('*'):
            if file_path.is_file():
                # Get relative path from source directory
                arcname = file_path.relative_to(source_dir)
                
                # Skip hidden files
                if any(part.startswith('.') for part in arcname.parts):
                    print(f"  Skipping hidden file: {arcname}")
                    continue
                
                print(f"  Adding: {arcname}")
                zipf.write(file_path, arcname)
                file_count += 1
    
    file_size = output_file.stat().st_size
    print(f"\n✓ Created ZIP archive: {output_file}")
    print(f"  Files: {file_count}")
    print(f"  Size: {file_size:,} bytes ({file_size / 1024 / 1024:.2f} MB)")
    
    return output_file


def encode_to_base64(zip_file: Path, output_file: Path = None) -> Path:
    """
    Encode ZIP file to base64.
    
    Args:
        zip_file: Path to ZIP file
        output_file: Optional output file path (default: [zipfile].b64)
    
    Returns:
        Path to the base64 encoded file
    """
    if not zip_file.exists():
        raise ValueError(f"ZIP file does not exist: {zip_file}")
    
    # Default output file
    if output_file is None:
        output_file = zip_file.with_suffix(zip_file.suffix + '.b64')
    
    print(f"\nEncoding to base64...")
    
    # Read ZIP file and encode
    with open(zip_file, 'rb') as f:
        zip_content = f.read()
    
    encoded_content = base64.b64encode(zip_content).decode('utf-8')
    
    # Write encoded content
    with open(output_file, 'w') as f:
        f.write(encoded_content)
    
    print(f"✓ Created base64 file: {output_file}")
    print(f"  Size: {len(encoded_content):,} bytes")
    
    return output_file


def main():
    parser = argparse.ArgumentParser(
        description="Create and encode CPAP data archive for MCP server upload",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Create archive from SD card data
  python create_archive.py /Volumes/RESMED/
  
  # Specify output filename
  python create_archive.py /Volumes/RESMED/ --output my_data.zip
  
  # Create archive and base64 encoding
  python create_archive.py /Volumes/RESMED/ --encode
  
  # Just encode an existing ZIP file
  python create_archive.py existing_data.zip --encode-only
"""
    )
    
    parser.add_argument(
        'source',
        type=str,
        help='Path to SD card data directory or existing ZIP file (with --encode-only)'
    )
    
    parser.add_argument(
        '-o', '--output',
        type=str,
        help='Output ZIP filename (default: cpap_data.zip)'
    )
    
    parser.add_argument(
        '-e', '--encode',
        action='store_true',
        help='Also create base64 encoded file'
    )
    
    parser.add_argument(
        '--encode-only',
        action='store_true',
        help='Only encode existing ZIP file (source should be a ZIP file)'
    )
    
    args = parser.parse_args()
    
    try:
        source_path = Path(args.source)
        
        if args.encode_only:
            # Just encode existing ZIP
            if not source_path.suffix == '.zip':
                print("Warning: Source file doesn't have .zip extension", file=sys.stderr)
            
            encode_to_base64(source_path)
            
        else:
            # Create archive
            output_path = Path(args.output) if args.output else None
            zip_file = create_cpap_archive(source_path, output_path)
            
            # Optionally encode
            if args.encode:
                encode_to_base64(zip_file)
        
        print("\n✓ Done!")
        print("\nNext steps:")
        if not args.encode_only and not args.encode:
            print("  1. Encode the ZIP file:")
            print(f"     python create_archive.py {zip_file} --encode-only")
            print("  2. Upload the base64 content to the MCP server")
        else:
            print("  1. Copy the base64 content from the .b64 file")
            print("  2. Send it to the AI with the upload_archive tool")
        
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == '__main__':
    main()
