/**
 * AI Summary polling hook.
 *
 * forcePrompt 逻辑:
 * 1. 首次访问 / 切换到新记录, 无缓存 → forcePrompt: false
 * 2. 切换到缓存记录 → 使用缓存, 无请求
 * 3. 点击刷新（重新生成） → forcePrompt: true, 清除旧缓存
 *
 * 缓存策略 (共享 summaryCache):
 * - 完成/失败结果缓存 (带 TTL)
 * - 记录切换使用缓存优先
 * - viewData 变化时清除所有缓存
 * - 并发触发去重: 相同 key 的并发触发复用一个请求
 *
 * 安全保证:
 * - MAX_POLLING_COUNT 超时
 * - isMountedRef 卸载保护
 * - 请求所有权验证 (recordId token)
 */
import $i18n from '../../../../../locales/i18n.js';
import React from 'react';
import { generateAiSummary } from '../../../services';
import { getAliWorkNo } from '../../../../../cn-ai-agent/utils/user-utils';
import { isEditor } from '../../../../../utils/env/index.js';
import { summaryCache, buildCacheKey } from './summary-cache';
const POLLING_INTERVAL = 1000;
const MAX_POLLING_COUNT = 60;
const SUMMARY_MODE = 'aiSummary';
export function useSummaryPolling({ recordId, tableId, rowData, initialSummary, viewData, enabled = true, bizRequestConfig, }) {
    const [status, setStatus] = React.useState('idle');
    const [summary, setSummary] = React.useState('');
    const pollingTimerRef = React.useRef(null);
    const pollingCountRef = React.useRef(0);
    const currentRecordIdRef = React.useRef(null);
    const isMountedRef = React.useRef(true);
    const prevViewDataRef = React.useRef(viewData);
    const getCacheKey = React.useCallback((id) => buildCacheKey(tableId, String(id !== null && id !== void 0 ? id : ''), SUMMARY_MODE), [tableId]);
    const stopPolling = React.useCallback(() => {
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        pollingCountRef.current = 0;
    }, []);
    const clearCache = React.useCallback(() => {
        summaryCache.clear();
    }, []);
    const updateResult = React.useCallback((id, newStatus, newSummary) => {
        if (!isMountedRef.current || currentRecordIdRef.current !== id)
            return;
        setStatus(newStatus);
        setSummary(newSummary);
        summaryCache.set(getCacheKey(id), { status: newStatus, summary: newSummary });
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [tableId]);
    const poll = React.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.get({
                id: 'GenerateSummaryTimeoutPleaseTryA_308174635',
                dm: '生成总结超时，请重试',
            }));
            stopPolling();
            return;
        }
        try {
            const params = {
                tableId,
                rowId: String(targetRecordId),
                forcePrompt,
                rowData,
                userId: getAliWorkNo(),
            };
            const result = await 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.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.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.get({
                id: 'FailedToGenerateSummaryPleaseTry_1755030794',
                dm: '生成总结失败，请重试',
            }));
            stopPolling();
        }
    }, [tableId, recordId, rowData, stopPolling, updateResult, bizRequestConfig, getCacheKey]);
    const startTask = React.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 = summaryCache.get(cacheKey);
        if (forceRefresh) {
            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);
            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.useEffect(() => {
        if (prevViewDataRef.current !== viewData) {
            clearCache();
            prevViewDataRef.current = viewData;
        }
    }, [viewData, clearCache]);
    // recordId / enabled 变化 -> 启动或停止任务
    React.useEffect(() => {
        if (!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.useEffect(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false;
            stopPolling();
        };
    }, [stopPolling]);
    const refresh = React.useCallback(() => {
        if (!enabled || status === 'loading')
            return;
        startTask(true);
    }, [enabled, status, startTask]);
    return { status, summary, refresh, clearCache };
}
