package com.ch.jedge.jbot.session;

import com.alibaba.fastjson.JSONArray;
import com.ch.jedge.jbot.JedgeBotGptService;
import com.ch.jedge.jbot.agent.JedgeGdeSession;
import com.ch.jedge.jbot.knbase.JedgeGptApp;
import com.changhong.qlib.util.Log.ISLog;

import static com.ch.jedge.jbot.JEJBotLLMConst.max_history_size;


/**
 *  聊天的会话，需要记录 领域、话题 等约束
 *      需要就如下内容进行缓存。
 *
 *      - 知识：
 *      - 词库：
 *      - 意图
 *      - 活跃关键字： （知识点）
 *
 *  在对话过程中，系统需要根据聊天的内容，手动或动态切换领域和话题等。
 *      领域将更新其后台知识库， 每次命中，可切换其关键字池、
 *      · 加载默认的知识条目、加载其知识条目下的关键字，引导查询多条知识条目在当前对话缓存中
 *      ·
 */



public class JedgeServiceSession {

    public boolean isStream = true;
    public long sid = 0;
    public String currentPrompt = "";
    public String currentResponse = "";

    public boolean knTalk;
    public boolean voiceTalk;
    public String domain;
    public int rn = 6;
    public String currentKnBase;
    public boolean localGlm = true;
    public String cbUri;
    public boolean printSingle = true;
    public String srcMod;
    public long ttl;
    public final JSONArray history_ = new JSONArray();
    public JedgeGdeSession gdeSession;
    private final JedgeGptApp mGdeApp;
    private final JedgeBotGptService mBotService;

    public JedgeServiceSession(JedgeGptApp app, JedgeBotGptService service) {
        mGdeApp = app==null ? new JedgeGptApp(service.getModule(),service,"Null App Stub"):app;
        mBotService = service;
        currentKnBase = app==null?"":app.getAppName();
    }

    public void clearHistory() {
        history_.clear();
    }

    public void append2LastQA(String returnText) {
        ttl = 0;
//        mGdeApp.getMgModule().infoLog(String.format(">>%s", returnText));
        currentResponse += (returnText);
//        mGdeApp.getMgModule().printClientLog(String.format(">>%s", currentResponse));
    }

    public void buildLastHistory() {
        JSONArray qa = new JSONArray();
        qa.add(currentPrompt);
        qa.add(currentResponse);
        currentResponse = "";
        currentPrompt = "";
        history_.add(qa);
        if(history_.size()>max_history_size) {
            history_.remove(0); //移除第0个聊天历史
        }
        String log;
        log =  history_.toJSONString();
        while (log.length()>1460) {
            history_.remove(0); //移除第0个聊天历史
            log =  (history_.toJSONString());
        }
        ISLog.fastLog(log);
        ttl = 0;
    }

    public JedgeGdeSession getGdtSession() {
        if(gdeSession==null) {
            gdeSession = new JedgeGdeSession(mGdeApp, srcMod, cbUri, sid);
            if(mGdeApp!=null)
                mGdeApp.setInitDomain(gdeSession);
        }
        return gdeSession;
    }

    public String getServiceRole() {
        return gdeSession.getServiceRole();
    }

    public JedgeBotGptService getGptBotService() {
        return mBotService;
    }
}
