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
 * 负责根据业务规则确定哪些源文件可以免费访问
 *
 * 职责:
 * 1. 从context.memberSourceList读取源文件关联列表
 * 2. 调用sourceRelationProcessor.processFreeSourceLogic()确定免费源文件
 * 3. 更新context.freeSourceIds
 *
 * 前置条件: context.memberSourceList不为空
 * 后置条件: context.freeSourceIds已设置
 */
@Slf4j
@Component
@StageConfig(
    stageId = "process_free_source",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "处理免费源文件逻辑",
    defaultEnabled = true
)
public class ProcessFreeSourceStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private SourceRelationProcessor sourceRelationProcessor;

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

    @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 scenicId = context.getFace().getScenicId();
        boolean isNew = context.isNew();
        Long faceId = context.getFaceId();

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

        try {
            // 处理免费逻辑
            List<Long> freeSourceIds = sourceRelationProcessor.processFreeSourceLogic(
                    memberSourceEntityList, scenicId, isNew);

            context.setFreeSourceIds(freeSourceIds);

            log.info("免费源文件处理完成: faceId={}, 总源文件数={}, 免费数={}",
                    faceId, memberSourceEntityList.size(), freeSourceIds != null ? freeSourceIds.size() : 0);

            return StageResult.success(String.format("确定了%d个免费源文件",
                    freeSourceIds != null ? freeSourceIds.size() : 0));

        } catch (Exception e) {
            log.error("处理免费源文件失败，faceId={}", faceId, e);
            // 免费逻辑失败不影响主流程，返回降级
            return StageResult.degraded("免费源文件处理失败: " + e.getMessage());
        }
    }
}
