package com.infoepoch.pms.agent.platform.chat.application;

import com.infoepoch.pms.agent.platform.chat.domain.irepository.ISessionRepository;
import com.infoepoch.pms.agent.platform.chat.domain.Session;
import com.infoepoch.pms.agent.platform.model.application.ModelProvisionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 会话标题生成服务。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SessionTitleService {

    private final ModelProvisionService modelProvisionService;
    private final ISessionRepository sessionRepository;

    private static final String PROMPT = "你是一个会话标题生成助手。根据用户的第一条消息，生成一个简短、准确的中文会话标题。\n" +
            "要求：\n" +
            "- 不超过 15 个字\n" +
            "- 不加引号、标点符号结尾\n" +
            "- 直接返回标题文本，不要任何前缀或解释";

    /**
     * 异步为首轮用户消息生成会话标题。
     *
     * @param sessionId        会话 ID
     * @param firstUserMessage 用户首条消息
     */
    @Async
    public void generateTitleAsync(String sessionId, String firstUserMessage) {
        try {
            log.info("Generating title for session: {}", sessionId);
            ChatModel chatModel = modelProvisionService.create(null);
            Prompt prompt = new Prompt(List.of(
                    new SystemMessage(PROMPT),
                    new UserMessage(firstUserMessage)
            ));

            String title = chatModel.call(prompt).getResult().getOutput().getText();
            log.info("Generated title for session {}: {}", sessionId, title);

            Session session = sessionRepository.selectById(sessionId);
            if (session != null) {
                session.applyTitle(title);
                sessionRepository.update(session);
            }
        } catch (Exception e) {
            log.warn("Failed to generate title for session: {}", sessionId, e);
        }
    }
}
