package tech.easyflow.skill.repository;

import com.easyagents.skill.model.SkillDescriptor;
import com.easyagents.skill.repository.SkillRepository;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Repository;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.skill.entity.Skill;
import tech.easyflow.skill.service.SkillService;
import tech.easyflow.skill.support.SkillModelConverter;

import java.math.BigInteger;
import java.util.List;
import java.util.Optional;

/**
 * 基于数据库的 easy-agents-skill 仓储适配器。
 */
@Repository
public class DBSkillRepository implements SkillRepository {

    private final SkillService skillService;

    /**
     * 创建数据库 Skill 仓储。
     *
     * @param skillService Skill 服务
     */
    public DBSkillRepository(SkillService skillService) {
        this.skillService = skillService;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void save(com.easyagents.skill.model.Skill skill) {
        Skill entity = SkillModelConverter.fromAgentSkill(skill);
        BigInteger parsedId = tryParseId(skill.getId());
        if (parsedId != null && skillService.getById(parsedId) != null) {
            entity.setId(parsedId);
            skillService.updateDraft(entity);
            return;
        }
        skillService.saveDraft(entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<com.easyagents.skill.model.Skill> get(String skillId) {
        BigInteger id = parseId(skillId);
        Skill skill = skillService.getDetail(id);
        return Optional.of(SkillModelConverter.toAgentSkill(skill));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Optional<SkillDescriptor> getDescriptor(String skillId) {
        BigInteger id = parseId(skillId);
        Skill skill = skillService.getById(id);
        if (skill == null) {
            return Optional.empty();
        }
        return Optional.of(new SkillDescriptor(String.valueOf(skill.getId()), skill.getName(), skill.getDescription(),
                new com.easyagents.skill.model.SkillMetadata(skill.getMetadataJson())));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<SkillDescriptor> listDescriptors() {
        return skillService.list().stream()
                .map(skill -> new SkillDescriptor(String.valueOf(skill.getId()), skill.getName(), skill.getDescription(),
                        new com.easyagents.skill.model.SkillMetadata(skill.getMetadataJson())))
                .toList();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void delete(String skillId) {
        skillService.removeAggregate(parseId(skillId));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean exists(String skillId) {
        BigInteger id = parseId(skillId);
        return skillService.count(QueryWrapper.create().eq(Skill::getId, id)) > 0;
    }

    private BigInteger parseId(String skillId) {
        if (skillId == null || skillId.isBlank()) {
            throw new BusinessException("Skill ID 不能为空");
        }
        return new BigInteger(skillId);
    }

    private BigInteger tryParseId(String skillId) {
        if (skillId == null || skillId.isBlank()) {
            return null;
        }
        try {
            return new BigInteger(skillId);
        } catch (NumberFormatException ignored) {
            return null;
        }
    }
}
