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.facebody.adapter.IFaceBodyAdapter;
import com.ycwl.basic.integration.common.manager.ScenicConfigManager;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.service.pc.ScenicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 准备上下文Stage
 * 负责加载人脸实体、景区配置、识别适配器等必要数据
 *
 * 职责:
 * 1. 加载FaceEntity(如不存在则失败)
 * 2. 检查是否人工选择(是则跳过,除非isNew=true)
 * 3. 加载ScenicConfigManager和IFaceBodyAdapter
 * 4. 更新Context
 */
@Slf4j
@Component
@StageConfig(
    stageId = "prepare_context",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "准备人脸匹配上下文数据"
)
public class PrepareContextStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceRepository faceRepository;

    @Autowired
    private ScenicRepository scenicRepository;

    @Autowired
    private ScenicService scenicService;

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

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        Long faceId = context.getFaceId();
        boolean isNew = context.isNew();

        // 1. 加载人脸实体
        FaceEntity face = faceRepository.getFace(faceId);
        if (face == null) {
            log.warn("人脸不存在，faceId: {}", faceId);
            return StageResult.failed("人脸不存在，faceId: " + faceId);
        }

        context.setFace(face);
        log.debug("加载人脸实体成功: faceId={}, memberId={}, scenicId={}",
                faceId, face.getMemberId(), face.getScenicId());

        // 2. 检查是否人工选择
        // 人工选择的无需重新匹配（新用户除外）
        if (!isNew && Integer.valueOf(1).equals(face.getIsManual())) {
            log.info("人工选择的人脸，无需匹配，faceId: {}", faceId);
            return StageResult.skipped("人工选择的人脸，无需重新匹配");
        }

        // 3. 加载景区配置
        ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(face.getScenicId());
        context.setScenicConfig(configManager);
        log.debug("加载景区配置成功: scenicId={}", face.getScenicId());

        // 4. 加载人脸识别适配器
        IFaceBodyAdapter faceBodyAdapter = scenicService.getScenicFaceBodyAdapter(face.getScenicId());
        if (faceBodyAdapter == null) {
            log.error("无法获取人脸识别适配器，scenicId: {}", face.getScenicId());
            return StageResult.failed("人脸识别服务不可用，请稍后再试");
        }

        context.setFaceBodyAdapter(faceBodyAdapter);
        log.debug("加载人脸识别适配器成功: scenicId={}", face.getScenicId());

        return StageResult.success("上下文准备完成");
    }
}
