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

import com.ycwl.basic.biz.FaceStatusManager;
import com.ycwl.basic.enums.FaceCutStatus;
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.service.pc.helper.ScenicConfigFacade;
import com.ycwl.basic.service.task.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 创建任务Stage
 * 负责根据配置决定是否自动创建任务
 *
 * 职责:
 * 1. 检查face_select_first配置
 * 2. 如果配置为false，则调用taskService.autoCreateTaskByFaceId()
 * 3. 如果配置为true，则设置任务状态为2(等待用户选择)
 */
@Slf4j
@Component
@StageConfig(
    stageId = "create_task",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "根据配置创建视频任务"
)
public class CreateTaskStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    @Autowired
    private TaskService taskService;

    @Autowired
    private FaceStatusManager faceStatusManager;

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

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        Long scenicId = context.getFace().getScenicId();
        Long faceId = context.getFaceId();

        try {
            boolean faceSelectFirst = scenicConfigFacade.isFaceSelectFirst(scenicId);

            if (!faceSelectFirst) {
                // 配置为自动创建任务
                taskService.autoCreateTaskByFaceId(faceId);
                log.info("自动创建任务成功: faceId={}", faceId);
                return StageResult.success("自动创建任务成功");
            } else {
                // 配置为等待用户选择
                faceStatusManager.setFaceCutStatus(faceId, FaceCutStatus.WAITING_USER_SELECT);
                log.debug("景区配置 face_select_first=true，跳过自动创建任务: faceId={}", faceId);
                return StageResult.skipped("等待用户手动选择");
            }

        } catch (Exception e) {
            log.error("创建任务失败，faceId={}", faceId, e);
            // 任务创建失败不影响主流程，返回降级而不是失败
            return StageResult.degraded("任务创建失败: " + e.getMessage());
        }
    }
}
