import json
import os
import zipfile

from ._version import __version__


def build_metadata(name, description, detected, features, target,
                   scaler, encoder, label_map, vectorizer=None, metrics=None):
    """Build the metadata.json dict for the bundle."""
    metadata = {
        'bundle_version': '1',
        'package_version': __version__,
        'name': name,
        'description': description or '',
        'task_type': detected.get('task_type') or '',
        'framework': detected.get('framework') or '',
        'model_class': detected.get('model_class') or '',
        'features': features or {},
        'target': target or {},
        'has_scaler': scaler is not None,
        'has_encoder': encoder is not None,
        'has_label_map': label_map is not None,
        'has_vectorizer': vectorizer is not None,
        'hyperparameters': detected.get('hyperparameters') or {},
        'class_labels': detected.get('class_labels'),
        'n_features': detected.get('n_features'),
        'feature_names': detected.get('feature_names'),
        'import_format': detected.get('import_format') or '',
    }
    if metrics:
        metadata['metrics'] = metrics
    return metadata


def create_bundle(tmpdir, artifact_paths, metadata):
    """Create a ZIP bundle from serialized artifacts and metadata.

    Returns the path to the created ZIP file.
    """
    # Write metadata.json into the temp directory
    metadata_path = os.path.join(tmpdir, 'metadata.json')
    with open(metadata_path, 'w') as f:
        json.dump(metadata, f, indent=2)

    zip_path = os.path.join(tmpdir, 'bundle.zip')
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        # Add metadata
        zf.write(metadata_path, 'metadata.json')
        # Add artifacts
        for artifact_name, file_path in artifact_paths.items():
            zf.write(file_path, artifact_name)

    return zip_path
