package com.ycwl.basic.face.pipeline.stages;

import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import com.ycwl.basic.mapper.SourceMapper;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.repository.MemberRelationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 持久化关联关系Stage
 * 负责过滤并保存源文件关联关系到数据库
 *
 * 职责:
 * 1. 从context.memberSourceList读取关联关系
 * 2. 过滤已存在的关联关系和无效的source引用
 * 3. 保存到数据库
 * 4. 清除缓存
 */
@Slf4j
@Component
@StageConfig(
    stageId = "persist_relations",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "持久化源文件关联关系"
)
public class PersistRelationsStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private SourceMapper sourceMapper;

    @Autowired
    private MemberRelationRepository memberRelationRepository;

    @Autowired
    private com.ycwl.basic.biz.FaceStatusManager faceStatusManager;

    @Override
    public String getName() {
        return "PersistRelations";
    }

    @Override
    protected boolean shouldExecuteByBusinessLogic(FaceMatchingContext context) {
        // 只有当memberSourceList不为空时才执行
        List<MemberSourceEntity> memberSourceList = context.getMemberSourceList();
        if (memberSourceList == null || memberSourceList.isEmpty()) {
            log.debug("memberSourceList为空，跳过持久化，faceId={}", context.getFaceId());
            return false;
        }
        return true;
    }

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        List<MemberSourceEntity> memberSourceEntityList = context.getMemberSourceList();
        Long faceId = context.getFaceId();

        // 防御性检查：memberSourceList为空
        if (memberSourceEntityList == null || memberSourceEntityList.isEmpty()) {
            log.debug("memberSourceList为空，跳过持久化，faceId={}", faceId);
            return StageResult.skipped("memberSourceList为空");
        }

        try {
            // 1. 过滤已存在的关联关系
            List<MemberSourceEntity> existingFiltered = sourceMapper.filterExistingRelations(memberSourceEntityList);

            // 2. 过滤无效的source引用
            List<MemberSourceEntity> validFiltered = sourceMapper.filterValidSourceRelations(existingFiltered);

            if (!validFiltered.isEmpty()) {
                // 3. 保存到数据库
                sourceMapper.addRelations(validFiltered);

                log.debug("创建关联关系: faceId={}, 原始数量={}, 过滤后数量={}",
                        faceId, memberSourceEntityList.size(), validFiltered.size());
            } else {
                log.warn("没有有效的关联关系可创建: faceId={}, 原始数量={}",
                        faceId, memberSourceEntityList.size());
                return StageResult.skipped("没有有效的关联关系可创建");
            }

            // 4. 清除缓存
            memberRelationRepository.clearSCacheByFace(faceId);
            faceStatusManager.invalidatePuzzleSourceVersion(faceId);

            return StageResult.success(String.format("持久化了%d条关联关系", validFiltered.size()));

        } catch (Exception e) {
            log.error("持久化关联关系失败，faceId={}", faceId, e);
            return StageResult.failed("保存关联关系失败", e);
        }
    }
}
