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

import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
import com.ycwl.basic.pipeline.core.Pipeline;
import com.ycwl.basic.pipeline.core.PipelineBuilder;
import com.ycwl.basic.face.pipeline.enums.FaceMatchingScene;
import com.ycwl.basic.face.pipeline.stages.*;
import com.ycwl.basic.service.pc.helper.ScenicConfigFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 人脸匹配Pipeline工厂
 * 负责为不同场景组装Pipeline
 *
 * 支持的场景:
 * 1. 自动人脸匹配（新用户/老用户）
 * 2. 自定义人脸匹配
 * 3. 仅识别
 */
@Slf4j
@Component
public class FaceMatchingPipelineFactory {

    // ==================== 通用 Stage（13个）====================
    @Autowired
    private PrepareContextStage prepareContextStage;
    @Autowired
    private RecordMetricsStage recordMetricsStage;
    @Autowired
    private FaceRecognitionStage faceRecognitionStage;
    @Autowired
    private FaceRecoveryStage faceRecoveryStage;
    @Autowired
    private UpdateFaceResultStage updateFaceResultStage;
    @Autowired
    private BuildSourceRelationStage buildSourceRelationStage;
    @Autowired
    private ProcessFreeSourceStage processFreeSourceStage;
    @Autowired
    private ProcessBuyStatusStage processBuyStatusStage;
    @Autowired
    private HandleVideoRecreationStage handleVideoRecreationStage;
    @Autowired
    private PersistRelationsStage persistRelationsStage;
    @Autowired
    private CreateTaskStage createTaskStage;
    @Autowired
    private SetTaskStatusStage setTaskStatusStage;
    @Autowired
    private GeneratePuzzleStage generatePuzzleStage;

    // ==================== 自定义匹配专属 Stage（6个）====================
    @Autowired
    private RecordCustomMatchMetricsStage recordCustomMatchMetricsStage;
    @Autowired
    private LoadFaceSamplesStage loadFaceSamplesStage;
    @Autowired
    private CustomFaceSearchStage customFaceSearchStage;
    @Autowired
    private LoadMatchedSamplesStage loadMatchedSamplesStage;
    @Autowired
    private FilterByTimeRangeStage filterByTimeRangeStage;
    @Autowired
    private FilterByDevicePhotoLimitStage filterByDevicePhotoLimitStage;
    @Autowired
    private DeleteOldRelationsStage deleteOldRelationsStage;
    @Autowired
    private ExpandSampleAssociationStage expandSampleAssociationStage;

    // ==================== 辅助服务 ====================
    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    /**
     * 创建打印机大屏识别试点Pipeline
     * 仅执行：识别、补救、落库、建关系
     *
     * 说明：
     * - “准备上下文”属于基础能力，默认包含
     * - “建关系”包含构建关联与持久化两步
     */
    public Pipeline<FaceMatchingContext> createPrinterTvRecognizePipeline() {
        PipelineBuilder<FaceMatchingContext> builder = new PipelineBuilder<>("PrinterTvRecognize");

        // 1. 准备上下文
        builder.addStage(prepareContextStage);

        // 2. 执行人脸识别
        builder.addStage(faceRecognitionStage);

        // 3. 人脸识别补救
        builder.addStage(faceRecoveryStage);

        // 4. 关联样本扩展
        builder.addStage(expandSampleAssociationStage);

        // 5. 更新人脸结果（落库）
        builder.addStage(updateFaceResultStage);

        // 6. 构建源文件关联（建关系）
        builder.addStage(buildSourceRelationStage);

        // 7. 持久化关联关系（建关系）
        builder.addStage(persistRelationsStage);

        log.debug("创建打印机大屏识别试点Pipeline: stageCount={}", builder.build().getStageCount());

        return builder.build();
    }

    /**
     * 创建自动人脸匹配Pipeline
     *
     * @param isNew 是否新用户
     * @return Pipeline
     */
    public Pipeline<FaceMatchingContext> createAutoMatchingPipeline(boolean isNew) {
        PipelineBuilder<FaceMatchingContext> builder = new PipelineBuilder<>("AutoMatching-" + (isNew ? "New" : "Old"));

        // 1. 准备上下文
        builder.addStage(prepareContextStage);

        // 2. 新用户设置任务状态
        if (isNew) {
            builder.addStage(setTaskStatusStage);
        }

        // 3. 记录识别次数
        builder.addStage(recordMetricsStage);

        // 4. 执行人脸识别
        builder.addStage(faceRecognitionStage);

        // 5. 人脸识别补救
        builder.addStage(faceRecoveryStage);

        // 6. 关联样本扩展
        builder.addStage(expandSampleAssociationStage);

        // 7. 更新人脸结果
        builder.addStage(updateFaceResultStage);

        // 8. 构建源文件关联
        builder.addStage(buildSourceRelationStage);

        // 9. 处理免费源文件逻辑
        builder.addStage(processFreeSourceStage);

        // 10. 处理购买状态
        builder.addStage(processBuyStatusStage);

        // 11. 处理视频重切
        builder.addStage(handleVideoRecreationStage);

        // 12. 持久化关联关系
        builder.addStage(persistRelationsStage);

        // 13. 创建任务
        builder.addStage(createTaskStage);

        // 14. 异步生成拼图模板
        builder.addStage(generatePuzzleStage);

        log.debug("创建自动人脸匹配Pipeline: isNew={}, stageCount={}", isNew, builder.build().getStageCount());

        return builder.build();
    }

    /**
     * 创建自定义人脸匹配Pipeline
     *
     * @return Pipeline
     */
    public Pipeline<FaceMatchingContext> createCustomMatchingPipeline() {
        PipelineBuilder<FaceMatchingContext> builder = new PipelineBuilder<>("CustomMatching");

        // 1. 准备上下文
        builder.addStage(prepareContextStage);

        // 2. 记录自定义匹配次数
        builder.addStage(recordCustomMatchMetricsStage);

        // 3. 加载用户选择的人脸样本
        builder.addStage(loadFaceSamplesStage);

        // 4. 根据配置执行自定义人脸搜索
        builder.addStage(customFaceSearchStage);

        // 5. 加载匹配样本实体到缓存
        builder.addStage(loadMatchedSamplesStage);

        // 6. 应用时间范围筛选
        builder.addStage(filterByTimeRangeStage);

        // 7. 应用设备照片数量限制筛选
        builder.addStage(filterByDevicePhotoLimitStage);

        // 8. 关联样本扩展
        builder.addStage(expandSampleAssociationStage);

        // 9. 更新人脸结果
        builder.addStage(updateFaceResultStage);

        // 10. 删除旧关系数据
        builder.addStage(deleteOldRelationsStage);

        // 11. 构建源文件关联
        builder.addStage(buildSourceRelationStage);

        // 12. 处理免费源文件逻辑
        builder.addStage(processFreeSourceStage);

        // 13. 处理购买状态
        builder.addStage(processBuyStatusStage);

        // 14. 处理视频重切
        builder.addStage(handleVideoRecreationStage);

        // 15. 持久化关联关系
        builder.addStage(persistRelationsStage);

        // 16. 创建任务
        builder.addStage(createTaskStage);

        log.debug("创建自定义人脸匹配Pipeline: stageCount={}", builder.build().getStageCount());

        return builder.build();
    }

    /**
     * 创建仅识别Pipeline
     * 只执行人脸识别，不处理后续业务逻辑
     *
     * @return Pipeline
     */
    public Pipeline<FaceMatchingContext> createRecognitionOnlyPipeline() {
        PipelineBuilder<FaceMatchingContext> builder = new PipelineBuilder<>("RecognitionOnly");

        // 1. 准备上下文
        builder.addStage(prepareContextStage);

        // 2. 执行人脸识别
        builder.addStage(faceRecognitionStage);

        // 3. 人脸识别补救
        builder.addStage(faceRecoveryStage);

        log.debug("创建仅识别Pipeline: stageCount={}", builder.build().getStageCount());

        return builder.build();
    }

    /**
     * 根据场景创建Pipeline
     *
     * @param scene 场景
     * @param isNew 是否新用户（仅AUTO_MATCHING场景需要）
     * @return Pipeline
     */
    public Pipeline<FaceMatchingContext> createPipeline(FaceMatchingScene scene, boolean isNew) {
        return switch (scene) {
            case AUTO_MATCHING -> createAutoMatchingPipeline(isNew);
            case CUSTOM_MATCHING -> createCustomMatchingPipeline();
            case RECOGNITION_ONLY -> createRecognitionOnlyPipeline();
            case PRINTER_TV_RECOGNIZE -> createPrinterTvRecognizePipeline();
        };
    }

    /**
     * 根据Context创建Pipeline
     *
     * @param context 上下文
     * @return Pipeline
     */
    public Pipeline<FaceMatchingContext> createPipeline(FaceMatchingContext context) {
        return createPipeline(context.getScene(), context.isNew());
    }
}
