package cn.nianxx.thhotel.platform.debug.repository;

import cn.nianxx.thhotel.platform.debug.common.dto.DebugEmlSuperAgentRunDraft;
import cn.nianxx.thhotel.platform.debug.common.dto.DebugEmlSuperAgentRunSnapshot;
import cn.nianxx.thhotel.platform.debug.common.dto.DebugEmlSuperAgentRunStatusUpdate;
import cn.nianxx.thhotel.platform.debug.common.dto.DebugEmlSuperAgentRunUpdate;
import cn.nianxx.thhotel.platform.debug.domain.DebugEmlSuperAgentRunEntity;
import cn.nianxx.thhotel.platform.debug.mapper.DebugEmlSuperAgentRunMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import java.util.Optional;
import org.springframework.stereotype.Repository;

/**
 * Debug EML 运行 MyBatis 持久化实现。负责 Entity 转换，不把 Mapper 暴露给 Service。
 */
@Repository
public class MybatisDebugEmlSuperAgentRunRepository implements DebugEmlSuperAgentRunRepository {

    private final DebugEmlSuperAgentRunMapper runMapper;

    /**
     * 注入 Debug EML Mapper。
     */
    public MybatisDebugEmlSuperAgentRunRepository(DebugEmlSuperAgentRunMapper runMapper) {
        this.runMapper = runMapper;
    }

    /**
     * 新建 Debug 运行记录，初始只保存酒店、标签和状态。
     */
    @Override
    public Long insert(DebugEmlSuperAgentRunDraft draft) {
        DebugEmlSuperAgentRunEntity entity = new DebugEmlSuperAgentRunEntity();
        entity.setHotelId(draft.hotelId());
        entity.setRunLabel(draft.runLabel());
        entity.setRunStatus(draft.runStatus());
        entity.setCreatedAt(draft.createdAt());
        entity.setUpdatedAt(draft.createdAt());
        runMapper.insert(entity);
        return entity.getId();
    }

    /**
     * 回填 Debug 运行结果；调用方负责保证错误摘要已经脱敏。
     */
    @Override
    public void updateResult(DebugEmlSuperAgentRunUpdate update) {
        LambdaUpdateWrapper<DebugEmlSuperAgentRunEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DebugEmlSuperAgentRunEntity::getId, update.id())
                .set(DebugEmlSuperAgentRunEntity::getSourceMessageId, update.sourceMessageId())
                .set(DebugEmlSuperAgentRunEntity::getExternalMessageId, update.externalMessageId())
                .set(DebugEmlSuperAgentRunEntity::getExternalConversationId, update.externalConversationId())
                .set(DebugEmlSuperAgentRunEntity::getOriginalFileName, update.originalFileName())
                .set(DebugEmlSuperAgentRunEntity::getOriginalEmlOssUrl, update.originalEmlOssUrl())
                .set(DebugEmlSuperAgentRunEntity::getOriginalEmlSha256, update.originalEmlSha256())
                .set(DebugEmlSuperAgentRunEntity::getPayloadJson, update.payloadJson())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentSessionId, update.superagentSessionId())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentRunId, update.superagentRunId())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentProfileId, update.superagentProfileId())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentProfileVersionId, update.superagentProfileVersionId())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentModelName, update.superagentModelName())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentRawAnswer, update.superagentRawAnswer())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentParsedJson, update.superagentParsedJson())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentInputTokens, update.superagentInputTokens())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentOutputTokens, update.superagentOutputTokens())
                .set(DebugEmlSuperAgentRunEntity::getSuperagentTotalTokens, update.superagentTotalTokens())
                .set(DebugEmlSuperAgentRunEntity::getRunStatus, update.runStatus())
                .set(DebugEmlSuperAgentRunEntity::getSafeErrorSummary, update.safeErrorSummary())
                .set(DebugEmlSuperAgentRunEntity::getUpdatedAt, update.updatedAt());
        runMapper.update(null, wrapper);
    }

    /**
     * 只更新运行状态和安全错误摘要，保留前面阶段已经写入的调试上下文。
     */
    @Override
    public void updateStatus(DebugEmlSuperAgentRunStatusUpdate update) {
        LambdaUpdateWrapper<DebugEmlSuperAgentRunEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DebugEmlSuperAgentRunEntity::getId, update.id())
                .set(DebugEmlSuperAgentRunEntity::getRunStatus, update.runStatus())
                .set(DebugEmlSuperAgentRunEntity::getSafeErrorSummary, update.safeErrorSummary())
                .set(DebugEmlSuperAgentRunEntity::getUpdatedAt, update.updatedAt());
        runMapper.update(null, wrapper);
    }

    /**
     * 按 ID 查询 Debug 运行安全快照。
     */
    @Override
    public Optional<DebugEmlSuperAgentRunSnapshot> findById(Long id) {
        return Optional.ofNullable(runMapper.selectById(id)).map(this::toSnapshot);
    }

    /**
     * 将数据库 Entity 转换为安全快照。
     */
    private DebugEmlSuperAgentRunSnapshot toSnapshot(DebugEmlSuperAgentRunEntity entity) {
        return new DebugEmlSuperAgentRunSnapshot(
                entity.getId(),
                entity.getHotelId(),
                entity.getRunStatus(),
                entity.getSourceMessageId(),
                entity.getCreatedAt());
    }
}
