package com.infoepoch.pms.agent.domain.care.log.hook;

import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.agent.hook.HookPosition;
import com.alibaba.cloud.ai.graph.agent.hook.messages.AgentCommand;
import com.alibaba.cloud.ai.graph.agent.hook.messages.MessagesModelHook;
import com.alibaba.cloud.ai.graph.agent.hook.messages.UpdatePolicy;
import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.domain.care.log.CareTraceLogSupport;
import org.springframework.ai.chat.messages.Message;

import java.util.List;

/**
 * care agent 模型请求与响应日志 hook。
 */
public class CareModelMessageLogHook extends MessagesModelHook {

    private static final String HOOK_NAME = "careModelMessageLogHook";

    @Override
    public String getName() {
        return HOOK_NAME;
    }

    @Override
    public int getOrder() {
        return 100;
    }

    @Override
    public HookPosition[] getHookPositions() {
        return new HookPosition[]{HookPosition.BEFORE_MODEL, HookPosition.AFTER_MODEL};
    }

    @Override
    public AgentCommand beforeModel(List<Message> messages, RunnableConfig runnableConfig) {
        String scene = CareTraceLogSupport.resolveScene(runnableConfig);
        LogHelper.info(this, CareTraceLogSupport.formatModelMessages(
                CareTraceLogSupport.resolveTraceId(runnableConfig),
                CareTraceLogSupport.resolveSessionId(runnableConfig),
                scene + "模型请求",
                messages
        ));
        return new AgentCommand(messages, UpdatePolicy.REPLACE);
    }

    @Override
    public AgentCommand afterModel(List<Message> messages, RunnableConfig runnableConfig) {
        String scene = CareTraceLogSupport.resolveScene(runnableConfig);
        LogHelper.info(this, CareTraceLogSupport.formatModelResponse(
                CareTraceLogSupport.resolveTraceId(runnableConfig),
                CareTraceLogSupport.resolveSessionId(runnableConfig),
                scene + "模型完整返回",
                CareTraceLogSupport.findLastAssistantText(messages)
        ));
        return new AgentCommand(messages, UpdatePolicy.REPLACE);
    }
}
