package com.infoepoch.pms.agent.domain.care.model;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * 会话短记忆。
 *
 * @param sessionId 会话唯一标识，由调用方透传
 * @param taskType 当前会话对应的任务类型
 * @param requestedCount 当前轮次希望返回的推荐数量
 * @param activityIntent 当前会话识别出的活动语义或活动名称
 * @param preferenceSummary 当前会话识别出的偏好摘要
 * @param searchConditions 当前会话累计的筛选条件
 * @param nextPageNo 推荐用户场景下下一次继续检索的分页页码
 * @param deliveredIds 当前会话已经下发给客户端的活动或用户 ID 集合
 * @param updatedAt 会话状态最后更新时间
 */
public record CareConversationState(
        String sessionId,
        CareTaskType taskType,
        int requestedCount,
        String activityIntent,
        String preferenceSummary,
        Map<String, Object> searchConditions,
        int nextPageNo,
        Set<String> deliveredIds,
        LocalDateTime updatedAt
) {

    public CareConversationState {
        searchConditions = sanitize(searchConditions);
        deliveredIds = deliveredIds == null ? Collections.emptySet() : Collections.unmodifiableSet(new LinkedHashSet<>(deliveredIds));
        activityIntent = activityIntent == null ? "" : activityIntent.trim();
        preferenceSummary = preferenceSummary == null ? "" : preferenceSummary.trim();
        updatedAt = updatedAt == null ? LocalDateTime.now() : updatedAt;
    }

    /**
     * 基于当前查询创建一份初始会话状态。
     */
    public static CareConversationState initial(String sessionId, CareQuery query) {
        return new CareConversationState(
                sessionId,
                query.taskType(),
                query.requestedCount(),
                query.activityIntent(),
                query.preferenceSummary(),
                query.searchConditions(),
                1,
                Collections.emptySet(),
                LocalDateTime.now()
        );
    }

    /**
     * 推进会话游标，并累计本轮已经下发的推荐对象。
     */
    public CareConversationState advance(int nextPageNo, Collection<String> newDeliveredIds) {
        LinkedHashSet<String> ids = new LinkedHashSet<>(deliveredIds);
        if (newDeliveredIds != null) {
            ids.addAll(newDeliveredIds);
        }
        return new CareConversationState(
                sessionId,
                taskType,
                requestedCount,
                activityIntent,
                preferenceSummary,
                searchConditions,
                nextPageNo,
                ids,
                LocalDateTime.now()
        );
    }

    /**
     * 使用新的理解结果覆盖当前会话的任务语义，并重置分页与已下发记录。
     */
    public CareConversationState rewriteFromQuery(CareQuery query) {
        return new CareConversationState(
                sessionId,
                query.taskType(),
                query.requestedCount(),
                query.activityIntent(),
                query.preferenceSummary(),
                query.searchConditions(),
                1,
                Collections.emptySet(),
                LocalDateTime.now()
        );
    }

    /**
     * 清洗筛选条件，仅保留非空键值对。
     */
    private static Map<String, Object> sanitize(Map<String, Object> searchConditions) {
        if (searchConditions == null || searchConditions.isEmpty()) {
            return Collections.emptyMap();
        }
        LinkedHashMap<String, Object> sanitized = new LinkedHashMap<>();
        searchConditions.forEach((key, value) -> {
            if (key != null && value != null) {
                sanitized.put(key, value);
            }
        });
        return Map.copyOf(sanitized);
    }
}
