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.face.pipeline.helper.PuzzleGenerationOrchestrator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 生成拼图模板Stage
 * 负责触发景区拼图模板的异步生成任务
 *
 * 职责:
 * 1. 从context读取必要参数(scenicId, faceId, memberId, faceUrl)
 * 2. 调用puzzleOrchestrator.generateAllTemplatesAsync()触发异步生成
 * 3. 立即返回,不等待生成完成
 *
 * 业务说明:
 * - 拼图生成是异步的,不影响主流程
 * - 具体的拼图生成逻辑由PuzzleGenerationOrchestrator负责
 * - Stage只负责触发任务,符合"薄Stage,厚Service"原则
 */
@Slf4j
@Component
@StageConfig(
    stageId = "generate_puzzle",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "异步生成拼图模板",
    defaultEnabled = true
)
public class GeneratePuzzleStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private PuzzleGenerationOrchestrator puzzleOrchestrator;

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

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

        try {
            // 触发异步生成拼图模板
            puzzleOrchestrator.generateAllTemplatesAsync(scenicId, faceId, memberId, faceUrl);

            log.debug("拼图模板异步生成任务已提交: scenicId={}, faceId={}", scenicId, faceId);

            return StageResult.success("拼图模板已提交异步生成");

        } catch (Exception e) {
            log.error("提交拼图生成任务失败: scenicId={}, faceId={}", scenicId, faceId, e);
            // 拼图生成失败不影响主流程,返回降级
            return StageResult.degraded("提交拼图生成任务失败: " + e.getMessage());
        }
    }
}
