// @ts-nocheck
import { defineStore } from 'pinia';
import { debugLog } from '../app/methods/common';

export const useTaskStore = defineStore('task', {
    state: () => ({
        currentTaskId: null as string | null,
        lastEventIndex: 0,
        pollingInterval: null as number | null,
        taskStatus: 'idle' as 'idle' | 'running' | 'succeeded' | 'failed' | 'canceled',
        isPolling: false,
        pollingError: null as string | null,
        taskCreatedAt: null as number | null,
        taskUpdatedAt: null as number | null,
    }),

    getters: {
        hasActiveTask: (state) => state.currentTaskId !== null && state.taskStatus === 'running',
        isTaskCompleted: (state) => ['succeeded', 'failed', 'canceled'].includes(state.taskStatus),
    },

    actions: {
        async createTask(message: string, images: any[] = [], videos: any[] = [], conversationId: string | null = null) {
            try {
                debugLog('[Task] 创建任务:', { message, conversationId });

                const response = await fetch('/api/tasks', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message,
                        images,
                        videos,
                        conversation_id: conversationId,
                    }),
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '创建任务失败');
                }

                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.error || '创建任务失败');
                }

                this.currentTaskId = result.data.task_id;
                this.taskStatus = result.data.status;
                this.lastEventIndex = 0;
                this.taskCreatedAt = result.data.created_at;
                this.pollingError = null;

                debugLog('[Task] 任务创建成功:', result.data.task_id);

                // 立即开始轮询
                this.startPolling();

                return result.data;
            } catch (error) {
                debugLog('[Task] 创建任务失败:', error);
                throw error;
            }
        },

        async pollTaskEvents(eventHandler: (event: any) => void) {
            if (!this.currentTaskId) {
                debugLog('[Task] 没有活跃任务，停止轮询');
                this.stopPolling();
                return;
            }

            try {
                const response = await fetch(
                    `/api/tasks/${this.currentTaskId}?from=${this.lastEventIndex}`
                );

                if (!response.ok) {
                    throw new Error('轮询任务失败');
                }

                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.error || '轮询任务失败');
                }

                const data = result.data;

                // 更新任务状态
                this.taskStatus = data.status;
                this.taskUpdatedAt = data.updated_at;

                // 处理新事件
                if (data.events && data.events.length > 0) {
                    debugLog(`[Task] 收到 ${data.events.length} 个新事件`);

                    for (const event of data.events) {
                        try {
                            eventHandler(event);
                        } catch (err) {
                            console.error('[Task] 处理事件失败:', err, event);
                        }
                    }

                    this.lastEventIndex = data.next_offset;
                }

                // 如果任务已完成，停止轮询
                if (this.isTaskCompleted) {
                    debugLog('[Task] 任务已完成，停止轮询:', this.taskStatus);
                    this.stopPolling();
                }

                this.pollingError = null;
            } catch (error) {
                console.error('[Task] 轮询失败:', error);
                this.pollingError = error.message;

                // 连续失败3次后停止轮询
                if (this.pollingError) {
                    // 可以在这里添加重试逻辑
                }
            }
        },

        startPolling(eventHandler?: (event: any) => void) {
            if (this.isPolling) {
                debugLog('[Task] 轮询已在运行');
                return;
            }

            if (!this.currentTaskId) {
                debugLog('[Task] 没有任务ID，无法启动轮询');
                return;
            }

            debugLog('[Task] 启动轮询:', this.currentTaskId);
            this.isPolling = true;

            // 如果没有传入 eventHandler，从根实例获取
            const handler = eventHandler || ((window as any).__taskEventHandler);

            if (!handler) {
                console.error('[Task] 没有事件处理器，无法启动轮询');
                this.isPolling = false;
                return;
            }

            // 立即执行一次
            this.pollTaskEvents(handler);

            // 设置定时轮询（150ms 间隔，接近流式输出效果）
            this.pollingInterval = window.setInterval(() => {
                this.pollTaskEvents(handler);
            }, 150);
        },

        stopPolling() {
            if (this.pollingInterval) {
                debugLog('[Task] 停止轮询');
                clearInterval(this.pollingInterval);
                this.pollingInterval = null;
            }
            this.isPolling = false;
        },

        async cancelTask() {
            if (!this.currentTaskId) {
                return;
            }

            try {
                debugLog('[Task] 取消任务:', this.currentTaskId);

                const response = await fetch(`/api/tasks/${this.currentTaskId}/cancel`, {
                    method: 'POST',
                });

                if (!response.ok) {
                    throw new Error('取消任务失败');
                }

                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.error || '取消任务失败');
                }

                this.taskStatus = 'canceled';
                this.stopPolling();

                debugLog('[Task] 任务已取消');
            } catch (error) {
                console.error('[Task] 取消任务失败:', error);
                throw error;
            }
        },

        async loadRunningTask(conversationId: string | null = null) {
            try {
                debugLog('[Task] 查找运行中的任务');

                const response = await fetch('/api/tasks');
                if (!response.ok) {
                    throw new Error('获取任务列表失败');
                }

                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.error || '获取任务列表失败');
                }

                // 查找运行中的任务
                const runningTask = result.data.find((task: any) =>
                    task.status === 'running' &&
                    (!conversationId || task.conversation_id === conversationId)
                );

                if (runningTask) {
                    debugLog('[Task] 发现运行中的任务:', runningTask.task_id);

                    this.currentTaskId = runningTask.task_id;
                    this.taskStatus = runningTask.status;
                    this.taskCreatedAt = runningTask.created_at;
                    this.taskUpdatedAt = runningTask.updated_at;
                    this.pollingError = null;

                    // 获取任务详情，计算已处理的事件数量
                    try {
                        const detailResponse = await fetch(`/api/tasks/${runningTask.task_id}`);
                        if (detailResponse.ok) {
                            const detailResult = await detailResponse.json();
                            if (detailResult.success && detailResult.data.events) {
                                // 设置为当前事件数量，只获取新事件
                                this.lastEventIndex = detailResult.data.next_offset || detailResult.data.events.length;
                                debugLog('[Task] 设置起始偏移量:', this.lastEventIndex);
                            } else {
                                this.lastEventIndex = 0;
                            }
                        } else {
                            this.lastEventIndex = 0;
                        }
                    } catch (error) {
                        console.warn('[Task] 获取任务详情失败，从头开始:', error);
                        this.lastEventIndex = 0;
                    }

                    return runningTask;
                }

                debugLog('[Task] 没有运行中的任务');
                return null;
            } catch (error) {
                console.error('[Task] 加载运行中任务失败:', error);
                return null;
            }
        },

        clearTask() {
            debugLog('[Task] 清理任务状态');
            this.stopPolling();
            this.currentTaskId = null;
            this.lastEventIndex = 0;
            this.taskStatus = 'idle';
            this.pollingError = null;
            this.taskCreatedAt = null;
            this.taskUpdatedAt = null;
        },

        resetForNewConversation() {
            debugLog('[Task] 重置任务状态（新对话）');
            this.stopPolling();
            this.currentTaskId = null;
            this.lastEventIndex = 0;
            this.taskStatus = 'idle';
            this.pollingError = null;
        },
    },
});
