package com.ss.android.ugc.effectmanager.algorithm;

import X.0Gf;
import X.0Gp;
import android.os.Handler;
import android.text.TextUtils;
import com.bytedance.covode.number.Covode;
import com.bytedance.frameworks.apm.trace.MethodCollector;
import com.ss.android.ugc.effectmanager.AlgorithmModelInfoMemoryCache;
import com.ss.android.ugc.effectmanager.DownloadableModelConfig;
import com.ss.android.ugc.effectmanager.EffectConfiguration;
import com.ss.android.ugc.effectmanager.LoadedModelList;
import com.ss.android.ugc.effectmanager.ModelEventListener;
import com.ss.android.ugc.effectmanager.common.EffectRequest;
import com.ss.android.ugc.effectmanager.common.Multimap;
import com.ss.android.ugc.effectmanager.common.Supplier;
import com.ss.android.ugc.effectmanager.common.WeakHandler;
import com.ss.android.ugc.effectmanager.common.cache.IModelCache;
import com.ss.android.ugc.effectmanager.common.logger.EPLog;
import com.ss.android.ugc.effectmanager.common.task.NormalTask;
import com.ss.android.ugc.effectmanager.common.utils.AssetUtils;
import com.ss.android.ugc.effectmanager.common.utils.EffectRequestUtil;
import com.ss.android.ugc.effectmanager.common.utils.NetworkUtils;
import com.ss.android.ugc.effectmanager.effect.task.task.FetchModelInfoByNameTask;
import com.ss.android.ugc.effectmanager.model.DownloadableModelResponse;
import com.ss.android.ugc.effectmanager.model.ModelInfo;
import com.ss.ugc.effectplatform.model.algorithm.SingleAlgorithmModelResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONException;
import org.json.JSONObject;

public class ModelConfigArbiter {
    public final DownloadableModelConfig mConfig;
    public IModelCache mIModelCache;
    public Map<String, ServerConfig> mModelListMap = new ConcurrentHashMap();
    public Map<String, ModelInfo> mSingleModelMap = new ConcurrentHashMap();
    public Supplier<0Gp<ServerConfig>> mTaskSupplier = new Supplier<0Gp<ServerConfig>>() {
        static {
            Covode.recordClassIndex(125197);
        }

        public 0Gp<ServerConfig> get(int i) {
            return ModelConfigArbiter.this.requestServerConfig(i);
        }
    };

    static {
        Covode.recordClassIndex(125196);
    }

    public void setIModelCache(IModelCache iModelCache) {
        this.mIModelCache = iModelCache;
    }

    public ModelConfigArbiter(DownloadableModelConfig downloadableModelConfig) {
        this.mConfig = downloadableModelConfig;
    }

    public 0Gp<ServerConfig> requestServerConfig(final int i) {
        return 0Gp.LIZ(new Callable<ServerConfig>() {
            static {
                Covode.recordClassIndex(125199);
            }

            public ServerConfig call() {
                Stopwatch createStarted = Stopwatch.createStarted();
                ModelEventListener eventListener = ModelConfigArbiter.this.mConfig.getEventListener();
                try {
                    final HashMap hashMap = new HashMap();
                    hashMap.put("sdk_version", ModelConfigArbiter.this.mConfig.getSdkVersion());
                    hashMap.put("device_type", ModelConfigArbiter.this.mConfig.getDeviceType());
                    hashMap.put("status", String.valueOf(ModelConfigArbiter.this.mConfig.getModelFileEnv().ordinal()));
                    new NormalTask((Handler) null, (String) null) {
                        static {
                            Covode.recordClassIndex(125200);
                        }

                        public void execute() {
                            EffectConfiguration effectConfiguration = ModelConfigArbiter.this.mConfig.getEffectConfiguration();
                            if (effectConfiguration != null) {
                                hashMap.putAll(EffectRequestUtil.INSTANCE.addCommonParams(effectConfiguration));
                            }
                            String loadJson = AssetUtils.loadJson(ModelConfigArbiter.this.mConfig.getAssetManager(), "model/effect_local_config.json");
                            if (!TextUtils.isEmpty(loadJson)) {
                                try {
                                    String optString = new JSONObject(loadJson).optString("tag");
                                    EPLog.d("ModelConfigArbiter", "asset tag = ".concat(String.valueOf(optString)));
                                    if (!TextUtils.isEmpty(optString)) {
                                        hashMap.put("tag", optString);
                                    }
                                } catch (JSONException unused) {
                                }
                            }
                            if (i > 0) {
                                hashMap.put("busi_id", String.valueOf(i));
                            }
                        }
                    }.execute();
                    DownloadableModelResponse downloadableModelResponse = (DownloadableModelResponse) ModelConfigArbiter.this.mConfig.getJsonConverter().convertJsonToObj(ModelConfigArbiter.this.mConfig.getEffectNetWorker().execute(new EffectRequest("GET", NetworkUtils.buildRequestUrl(hashMap, ModelConfigArbiter.this.mConfig.getHosts().get(0).getItemName() + "/model/api/arithmetics"))), DownloadableModelResponse.class);
                    Multimap multimap = new Multimap();
                    if (downloadableModelResponse != null) {
                        int i = downloadableModelResponse.status_code;
                        if (i == 0) {
                            DownloadableModelResponse.Data data = downloadableModelResponse.getData();
                            if (data == null || data.getArithmetics() == null) {
                                throw new IllegalStateException("status_code == 0 but data == null, indicates there may be an internal server error");
                            }
                            Map<String, List<ModelInfo>> arithmetics = data.getArithmetics();
                            for (String next : arithmetics.keySet()) {
                                for (Object put : arithmetics.get(next)) {
                                    multimap.put(next, put);
                                }
                            }
                            if (eventListener != null) {
                                eventListener.onFetchModelList(true, (String) null, createStarted.elapsedMillis(), ModelConfigArbiter.this.mConfig.getSdkVersion());
                            }
                            return new ServerConfig(multimap);
                        }
                        throw new IllegalStateException("status code == " + i + " , indicates there is no model config from server, sdk version is " + ModelConfigArbiter.this.mConfig.getSdkVersion());
                    }
                    throw new IllegalStateException("response == null, indicates there may be an internal server error");
                } catch (IllegalStateException e) {
                    if (eventListener != null) {
                        eventListener.onFetchModelList(false, e.getMessage(), createStarted.elapsedMillis(), ModelConfigArbiter.this.mConfig.getSdkVersion());
                    }
                    return null;
                }
            }
        }, this.mConfig.getExecutor(), (0Gf) null);
    }

    public LoadedModelList requireDecidedConfigNonBlockling(final int i) {
        ServerConfig serverConfig = this.mModelListMap.get("biz_".concat(String.valueOf(i)));
        if (serverConfig != null && serverConfig.getLoadedModelList() != null) {
            return serverConfig.getLoadedModelList();
        }
        0Gp.LIZ(new Callable<Object>() {
            static {
                Covode.recordClassIndex(125202);
            }

            public Object call() {
                ModelConfigArbiter.this.requireDecidedConfig(i);
                return null;
            }
        });
        return null;
    }

    public synchronized LoadedModelList requireDecidedConfig(int i) {
        MethodCollector.i(8627);
        String concat = "biz_".concat(String.valueOf(i));
        ServerConfig serverConfig = this.mModelListMap.get(concat);
        if (serverConfig == null || serverConfig.getLoadedModelList() == null) {
            0Gp r2 = (0Gp) this.mTaskSupplier.get(i);
            try {
                r2.LJFF();
                if (!r2.LIZJ()) {
                    final ServerConfig serverConfig2 = (ServerConfig) r2.LIZLLL();
                    if (this.mIModelCache != null) {
                        0Gp.LIZ(new Callable<Void>() {
                            static {
                                Covode.recordClassIndex(125201);
                            }

                            public Void call() {
                                AlgorithmModelInfoMemoryCache.INSTANCE.buildCache(serverConfig2.getLoadedModelList(), ModelConfigArbiter.this.mIModelCache);
                                return null;
                            }
                        });
                    }
                    if (serverConfig2 == null) {
                        RuntimeException runtimeException = new RuntimeException("config == null");
                        MethodCollector.o(8627);
                        throw runtimeException;
                    } else if (serverConfig2.getLoadedModelList() != null) {
                        this.mModelListMap.put(concat, serverConfig2);
                        LoadedModelList loadedModelList = serverConfig2.getLoadedModelList();
                        MethodCollector.o(8627);
                        return loadedModelList;
                    } else {
                        RuntimeException runtimeException2 = new RuntimeException("loadedModelList == null");
                        MethodCollector.o(8627);
                        throw runtimeException2;
                    }
                } else {
                    RuntimeException runtimeException3 = new RuntimeException(r2.LJ());
                    MethodCollector.o(8627);
                    throw runtimeException3;
                }
            } catch (Exception e) {
                RuntimeException runtimeException4 = new RuntimeException(e);
                MethodCollector.o(8627);
                throw runtimeException4;
            }
        } else {
            LoadedModelList loadedModelList2 = serverConfig.getLoadedModelList();
            MethodCollector.o(8627);
            return loadedModelList2;
        }
    }

    private 0Gp<ModelInfo> requestSingleModel(final int i, final String str) {
        return 0Gp.LIZ(new Callable<ModelInfo>() {
            static {
                Covode.recordClassIndex(125198);
            }

            public ModelInfo call() {
                SingleAlgorithmModelResponse runDirectly = new FetchModelInfoByNameTask(ModelConfigArbiter.this.mConfig, str, i, (String) null, (String) null, (WeakHandler) null).runDirectly();
                if (runDirectly == null || runDirectly.getData() == null || runDirectly.getData().getFile_url() == null) {
                    return null;
                }
                return new ModelInfo(runDirectly.getData());
            }
        }, this.mConfig.getExecutor(), (0Gf) null);
    }

    public ModelInfo getSingleModelInfoNonBlocking(final int i, final String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        ModelInfo modelInfo = this.mSingleModelMap.get(str);
        if (modelInfo == null) {
            0Gp.LIZ(new Callable<Object>() {
                static {
                    Covode.recordClassIndex(125203);
                }

                public Object call() {
                    ModelConfigArbiter.this.getSingleModelInfo(i, str);
                    return null;
                }
            });
        }
        return modelInfo;
    }

    public synchronized ModelInfo getSingleModelInfo(int i, String str) {
        MethodCollector.i(8631);
        if (TextUtils.isEmpty(str)) {
            MethodCollector.o(8631);
            return null;
        }
        ModelInfo modelInfo = this.mSingleModelMap.get(str);
        if (modelInfo == null) {
            0Gp<ModelInfo> requestSingleModel = requestSingleModel(i, str);
            try {
                requestSingleModel.LJFF();
                if (!requestSingleModel.LIZJ()) {
                    modelInfo = (ModelInfo) requestSingleModel.LIZLLL();
                    this.mSingleModelMap.put(str, modelInfo);
                } else {
                    RuntimeException runtimeException = new RuntimeException(requestSingleModel.LJ());
                    MethodCollector.o(8631);
                    throw runtimeException;
                }
            } catch (Exception e) {
                RuntimeException runtimeException2 = new RuntimeException(e);
                MethodCollector.o(8631);
                throw runtimeException2;
            }
        }
        MethodCollector.o(8631);
        return modelInfo;
    }
}
