package com.infoepoch.pms.agent.platform.agent.adapter.out.persistence;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.common.utils.OracleUtils;
import com.infoepoch.pms.agent.platform.agent.domain.Agent;
import com.infoepoch.pms.agent.platform.agent.domain.AgentField;
import com.infoepoch.pms.agent.platform.agent.domain.irepository.AgentCriteria;
import com.infoepoch.pms.agent.platform.agent.domain.irepository.IAgentRepository;
import com.infoepoch.pms.agent.platform.model.adapter.out.persistence.AiModelConfigRepository;
import com.infoepoch.pms.agent.platform.shared.exception.ValidationException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 智能体定义表仓储实现
 */
@Repository
public class AgentRepository implements IAgentRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(Agent entity) {
        String sql = "INSERT INTO AI_AGENTS(ID, NAME, DESCRIPTION, SYSTEM_PROMPT, SUBMIT_URL, MODEL_CONFIG_ID, ENABLED, CREATED_AT, UPDATED_AT, CONTEXT_WINDOW_SIZE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getName(), entity.getDescription(), entity.getSystemPrompt(), entity.getSubmitUrl(), entity.getModelConfigId(), entity.isEnabled(), entity.getCreatedAt() != null ? Timestamp.valueOf(entity.getCreatedAt()) : null, entity.getUpdatedAt() != null ? Timestamp.valueOf(entity.getUpdatedAt()) : null, entity.getContextWindowSize());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增 智能体定义表 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(Agent entity) {
        String sql = "UPDATE AI_AGENTS SET NAME = ?, DESCRIPTION = ?, SYSTEM_PROMPT = ?, SUBMIT_URL = ?, MODEL_CONFIG_ID = ?, ENABLED = ?, CREATED_AT = ?, UPDATED_AT = ?, CONTEXT_WINDOW_SIZE = ? WHERE ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getName(), entity.getDescription(), entity.getSystemPrompt(), entity.getSubmitUrl(), entity.getModelConfigId(), entity.isEnabled(), entity.getCreatedAt() != null ? Timestamp.valueOf(entity.getCreatedAt()) : null, entity.getUpdatedAt() != null ? Timestamp.valueOf(entity.getUpdatedAt()) : null, entity.getContextWindowSize(), entity.getId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新 智能体定义表 数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<Agent> list) {
        String sql = "INSERT INTO AI_AGENTS(ID, NAME, DESCRIPTION, SYSTEM_PROMPT, SUBMIT_URL, MODEL_CONFIG_ID, ENABLED, CREATED_AT, UPDATED_AT, CONTEXT_WINDOW_SIZE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Agent item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getDescription());
                ps.setString(++j, item.getSystemPrompt());
                ps.setString(++j, item.getSubmitUrl());
                ps.setString(++j, item.getModelConfigId());
                ps.setBoolean(++j, item.isEnabled());
                ps.setTimestamp(++j, item.getCreatedAt() != null ? Timestamp.valueOf(item.getCreatedAt()) : null);
                ps.setTimestamp(++j, item.getUpdatedAt() != null ? Timestamp.valueOf(item.getUpdatedAt()) : null);
                ps.setObject(++j, item.getContextWindowSize());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<Agent> list) {
        String sql = "UPDATE AI_AGENTS SET NAME = ?, DESCRIPTION = ?, SYSTEM_PROMPT = ?, SUBMIT_URL = ?, MODEL_CONFIG_ID = ?, ENABLED = ?, CREATED_AT = ?, UPDATED_AT = ?, CONTEXT_WINDOW_SIZE = ? WHERE ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                Agent item = list.get(i);
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getDescription());
                ps.setString(++j, item.getSystemPrompt());
                ps.setString(++j, item.getSubmitUrl());
                ps.setString(++j, item.getModelConfigId());
                ps.setBoolean(++j, item.isEnabled());
                ps.setTimestamp(++j, item.getCreatedAt() != null ? Timestamp.valueOf(item.getCreatedAt()) : null);
                ps.setTimestamp(++j, item.getUpdatedAt() != null ? Timestamp.valueOf(item.getUpdatedAt()) : null);
                ps.setObject(++j, item.getContextWindowSize());
                ps.setString(++j, item.getId());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 删除
     */
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM AI_AGENTS WHERE ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("删除 智能体定义表 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 根据Id查询
     */
    @Override
    public Agent selectById(String id) {
        String sql = "SELECT * FROM AI_AGENTS WHERE ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new AgentRowMapper(), id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询单个对象
     */
    @Override
    public Agent selectOneByCriteria(AgentCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_AGENTS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1);
        try {
            return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new AgentRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询对象集合
     */
    @Override
    public List<Agent> selectByCriteria(AgentCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_AGENTS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new AgentRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件分页查询对象结合
     */
    @Override
    public List<Agent> selectCriteriaByPage(AgentCriteria criteria, int pageNum, int pageSize) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM AI_AGENTS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), pageNum, pageSize);
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new AgentRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据条件查询对象总记录数
     */
    @Override
    public Integer selectCountByCriteria(AgentCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT COUNT(*) FROM AI_AGENTS ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        int count = jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), int.class);
        return count;
    }

    @Override
    public Optional<Agent> findById(String id) {
        return Optional.ofNullable(id).map(this::selectById);
    }

    @Override
    public Agent save(Agent entity) {
        if (entity == null) {
            return null;
        }
        if (findById(entity.getId()).isPresent()) {
            update(entity);
        } else {
            insert(entity);
        }
        return entity;
    }

    @Override
    public boolean existsById(String id) {
        return findById(id).isPresent();
    }

    @Override
    public boolean existsByName(String name) {
        AgentCriteria criteria = new AgentCriteria();
        criteria.setName(name == null ? null : name.trim());
        return selectCountByCriteria(criteria) > 0;
    }

    @Override
    public boolean existsByNameAndIdNot(String name, String id) {
        AgentCriteria criteria = new AgentCriteria();
        criteria.setName(name == null ? null : name.trim());
        List<Agent> agents = selectByCriteria(criteria);
        if (agents == null) {
            return false;
        }
        return agents.stream().anyMatch(agent -> !Objects.equals(agent.getId(), id));
    }

    @Override
    public boolean existsByModelConfigId(String modelConfigId) {
        AgentCriteria criteria = new AgentCriteria();
        criteria.setModelConfigId(modelConfigId);
        return selectCountByCriteria(criteria) > 0;
    }

    @Override
    public List<Agent> findAllByOrderByCreatedAtDesc() {
        List<Agent> agents = selectByCriteria(null);
        if (agents == null) {
            return List.of();
        }
        return agents.stream()
                .sorted((left, right) -> right.getCreatedAt().compareTo(left.getCreatedAt()))
                .toList();
    }

    @Override
    public List<Agent> findByIdInAndEnabledTrue(Set<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return List.of();
        }
        AgentCriteria criteria = new AgentCriteria();
        criteria.setEnabled(Boolean.TRUE);
        List<Agent> agents = selectByCriteria(criteria);
        if (agents == null) {
            return List.of();
        }
        return agents.stream()
                .filter(agent -> ids.contains(agent.getId()))
                .sorted((left, right) -> left.getCreatedAt().compareTo(right.getCreatedAt()))
                .toList();
    }

    /**
     * RowMapper
     */
    private class AgentRowMapper implements RowMapper<Agent> {
        @Override
        public Agent mapRow(ResultSet rs, int i) throws SQLException {
            return new Agent(
                    rs.getString("ID"),
                    rs.getString("NAME"),
                    rs.getString("DESCRIPTION"),
                    rs.getString("SYSTEM_PROMPT"),
                    rs.getString("SUBMIT_URL"),
                    rs.getString("MODEL_CONFIG_ID"),
                    rs.getObject("ENABLED") != null ? rs.getBoolean("ENABLED") : true,
                    rs.getTimestamp("CREATED_AT").toLocalDateTime(),
                    rs.getTimestamp("UPDATED_AT").toLocalDateTime(),
                    rs.getObject("CONTEXT_WINDOW_SIZE") != null ? rs.getInt("CONTEXT_WINDOW_SIZE") : 0
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(AgentCriteria criteria) {
        Map<String, Object> andMap = new LinkedHashMap<>();
        if (criteria == null)
            return andMap;
        //if (criteria.byId())
        //    andMap.put(criteria.getId() == null ? " T_Id IS NULL " : " T_Id = ? ", criteria.getId());

        //智能体名称
        if (criteria.byName())
            andMap.put(criteria.getName() == null ? " NAME IS NULL " : " NAME = ? ", criteria.getName());
        //智能体名称（LIKE）
        if (criteria.byNameContain())
            andMap.put(" NAME LIKE ? ", "%" + criteria.getNameContain() + "%");
        //指定模型配置，为空则使用全局默认模型
        if (criteria.byModelConfigId())
            andMap.put(criteria.getModelConfigId() == null ? " MODEL_CONFIG_ID IS NULL " : " MODEL_CONFIG_ID = ? ", criteria.getModelConfigId());
        //是否启用
        if (criteria.byEnabled())
            andMap.put(criteria.getEnabled() == null ? " ENABLED IS NULL " : " ENABLED = ? ", criteria.getEnabled());
        return andMap;
    }

}
