package work.slhaf.partner.framework.agent.model

import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler
import work.slhaf.partner.framework.agent.factory.component.abstracts.AbstractAgentModule
import work.slhaf.partner.framework.agent.model.pojo.Message
import work.slhaf.partner.framework.agent.support.Result

interface ActivateModel {

    fun chat(messages: List<Message>): Result<String> {
        return ModelRuntimeRegistry.resolveProvider(modelKey())
            .chat(mergeMessages(messages))
            .onFailure { ExceptionReporterHandler.report(it) }
    }

    fun streamChat(
        messages: List<Message>,
        consumer: StreamChatMessageConsumer
    ): Result<Unit> {
        return ModelRuntimeRegistry.resolveProvider(modelKey())
            .streamChat(mergeMessages(messages), consumer)
            .onSuccess { consumer.onComplete() }
            .onFailure { consumer.onError(it) }
    }

    fun <T : Any> formattedChat(messages: List<Message>, responseType: Class<T>): Result<T> {
        return ModelRuntimeRegistry.resolveProvider(modelKey())
            .formattedChat(mergeMessages(messages), responseType)
            .onFailure { ExceptionReporterHandler.report(it) }
    }

    fun mergeMessages(messages: List<Message>): List<Message> {
        if (modulePrompt().isEmpty()) {
            return messages
        }
        return buildList {
            addAll(modulePrompt())
            addAll(messages)
        }
    }

    /**
     * 对应调用的模型配置名称
     */
    fun modelKey(): String {
        return if (this is AbstractAgentModule) {
            this.moduleName
        } else {
            javaClass.simpleName
        }
    }

    fun modulePrompt(): List<Message> = emptyList()
}
