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.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.service.pc.processor.SourceRelationProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 构建源文件关联Stage
 * 负责根据匹配到的样本ID构建member_source关联关系
 *
 * 职责:
 * 1. 从context.sampleListIds读取匹配的样本ID列表
 * 2. 调用sourceRelationProcessor.processMemberSources()生成MemberSourceEntity列表
 * 3. 更新context.memberSourceList
 *
 * 前置条件: context.sampleListIds不为空
 * 后置条件: context.memberSourceList已设置
 */
@Slf4j
@Component
@StageConfig(
    stageId = "build_source_relation",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "构建源文件关联关系"
)
public class BuildSourceRelationStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private SourceRelationProcessor sourceRelationProcessor;

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

    @Override
    protected boolean shouldExecuteByBusinessLogic(FaceMatchingContext context) {
        // 只有当sampleListIds不为空时才执行
        List<Long> sampleListIds = context.getSampleListIds();
        if (sampleListIds == null || sampleListIds.isEmpty()) {
            // 从searchResult中获取
            if (context.getSearchResult() != null) {
                sampleListIds = context.getSearchResult().getSampleListIds();
                context.setSampleListIds(sampleListIds);
            }
        }

        if (sampleListIds == null || sampleListIds.isEmpty()) {
            log.debug("sampleListIds为空，跳过源文件关联，faceId={}", context.getFaceId());
            return false;
        }

        return true;
    }

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        List<Long> sampleListIds = context.getSampleListIds();
        Long faceId = context.getFaceId();

        // 防御性检查：sampleListIds为空
        if (sampleListIds == null || sampleListIds.isEmpty()) {
            // 尝试从searchResult中获取
            if (context.getSearchResult() != null) {
                sampleListIds = context.getSearchResult().getSampleListIds();
                if (sampleListIds != null && !sampleListIds.isEmpty()) {
                    context.setSampleListIds(sampleListIds);
                } else {
                    log.debug("sampleListIds为空，跳过源文件关联，faceId={}", faceId);
                    return StageResult.skipped("sampleListIds为空");
                }
            } else {
                log.debug("sampleListIds为空，跳过源文件关联，faceId={}", faceId);
                return StageResult.skipped("sampleListIds为空");
            }
        }

        try {
            // 处理源文件关联
            List<MemberSourceEntity> memberSourceEntityList =
                    sourceRelationProcessor.processMemberSources(sampleListIds, context.getFace());

            if (memberSourceEntityList == null || memberSourceEntityList.isEmpty()) {
                log.warn("未找到有效的源文件，faceId={}, sampleListIds={}", faceId, sampleListIds);
                return StageResult.skipped("未找到有效的源文件");
            }

            context.setMemberSourceList(memberSourceEntityList);

            log.info("构建源文件关联成功: faceId={}, 关联源文件数={}", faceId, memberSourceEntityList.size());

            return StageResult.success(String.format("构建了%d个源文件关联", memberSourceEntityList.size()));

        } catch (Exception e) {
            log.error("构建源文件关联失败，faceId={}, sampleListIds={}", faceId, sampleListIds, e);
            // 源文件关联失败不影响主流程，返回降级
            return StageResult.degraded("构建源文件关联失败: " + e.getMessage());
        }
    }
}
