package com.erp.ai.scheduler;

import com.erp.ai.dto.GroupExecutionResult;
import com.erp.ai.mapper.AiAgentScheduleMapper;
import com.erp.ai.model.AiAgentSchedule;
import com.erp.ai.service.MultiAgentExecutionEngine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

import java.util.Map;

/**
 * Quartz Job — AI 스케줄 실행.
 * architecture §8.2.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MultiAgentExecutionJob implements Job {

    @Autowired
    private MultiAgentExecutionEngine executionEngine;

    @Autowired
    private AiAgentScheduleMapper scheduleMapper;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        long scheduleId = context.getMergedJobDataMap().getLong("scheduleId");
        AiAgentSchedule schedule = scheduleMapper.getById(scheduleId);
        if (schedule == null) {
            log.warn("스케줄 없음: {}", scheduleId);
            return;
        }
        log.info("AI 스케줄 실행: {} (ID: {})", schedule.getName(), schedule.getId());

        try {
            GroupExecutionResult result = executionEngine.execute(
                    schedule.getGroup_id(),
                    schedule.getInput_message(),
                    schedule.getCreated_by(),
                    null);
            scheduleMapper.markRun(schedule.getId());
            sendNotification(schedule, result);
            log.info("AI 스케줄 완료: {} - {} tokens", schedule.getName(), result.getTotalTokens());
        } catch (Exception e) {
            log.error("AI 스케줄 실패: {} - {}", schedule.getName(), e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    private void sendNotification(AiAgentSchedule schedule, GroupExecutionResult result) {
        if (schedule.getNotification() == null) return;
        try {
            // notification 은 JSON 문자열 — 단순 처리: webhook 만 RestClient.post
            // 시스템 공지/이메일은 invyone 서비스 호출 (Phase 2).
            String n = schedule.getNotification();
            if (n.contains("\"webhook\"")) {
                int idx = n.indexOf("\"webhook\"");
                int colon = n.indexOf(':', idx);
                int quoteOpen = n.indexOf('"', colon + 1);
                int quoteClose = n.indexOf('"', quoteOpen + 1);
                if (quoteOpen > 0 && quoteClose > quoteOpen) {
                    String webhook = n.substring(quoteOpen + 1, quoteClose);
                    if (webhook.startsWith("http")) {
                        RestClient.create().post().uri(webhook)
                                .body(Map.of("text",
                                        "[" + schedule.getName() + "] 실행 완료\n\n"
                                                + (result.getFinalSummary().length() > 1000
                                                        ? result.getFinalSummary().substring(0, 1000)
                                                        : result.getFinalSummary())))
                                .retrieve()
                                .toBodilessEntity();
                    }
                }
            }
        } catch (Exception e) {
            log.warn("알림 발송 실패: {}", e.getMessage());
        }
    }
}
