/*
 * Copyright (C) 2025 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.ai.sample.appbuilder;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.baidubce.appbuilder.base.exception.AppBuilderServerException;
import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;

import android.text.TextUtils;
import android.util.Log;

public class AiAppBuilderClient {
    private static final String TAG = "AiAppBuilderClient";
    private final ExecutorService mExecutor;
    private AppBuilderClient mClient;
    private String mConversationId;
    private OnAppBuilderClientListener mListener;

    public AiAppBuilderClient(String appId, String appBuilderToken) {
         System.setProperty("APPBUILDER_TOKEN", appBuilderToken);
         mClient = new AppBuilderClient(appId);
         mExecutor = Executors.newFixedThreadPool(3);
     }

    public boolean createConversationAsync() {
        if (mExecutor.isShutdown()) {
            return false;
        }
        mExecutor.submit(() -> {
            try {
                mConversationId = mClient.createConversation();
                if (mListener != null) {
                    if (!TextUtils.isEmpty(mConversationId)) {
                        mListener.onCreateConversation(true, mConversationId);
                    } else {
                        mListener.onCreateConversation(false, null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return true;
    }

    public boolean sendQueryAsync(String query) {
        if (mClient == null || TextUtils.isEmpty(mConversationId)) {
            return false;
        }
        if (mExecutor.isShutdown()) {
            return false;
        }
        mExecutor.submit(() -> {
            AppBuilderClientIterator itor = null;
            try {
                itor = mClient.run(query, mConversationId,
                        new String[] {}, false);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (AppBuilderServerException e) {
                e.printStackTrace();
            }
            StringBuilder answer = new StringBuilder();
            while (itor.hasNext()) {
                AppBuilderClientResult response = itor.next();
                answer.append(response.getAnswer());
            }
//            Log.d(TAG, "answer: " + answer);

            if (mListener != null) {
                if (!TextUtils.isEmpty(answer)) {
                    mListener.onQueryAnswer(true, answer.toString());
                } else {
                    mListener.onQueryAnswer(false, null);
                }
            }
        });

        return true;
    }

    public void setOnAppBuilderClientListener(OnAppBuilderClientListener listener) {
        this.mListener = listener;
    }

    public interface OnAppBuilderClientListener {
        void onCreateConversation(boolean status, String conversationId);
        void onQueryAnswer(boolean status, String answer);
    }

    public void onDestroy() {
        mExecutor.shutdown();
        Log.i(TAG, "AiAppBuilderClient onDestroy");
    }

}
