package com.yaoai.pipeline.async;

import com.yaoai.ai.providers.model.VideoTaskResult;
import com.yaoai.ai.providers.service.SeedanceService;
import com.yaoai.domain.entity.AiTask;
import com.yaoai.domain.mapper.AiTaskMapper;
import com.yaoai.pipeline.service.ShotAssetService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class VideoTaskCompletionService {

    private final AiTaskMapper aiTaskMapper;
    private final SeedanceService seedanceService;
    private final ShotAssetService shotAssetService;
    private final VideoTransferService videoTransferService;

    /**
     * Poll one video task and update local state.
     * When provider video is ready, write the provider URL immediately so the UI can play it,
     * then transfer it to TOS asynchronously and replace the URL later.
     */
    public boolean pollOnce(AiTask task) {
        Long taskId = task.getId();
        String externalTaskId = task.getExternalTaskId();
        try {
            VideoTaskResult result = seedanceService.getTaskStatus(externalTaskId);
            String status = result.getStatus();
            log.debug("Polling video provider: taskId={}, externalId={}, status={}", taskId, externalTaskId, status);

            if ("succeeded".equals(status) || "failed".equals(status)) {
                String videoUrl = result.getVideoUrl();
                if ("succeeded".equals(status) && (videoUrl == null || videoUrl.isBlank())) {
                    log.warn("Video task succeeded but URL is empty, will retry: taskId={}, externalId={}",
                            taskId, externalTaskId);
                    return false;
                }

                AiTask done = new AiTask();
                done.setId(taskId);
                done.setStatus(status);
                if ("succeeded".equals(status)) {
                    done.setResultVideoUrl(videoUrl);
                }
                if (result.getErrorMessage() != null) {
                    done.setErrorMessage(result.getErrorMessage());
                }
                aiTaskMapper.updateById(done);

                if ("succeeded".equals(status)) {
                    shotAssetService.markVideoAssetSucceeded(task.getTenantId(), taskId, videoUrl);
                    videoTransferService.transferVideoToTos(task.getTenantId(), task.getProjectId(), taskId, videoUrl);
                } else {
                    shotAssetService.markVideoAssetFailed(task.getTenantId(), taskId, done.getErrorMessage());
                }

                log.info("Video task completed: taskId={}, status={}, url={}", taskId, status, videoUrl);
                return true;
            }

            if ("running".equals(status) && !"running".equals(task.getStatus())) {
                AiTask running = new AiTask();
                running.setId(taskId);
                running.setStatus("running");
                aiTaskMapper.updateById(running);
            }
            return false;
        } catch (Exception e) {
            log.warn("Video poll error (will retry): taskId={}, error={}", taskId, e.getMessage());
            return false;
        }
    }
}
