package com.competition.modules.leai.task;

import com.competition.modules.leai.service.ILeaiSyncService;
import com.competition.modules.leai.service.LeaiApiClient;
import com.competition.modules.leai.util.LeaiUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * B3 定时对账任务
 * 每 30 分钟调用 B3 接口对账，补偿 Webhook 遗漏
 * <p>
 * 查询范围：最近 2 小时内更新的作品（覆盖 2 个对账周期，确保不遗漏边界数据）
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LeaiReconcileTask {

    private final LeaiApiClient leaiApiClient;
    private final ILeaiSyncService leaiSyncService;

    /**
     * 每30分钟执行一次，初始延迟60秒
     */
    @Scheduled(fixedRate = 30 * 60 * 1000, initialDelay = 60 * 1000)
    public void reconcile() {
        log.info("[B3对账] 开始执行...");

        try {
            String updatedAfter = LeaiApiClient.getUtcTwoHoursAgoIso();

            List<Map<String, Object>> works = leaiApiClient.queryWorks(updatedAfter);
            if (works.isEmpty()) {
                log.info("[B3对账] 未查询到变更作品");
                return;
            }

            int synced = 0;
            for (Map<String, Object> work : works) {
                String workId = LeaiUtil.toString(work.get("workId"), null);
                if (workId == null) {
                    continue;
                }

                // 尝试调 B2 获取完整数据
                Map<String, Object> fullData = leaiApiClient.fetchWorkDetail(workId);
                if (fullData != null) {
                    try {
                        leaiSyncService.syncWork(workId, fullData, "B3对账");
                        synced++;
                    } catch (Exception e) {
                        log.warn("[B3对账] 同步失败: workId={}", workId, e);
                    }
                } else {
                    // B2 失败时用 B3 摘要数据做简易同步
                    try {
                        leaiSyncService.syncWork(workId, work, "B3对账(摘要)");
                        synced++;
                    } catch (Exception e) {
                        log.warn("[B3对账] 摘要同步失败: workId={}", workId, e);
                    }
                }
            }

            log.info("[B3对账] 完成: 检查 {} 个作品, 同步 {} 个", works.size(), synced);

        } catch (Exception e) {
            log.error("[B3对账] 执行异常", e);
        }
    }
}
