package com.agent.management.service;

import com.agent.management.model.entity.ChatSession;
import com.agent.management.repository.ChatMessageRepository;
import com.agent.management.repository.ChatSessionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * Agent 对话会话 Service。
 *
 * <p>对应设计文档 {@code docs/design/agent-chat-page-design.md} §4.3.1。
 * 承载会话 CRUD、{@code last_message_at} 触达、自动标题。</p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatSessionService {

    private final ChatSessionRepository sessionRepo;
    private final ChatMessageRepository messageRepo;

    /** 列出所有 ACTIVE 会话，置顶优先，其次按 last_message_at 倒序 */
    public List<ChatSession> listActive() {
        return sessionRepo.findActiveOrderByPinnedAndLastMessageAtDesc("ACTIVE");
    }

    public Optional<ChatSession> findById(Long id) {
        return sessionRepo.findById(id);
    }

    public Optional<ChatSession> findByUuid(String uuid) {
        return sessionRepo.findBySessionUuid(uuid);
    }

    /**
     * 创建新会话。sessionUuid / hermesSession 在此显式生成；PrePersist 仅作兜底。
     */
    @Transactional
    public ChatSession create(String title, Long modelId, String skillFolder) {
        ChatSession s = new ChatSession();
        String uuid = UUID.randomUUID().toString();
        s.setSessionUuid(uuid);
        s.setHermesSession("chat-" + uuid.replace("-", "").substring(0, 12));
        s.setTitle(title);
        s.setModelId(modelId);
        s.setSkillFolder(skillFolder);
        s.setStatus("ACTIVE");
        return sessionRepo.save(s);
    }

    @Transactional
    public ChatSession updateTitle(Long id, String title) {
        ChatSession s = sessionRepo.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("会话不存在: " + id));
        s.setTitle(title);
        return sessionRepo.save(s);
    }

    /** 切换置顶状态。 */
    @Transactional
    public ChatSession setPinned(Long id, boolean pinned) {
        ChatSession s = sessionRepo.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("会话不存在: " + id));
        s.setPinned(pinned);
        return sessionRepo.save(s);
    }

    /**
     * 归档（软删除）：仅在列表中隐藏，消息树保留供审计。
     */
    @Transactional
    public void archive(Long id) {
        ChatSession s = sessionRepo.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("会话不存在: " + id));
        s.setStatus("ARCHIVED");
        sessionRepo.save(s);
    }

    /**
     * 触达 last_message_at + updatedAt。每次新消息/完成 run 后调用。
     */
    @Transactional
    public void touch(Long id) {
        sessionRepo.touch(id, LocalDateTime.now());
    }

    /**
     * 自动标题：若 title 为空，取最近一条 user 消息内容前 30 字作为标题。
     */
    @Transactional
    public void autoTitleIfNeeded(Long sessionId) {
        var firstUserMsg = messageRepo.findFirstBySessionIdAndRoleAndIsActiveTrueOrderByCreatedAtAsc(
                sessionId, "USER");
        if (firstUserMsg.isEmpty()) {
            return;
        }
        String raw = firstUserMsg.get().getContent();
        if (raw == null || raw.isBlank()) {
            return;
        }
        String title = raw.replaceAll("\\s+", " ").trim();
        if (title.length() > 30) {
            title = title.substring(0, 30) + "…";
        }
        sessionRepo.setTitleIfNull(sessionId, title);
    }
}
