package org.xyzh.ai.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xyzh.ai.client.DifyApiClient;
import org.xyzh.ai.exception.DifyException;
import org.xyzh.ai.mapper.AiAgentConfigMapper;
import org.xyzh.api.ai.agent.AiAgentConfigService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.ai.TbAiAgentConfig;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.system.utils.LoginUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @description AI智能体配置服务实现
 * @filename AiAgentConfigServiceImpl.java
 * @author AI Assistant
 * @copyright xyzh
 * @since 2025-11-04
 */
@Slf4j
@Service
public class AiAgentConfigServiceImpl implements AiAgentConfigService {

    @Autowired
    private AiAgentConfigMapper agentConfigMapper;

    @Autowired
    private DifyApiClient difyApiClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbAiAgentConfig> createAgent(TbAiAgentConfig agentConfig) {
        ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();

        try {
            // 1. 参数验证
            if (!StringUtils.hasText(agentConfig.getName())) {
                resultDomain.fail("智能体名称不能为空");
                return resultDomain;
            }

            // 2. 检查名称是否已存在
            ResultDomain<Boolean> checkResult = checkNameExists(agentConfig.getName(), null);
            if (checkResult.getData()) {
                resultDomain.fail("智能体名称已存在");
                return resultDomain;
            }

            // 3. 获取当前用户信息
            TbSysUser currentUser = LoginUtil.getCurrentUser();
            if (currentUser == null) {
                resultDomain.fail("用户未登录");
                return resultDomain;
            }

            // 4. 设置默认值
            agentConfig.setID(UUID.randomUUID().toString());
            agentConfig.setCreator(currentUser.getID());
            agentConfig.setUpdater(currentUser.getID());
            agentConfig.setCreateTime(new Date());
            agentConfig.setUpdateTime(new Date());
            agentConfig.setDeleted(false);

            if (agentConfig.getStatus() == null) {
                agentConfig.setStatus(1); // 默认启用
            }

            // 5. 插入数据库
            int rows = agentConfigMapper.insertAgentConfig(agentConfig);
            if (rows > 0) {
                log.info("创建智能体成功: {} - {}", agentConfig.getID(), agentConfig.getName());
                resultDomain.success("创建智能体成功", agentConfig);
                return resultDomain;
            } else {
                resultDomain.fail("创建智能体失败");
                return resultDomain;
            }

        } catch (Exception e) {
            log.error("创建智能体异常", e);
            resultDomain.fail("创建智能体异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbAiAgentConfig> updateAgent(TbAiAgentConfig agentConfig) {
        ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();

        try {
            // 1. 参数验证
            if (!StringUtils.hasText(agentConfig.getID())) {
                resultDomain.fail("智能体ID不能为空");
                return resultDomain;
            }

            // 2. 检查是否存在
            TbAiAgentConfig existing = agentConfigMapper.selectAgentConfigById(agentConfig.getID());
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("智能体不存在");
                return resultDomain;
            }

            // 3. 检查名称是否重复
            if (StringUtils.hasText(agentConfig.getName()) &&
                !agentConfig.getName().equals(existing.getName())) {
                ResultDomain<Boolean> checkResult = checkNameExists(agentConfig.getName(), agentConfig.getID());
                if (checkResult.getData()) {
                    resultDomain.fail("智能体名称已存在");
                    return resultDomain;
                }
            }

            // 4. 获取当前用户
            TbSysUser currentUser = LoginUtil.getCurrentUser();
            if (currentUser == null) {
                resultDomain.fail("用户未登录");
                return resultDomain;
            }

            // 5. 更新字段
            agentConfig.setUpdater(currentUser.getID());
            agentConfig.setUpdateTime(new Date());

            // 6. 执行更新
            int rows = agentConfigMapper.updateAgentConfig(agentConfig);
            if (rows > 0) {
                // 重新查询最新数据
                TbAiAgentConfig updated = agentConfigMapper.selectAgentConfigById(agentConfig.getID());
                log.info("更新智能体成功: {} - {}", agentConfig.getID(), agentConfig.getName());
                resultDomain.success("更新智能体成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新智能体失败");
                return resultDomain;
            }

        } catch (Exception e) {
            log.error("更新智能体异常", e);
            resultDomain.fail("更新智能体异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteAgent(String agentId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();

        try {
            // 1. 参数验证
            if (!StringUtils.hasText(agentId)) {
                resultDomain.fail("智能体ID不能为空");
                return resultDomain;
            }

            // 2. 检查是否存在
            TbAiAgentConfig existing = agentConfigMapper.selectAgentConfigById(agentId);
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("智能体不存在");
                return resultDomain;
            }

            // 3. 获取当前用户
            TbSysUser currentUser = LoginUtil.getCurrentUser();
            if (currentUser == null) {
                resultDomain.fail("用户未登录");
                return resultDomain;
            }

            // 4. 逻辑删除
            TbAiAgentConfig deleteEntity = new TbAiAgentConfig();
            deleteEntity.setID(agentId);
            deleteEntity.setUpdater(currentUser.getID());
            
            int rows = agentConfigMapper.deleteAgentConfig(deleteEntity);
            if (rows > 0) {
                log.info("删除智能体成功: {} - {}", agentId, existing.getName());
                resultDomain.success("删除智能体成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("删除智能体失败");
                return resultDomain;
            }

        } catch (Exception e) {
            log.error("删除智能体异常", e);
            resultDomain.fail("删除智能体异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbAiAgentConfig> getAgentById(String agentId) {
        ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();

        try {
            if (!StringUtils.hasText(agentId)) {
                resultDomain.fail("智能体ID不能为空");
                return resultDomain;
            }

            TbAiAgentConfig agent = agentConfigMapper.selectAgentConfigById(agentId);
            if (agent == null || agent.getDeleted()) {
                resultDomain.fail("智能体不存在");
                return resultDomain;
            }

            resultDomain.success("查询成功", agent);
            return resultDomain;

        } catch (Exception e) {
            log.error("查询智能体异常", e);
            resultDomain.fail("查询智能体异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbAiAgentConfig> listEnabledAgents() {
        ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();

        try {
            TbAiAgentConfig filter = new TbAiAgentConfig();
            filter.setStatus(1); // 只查询启用的

            List<TbAiAgentConfig> agents = agentConfigMapper.selectAgentConfigs(filter);
            resultDomain.success("查询成功", agents);
            return resultDomain;

        } catch (Exception e) {
            log.error("查询启用智能体列表异常", e);
            resultDomain.fail("查询失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbAiAgentConfig> listAgents(TbAiAgentConfig filter) {
        ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();

        try {
            List<TbAiAgentConfig> agents = agentConfigMapper.selectAgentConfigs(filter);
            resultDomain.success("查询成功", agents);
            return resultDomain;

        } catch (Exception e) {
            log.error("查询智能体列表异常", e);
            resultDomain.fail("查询失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public PageDomain<TbAiAgentConfig> pageAgents(TbAiAgentConfig filter, PageParam pageParam) {
        try {
            // 查询列表
            List<TbAiAgentConfig> agents = agentConfigMapper.selectAgentConfigsPage(filter, pageParam);
            
            // 查询总数
            long total = agentConfigMapper.countAgentConfigs(filter);

            // 构建分页结果
            PageParam resultPageParam = new PageParam(pageParam.getPageNumber(), pageParam.getPageSize());
            resultPageParam.setTotalElements(total);
            resultPageParam.setTotalPages((int) Math.ceil((double) total / pageParam.getPageSize()));
            
            return new PageDomain<>(resultPageParam, agents);

        } catch (Exception e) {
            log.error("分页查询智能体列表异常", e);
            return new PageDomain<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> updateAgentStatus(String agentId, Integer status) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();

        try {
            // 1. 参数验证
            if (!StringUtils.hasText(agentId)) {
                resultDomain.fail("智能体ID不能为空");
                return resultDomain;
            }
            if (status == null || (status != 0 && status != 1)) {
                resultDomain.fail("状态参数无效");
                return resultDomain;
            }

            // 2. 检查是否存在
            TbAiAgentConfig existing = agentConfigMapper.selectAgentConfigById(agentId);
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("智能体不存在");
                return resultDomain;
            }

            // 3. 更新状态
            TbAiAgentConfig update = new TbAiAgentConfig();
            update.setID(agentId);
            update.setStatus(status);
            update.setUpdateTime(new Date());

            TbSysUser currentUser = LoginUtil.getCurrentUser();
            if (currentUser != null) {
                update.setUpdater(currentUser.getID());
            }

            int rows = agentConfigMapper.updateAgentConfig(update);
            if (rows > 0) {
                log.info("更新智能体状态成功: {} - {}", agentId, status == 1 ? "启用" : "禁用");
                resultDomain.success("更新状态成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("更新状态失败");
                return resultDomain;
            }

        } catch (Exception e) {
            log.error("更新智能体状态异常", e);
            resultDomain.fail("更新状态异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> updateDifyConfig(String agentId, String difyAppId, String difyApiKey) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();

        try {
            // 1. 参数验证
            if (!StringUtils.hasText(agentId)) {
                resultDomain.fail("智能体ID不能为空");
                return resultDomain;
            }

            // 2. 检查是否存在
            TbAiAgentConfig existing = agentConfigMapper.selectAgentConfigById(agentId);
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("智能体不存在");
                return resultDomain;
            }

            // 3. 如果提供了Dify配置，验证连接
            if (StringUtils.hasText(difyAppId) && StringUtils.hasText(difyApiKey)) {
                try {
                    // 可以调用Dify API验证配置是否有效
                    // difyApiClient.testConnection(difyApiKey);
                    log.info("Dify配置验证通过");
                } catch (DifyException e) {
                    log.error("Dify配置验证失败", e);
                    resultDomain.fail("Dify配置验证失败: " + e.getMessage());
                    return resultDomain;
                }
            }

            // 4. 更新Dify配置
            TbAiAgentConfig update = new TbAiAgentConfig();
            update.setID(agentId);
            update.setDifyAppId(difyAppId);
            update.setDifyApiKey(difyApiKey);
            update.setUpdateTime(new Date());

            TbSysUser currentUser = LoginUtil.getCurrentUser();
            if (currentUser != null) {
                update.setUpdater(currentUser.getID());
            }

            int rows = agentConfigMapper.updateAgentConfig(update);
            if (rows > 0) {
                log.info("更新智能体Dify配置成功: {}", agentId);
                resultDomain.success("更新Dify配置成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("更新Dify配置失败");
                return resultDomain;
            }

        } catch (Exception e) {
            log.error("更新智能体Dify配置异常", e);
            resultDomain.fail("更新Dify配置异常: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> checkNameExists(String name, String excludeId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();

        try {
            if (!StringUtils.hasText(name)) {
                resultDomain.fail("名称不能为空");
                return resultDomain;
            }

            int count = agentConfigMapper.countAgentConfigByName(name, excludeId);
            resultDomain.success("检查完成", count > 0);
            return resultDomain;

        } catch (Exception e) {
            log.error("检查智能体名称异常", e);
            resultDomain.fail("检查失败: " + e.getMessage());
            return resultDomain;
        }
    }
}
