"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSummaryPolling = useSummaryPolling;
/**
 * AI Summary polling hook.
 *
 * forcePrompt 逻辑:
 * 1. 首次访问 / 切换到新记录, 无缓存 → forcePrompt: false
 * 2. 切换到缓存记录 → 使用缓存, 无请求
 * 3. 点击刷新（重新生成） → forcePrompt: true, 清除旧缓存
 *
 * 缓存策略 (共享 summaryCache):
 * - 完成/失败结果缓存 (带 TTL)
 * - 记录切换使用缓存优先
 * - viewData 变化时清除所有缓存
 * - 并发触发去重: 相同 key 的并发触发复用一个请求
 *
 * 安全保证:
 * - MAX_POLLING_COUNT 超时
 * - isMountedRef 卸载保护
 * - 请求所有权验证 (recordId token)
 */
const i18n_1 = __importDefault(require("../../../../../locales/i18n.js"));
const react_1 = __importDefault(require("react"));
const services_1 = require("../../../services");
const user_utils_1 = require("../../../../../cn-ai-agent/utils/user-utils");
const env_1 = require("../../../../../utils/env/index.js");
const summary_cache_1 = require("./summary-cache");
const POLLING_INTERVAL = 1000;
const MAX_POLLING_COUNT = 60;
const SUMMARY_MODE = 'aiSummary';
function useSummaryPolling({ recordId, tableId, rowData, initialSummary, viewData, enabled = true, bizRequestConfig, }) {
    const [status, setStatus] = react_1.default.useState('idle');
    const [summary, setSummary] = react_1.default.useState('');
    const pollingTimerRef = react_1.default.useRef(null);
    const pollingCountRef = react_1.default.useRef(0);
    const currentRecordIdRef = react_1.default.useRef(null);
    const isMountedRef = react_1.default.useRef(true);
    const prevViewDataRef = react_1.default.useRef(viewData);
    const getCacheKey = react_1.default.useCallback((id) => (0, summary_cache_1.buildCacheKey)(tableId, String(id !== null && id !== void 0 ? id : ''), SUMMARY_MODE), [tableId]);
    const stopPolling = react_1.default.useCallback(() => {
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        pollingCountRef.current = 0;
    }, []);
    const clearCache = react_1.default.useCallback(() => {
        summary_cache_1.summaryCache.clear();
    }, []);
    const updateResult = react_1.default.useCallback((id, newStatus, newSummary) => {
        if (!isMountedRef.current || currentRecordIdRef.current !== id)
            return;
        setStatus(newStatus);
        setSummary(newSummary);
        summary_cache_1.summaryCache.set(getCacheKey(id), { status: newStatus, summary: newSummary });
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [tableId]);
    const poll = react_1.default.useCallback(async (forcePrompt) => {
        if (!isMountedRef.current || recordId === undefined || recordId === null)
            return;
        const targetRecordId = recordId;
        if (currentRecordIdRef.current !== targetRecordId)
            return;
        pollingCountRef.current += 1;
        if (pollingCountRef.current > MAX_POLLING_COUNT) {
            updateResult(targetRecordId, 'error', i18n_1.default.get({
                id: 'GenerateSummaryTimeoutPleaseTryA_308174635',
                dm: '生成总结超时，请重试',
            }));
            stopPolling();
            return;
        }
        try {
            const params = {
                tableId,
                rowId: String(targetRecordId),
                forcePrompt,
                rowData,
                userId: (0, user_utils_1.getAliWorkNo)(),
            };
            const result = await (0, services_1.generateAiSummary)(params, bizRequestConfig);
            if (!isMountedRef.current || currentRecordIdRef.current !== targetRecordId)
                return;
            if (!(result === null || result === void 0 ? void 0 : result.success)) {
                updateResult(targetRecordId, 'error', (result === null || result === void 0 ? void 0 : result.errorMsg) ||
                    i18n_1.default.get({
                        id: 'FailedToGenerateSummaryPleaseTry_1755030794',
                        dm: '生成总结失败，请重试',
                    }));
                stopPolling();
                return;
            }
            const taskData = result.data;
            if (!taskData) {
                pollingTimerRef.current = setTimeout(() => poll(false), POLLING_INTERVAL);
                return;
            }
            switch (taskData.status) {
                case 'finish':
                    updateResult(targetRecordId, 'done', taskData.jobOutput || '');
                    stopPolling();
                    break;
                case 'failed':
                    updateResult(targetRecordId, 'error', taskData.jobOutput ||
                        i18n_1.default.get({
                            id: 'FailedToGenerateSummaryPleaseTry_1755030794',
                            dm: '生成总结失败，请重试',
                        }));
                    stopPolling();
                    break;
                default:
                    setStatus('loading');
                    pollingTimerRef.current = setTimeout(() => poll(false), POLLING_INTERVAL);
            }
        }
        catch (error) {
            if (!isMountedRef.current || currentRecordIdRef.current !== targetRecordId)
                return;
            // eslint-disable-next-line no-console
            console.error('轮询查询总结结果失败:', error);
            updateResult(targetRecordId, 'error', i18n_1.default.get({
                id: 'FailedToGenerateSummaryPleaseTry_1755030794',
                dm: '生成总结失败，请重试',
            }));
            stopPolling();
        }
    }, [tableId, recordId, rowData, stopPolling, updateResult, bizRequestConfig, getCacheKey]);
    const startTask = react_1.default.useCallback((forceRefresh) => {
        if (!enabled) {
            stopPolling();
            setStatus('idle');
            setSummary(initialSummary !== null && initialSummary !== void 0 ? initialSummary : '');
            return;
        }
        if (recordId === undefined || recordId === null) {
            setStatus('idle');
            setSummary('');
            return;
        }
        stopPolling();
        currentRecordIdRef.current = recordId;
        const cacheKey = getCacheKey(recordId);
        const cached = summary_cache_1.summaryCache.get(cacheKey);
        if (forceRefresh) {
            summary_cache_1.summaryCache.delete(cacheKey);
            setStatus('loading');
            setSummary('');
            setTimeout(() => poll(true), 0);
            return;
        }
        if (cached && (cached.status === 'done' || cached.status === 'error')) {
            setStatus(cached.status);
            setSummary(cached.summary);
            return;
        }
        if ((cached === null || cached === void 0 ? void 0 : cached.status) === 'loading') {
            setStatus('loading');
            setSummary(cached.summary);
            setTimeout(() => poll(false), 0);
            return;
        }
        if (initialSummary) {
            setStatus('done');
            setSummary(initialSummary);
            summary_cache_1.summaryCache.set(cacheKey, { status: 'done', summary: initialSummary });
            return;
        }
        setStatus('loading');
        setSummary('');
        setTimeout(() => poll(false), 0);
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [enabled, recordId, initialSummary, stopPolling, poll, tableId, getCacheKey]);
    // viewData change -> invalidate cache
    react_1.default.useEffect(() => {
        if (prevViewDataRef.current !== viewData) {
            clearCache();
            prevViewDataRef.current = viewData;
        }
    }, [viewData, clearCache]);
    // recordId / enabled 变化 -> 启动或停止任务
    react_1.default.useEffect(() => {
        if (!env_1.isEditor) {
            if (!enabled) {
                stopPolling();
                setStatus('idle');
                setSummary(initialSummary !== null && initialSummary !== void 0 ? initialSummary : '');
                return () => stopPolling();
            }
            startTask(false);
            return () => stopPolling();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [recordId, enabled]);
    // Lifecycle
    react_1.default.useEffect(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false;
            stopPolling();
        };
    }, [stopPolling]);
    const refresh = react_1.default.useCallback(() => {
        if (!enabled || status === 'loading')
            return;
        startTask(true);
    }, [enabled, status, startTask]);
    return { status, summary, refresh, clearCache };
}
