import os
import base64
from pathlib import Path
from .init_files import init_files

def _safe_copy_files():
    """
    Extracts and saves files from init_files.py to appropriate relative paths.
    Creates directory structure if it does not exist.
    Files are not overwritten if they already exist.
    """
    # Determine destination paths
    dest_path = Path.cwd().resolve()
    print(f'\nInitializing directory "{dest_path}"')
    
    # Process each file entry
    for relative_path, content_base64 in init_files.items():
        # Create the full destination path
        dest_file = dest_path / relative_path
        
        try:
            # Skip if file already exists
            if dest_file.exists():
                print(f'[SKIP]  File "{relative_path}" already exists, skipping copy.')
                continue
            
            # Create parent directories if they don't exist
            dest_file.parent.mkdir(parents=True, exist_ok=True)
            
            # Decode base64 content and write to file
            file_content = base64.b64decode(content_base64)
            with open(dest_file, "wb") as fdst:
                fdst.write(file_content)
            print(f'[OK]    file "{relative_path}" copied successfully.')
        except Exception as err:
            print(f'[ERROR] Could not create file "{dest_file}": {err}')   

def init():
    """
    Initializes the current working directory by copying necessary files from the
    init_files directory. Existing files are not overwritten.
    """
    try:
        _safe_copy_files()
        print('[DONE]  Initialization completed successfully.')
    except Exception as err:
        print(f'\n[ERROR] Initialization failed: {err}')
        raise


init()
