package com.ycwl.basic.integration.render.service;

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.render.client.RenderJobV2Client;
import com.ycwl.basic.integration.render.dto.job.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 渲染作业集成服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RenderJobIntegrationService {

    private final RenderJobV2Client renderJobV2Client;

    private static final String SERVICE_NAME = "zt-render-worker";

    // ==================== 小程序侧接口 ====================

    /**
     * 创建预览作业（直接调用，不降级）
     */
    public CreatePreviewResponse createPreview(CreatePreviewRequest request) {
        log.debug("创建预览作业, templateId: {}, scenicId: {}", request.getTemplateId(), request.getScenicId());
        CommonResponse<CreatePreviewResponse> response = renderJobV2Client.createPreview(request);
        return handleResponse(response, "创建预览作业失败");
    }

    /**
     * 获取作业状态（带降级）
     */
    public JobStatusResponse getJobStatus(Long jobId) {
        log.debug("获取作业状态, jobId: {}", jobId);
        CommonResponse<JobStatusResponse> response = renderJobV2Client.getJobStatus(jobId);
        return handleResponse(response, "获取作业状态失败");
    }

    /**
     * 获取HLS播放列表
     * 返回M3U8格式的文本内容（不降级）
     */
    public String getHlsPlaylist(Long jobId) {
        log.debug("获取HLS播放列表, jobId: {}", jobId);
        try {
            return renderJobV2Client.getHlsPlaylist(jobId);
        } catch (Exception e) {
            log.error("获取HLS播放列表失败, jobId: {}", jobId, e);
            throw new IntegrationException(5000, "获取HLS播放列表失败: " + e.getMessage(), SERVICE_NAME);
        }
    }

    /**
     * 获取播放列表信息（带降级）
     */
    public PlaylistInfoDTO getPlaylistInfo(Long jobId) {
        log.debug("获取播放列表信息, jobId: {}", jobId);
        CommonResponse<PlaylistInfoDTO> response = renderJobV2Client.getPlaylistInfo(jobId);
        return handleResponse(response, "获取播放列表信息失败");
    }

    /**
     * 取消作业（直接调用，不降级）
     */
    public void cancelJob(Long jobId) {
        log.debug("取消作业, jobId: {}", jobId);
        CommonResponse<Void> response = renderJobV2Client.cancelJob(jobId);
        handleVoidResponse(response, "取消作业失败");
    }

    /**
     * 创建FINALIZE_MP4任务（直接调用，不降级）
     * 将所有已发布的TS片段合成为MP4文件
     *
     * @param jobId 作业ID
     * @return 任务创建结果
     * @throws IntegrationException 当前置条件不满足时抛出异常
     */
    public FinalizeMP4Response createFinalizeMP4Task(Long jobId) {
        log.debug("创建FINALIZE_MP4任务, jobId: {}", jobId);
        CommonResponse<FinalizeMP4Response> response = renderJobV2Client.createFinalizeMP4Task(jobId);
        return handleResponse(response, "创建FINALIZE_MP4任务失败");
    }

    // ==================== 管理端接口 ====================

    /**
     * 获取作业列表（不降级）
     */
    public PageResponse<RenderJobV2DTO> listJobs(Long scenicId, Long templateId, String status,
                                                  String jobType, Integer page, Integer pageSize) {
        log.debug("查询作业列表, scenicId: {}, templateId: {}, status: {}, jobType: {}, page: {}, pageSize: {}",
                scenicId, templateId, status, jobType, page, pageSize);
        CommonResponse<PageResponse<RenderJobV2DTO>> response =
                renderJobV2Client.listJobs(scenicId, templateId, status, jobType, page, pageSize);
        return handleResponse(response, "查询作业列表失败");
    }

    /**
     * 获取作业详情（带降级）
     */
    public RenderJobV2DTO getJobDetail(Long jobId) {
        log.debug("获取作业详情, jobId: {}", jobId);
        CommonResponse<RenderJobV2DTO> response = renderJobV2Client.getJobDetail(jobId);
        return handleResponse(response, "获取作业详情失败");
    }

    /**
     * 获取作业片段列表（带降级）
     */
    @SuppressWarnings("unchecked")
    public List<RenderJobSegmentV2DTO> getJobSegments(Long jobId) {
        log.debug("获取作业片段列表, jobId: {}", jobId);
        CommonResponse<List<RenderJobSegmentV2DTO>> response =
                renderJobV2Client.getJobSegments(jobId);
        return handleResponse(response, "获取作业片段列表失败");
    }

    // ==================== Helper Methods ====================

    /**
     * 处理通用响应
     */
    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.getSuccess()) {
            String msg = response != null && response.getMessage() != null ?
                    response.getMessage() : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
        return response.getData();
    }

    /**
     * 处理空响应
     */
    private void handleVoidResponse(CommonResponse<Void> response, String errorMessage) {
        if (response == null || !response.getSuccess()) {
            String msg = response != null && response.getMessage() != null ?
                    response.getMessage() : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
    }
}
