import os

import joblib

from ._detect import _is_keras_model


def serialize_artifacts(tmpdir, model, scaler=None, encoder=None, label_map=None, vectorizer=None):
    """Serialize model and optional artifacts to a temp directory.

    Returns a dict of {artifact_name: file_path} for artifacts that were saved.
    """
    paths = {}

    if _is_keras_model(model):
        model_path = os.path.join(tmpdir, 'model.keras')
        model.save(model_path)
        paths['model.keras'] = model_path
    else:
        model_path = os.path.join(tmpdir, 'model.pkl')
        joblib.dump(model, model_path)
        paths['model.pkl'] = model_path

    if scaler is not None:
        p = os.path.join(tmpdir, 'scaler.pkl')
        joblib.dump(scaler, p)
        paths['scaler.pkl'] = p

    if encoder is not None:
        p = os.path.join(tmpdir, 'encoder.pkl')
        joblib.dump(encoder, p)
        paths['encoder.pkl'] = p

    if label_map is not None:
        p = os.path.join(tmpdir, 'label_map.pkl')
        joblib.dump(label_map, p)
        paths['label_map.pkl'] = p

    if vectorizer is not None:
        p = os.path.join(tmpdir, 'vectorizer.pkl')
        joblib.dump(vectorizer, p)
        paths['vectorizer.pkl'] = p

    return paths
